1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.content.pm.cts; 18 19 import static android.Manifest.permission.INSTALL_TEST_ONLY_PACKAGE; 20 import static android.content.pm.ApplicationInfo.FLAG_HAS_CODE; 21 import static android.content.pm.ApplicationInfo.FLAG_INSTALLED; 22 import static android.content.pm.ApplicationInfo.FLAG_SYSTEM; 23 import static android.content.pm.PackageManager.GET_ACTIVITIES; 24 import static android.content.pm.PackageManager.GET_META_DATA; 25 import static android.content.pm.PackageManager.GET_PERMISSIONS; 26 import static android.content.pm.PackageManager.GET_PROVIDERS; 27 import static android.content.pm.PackageManager.GET_RECEIVERS; 28 import static android.content.pm.PackageManager.GET_SERVICES; 29 import static android.content.pm.PackageManager.MATCH_APEX; 30 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 31 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 32 import static android.content.pm.PackageManager.MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS; 33 import static android.content.pm.PackageManager.MATCH_INSTANT; 34 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 35 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 36 37 import static com.google.common.truth.Truth.assertThat; 38 import static com.google.common.truth.Truth.assertWithMessage; 39 40 import static org.junit.Assert.assertEquals; 41 import static org.junit.Assert.assertFalse; 42 import static org.junit.Assert.assertNotNull; 43 import static org.junit.Assert.assertNull; 44 import static org.junit.Assert.assertTrue; 45 import static org.junit.Assert.fail; 46 import static org.junit.Assume.assumeFalse; 47 import static org.junit.Assume.assumeTrue; 48 import static org.testng.Assert.assertThrows; 49 50 import android.annotation.NonNull; 51 import android.content.ComponentName; 52 import android.content.Context; 53 import android.content.Intent; 54 import android.content.IntentFilter; 55 import android.content.cts.MockActivity; 56 import android.content.cts.MockContentProvider; 57 import android.content.cts.MockReceiver; 58 import android.content.cts.MockService; 59 import android.content.cts.R; 60 import android.content.pm.ActivityInfo; 61 import android.content.pm.ApplicationInfo; 62 import android.content.pm.ComponentInfo; 63 import android.content.pm.InstrumentationInfo; 64 import android.content.pm.PackageInfo; 65 import android.content.pm.PackageItemInfo; 66 import android.content.pm.PackageManager; 67 import android.content.pm.PackageManager.NameNotFoundException; 68 import android.content.pm.PermissionGroupInfo; 69 import android.content.pm.PermissionInfo; 70 import android.content.pm.ProviderInfo; 71 import android.content.pm.ResolveInfo; 72 import android.content.pm.ServiceInfo; 73 import android.content.pm.Signature; 74 import android.content.res.Configuration; 75 import android.content.res.Resources; 76 import android.content.res.TypedArray; 77 import android.content.res.XmlResourceParser; 78 import android.os.Bundle; 79 import android.os.SystemClock; 80 import android.os.SystemProperties; 81 import android.os.UserHandle; 82 import android.platform.test.annotations.AppModeFull; 83 import android.text.TextUtils; 84 import android.util.Log; 85 86 import androidx.test.InstrumentationRegistry; 87 import androidx.test.runner.AndroidJUnit4; 88 89 import com.android.compatibility.common.util.SystemUtil; 90 91 import org.junit.After; 92 import org.junit.Before; 93 import org.junit.Test; 94 import org.junit.runner.RunWith; 95 import org.xmlpull.v1.XmlPullParser; 96 import org.xmlpull.v1.XmlPullParserException; 97 98 import java.io.IOException; 99 import java.util.ArrayList; 100 import java.util.Arrays; 101 import java.util.HashSet; 102 import java.util.Iterator; 103 import java.util.List; 104 import java.util.Set; 105 import java.util.function.Consumer; 106 import java.util.stream.Collectors; 107 108 /** 109 * This test is based on the declarations in AndroidManifest.xml. We create mock declarations 110 * in AndroidManifest.xml just for test of PackageManager, and there are no corresponding parts 111 * of these declarations in test project. 112 */ 113 @AppModeFull // TODO(Instant) Figure out which APIs should work. 114 @RunWith(AndroidJUnit4.class) 115 public class PackageManagerTest { 116 private static final String TAG = "PackageManagerTest"; 117 118 private Context mContext; 119 private PackageManager mPackageManager; 120 private static final String PACKAGE_NAME = "android.content.cts"; 121 private static final String CONTENT_PKG_NAME = "android.content.cts"; 122 private static final String APPLICATION_NAME = "android.content.cts.MockApplication"; 123 private static final String ACTIVITY_ACTION_NAME = "android.intent.action.PMTEST"; 124 private static final String MAIN_ACTION_NAME = "android.intent.action.MAIN"; 125 private static final String SERVICE_ACTION_NAME = 126 "android.content.pm.cts.activity.PMTEST_SERVICE"; 127 private static final String GRANTED_PERMISSION_NAME = "android.permission.INTERNET"; 128 private static final String NOT_GRANTED_PERMISSION_NAME = "android.permission.HARDWARE_TEST"; 129 private static final String ACTIVITY_NAME = "android.content.pm.cts.TestPmActivity"; 130 private static final String SERVICE_NAME = "android.content.pm.cts.TestPmService"; 131 private static final String RECEIVER_NAME = "android.content.pm.cts.PmTestReceiver"; 132 private static final String INSTRUMENT_NAME = "android.content.pm.cts.TestPmInstrumentation"; 133 private static final String CALL_ABROAD_PERMISSION_NAME = 134 "android.content.cts.CALL_ABROAD_PERMISSION"; 135 private static final String PROVIDER_NAME = "android.content.cts.MockContentProvider"; 136 private static final String PERMISSIONGROUP_NAME = "android.permission-group.COST_MONEY"; 137 private static final String PERMISSION_TREE_ROOT = 138 "android.content.cts.permission.TEST_DYNAMIC"; 139 // Number of activities/activity-alias in AndroidManifest 140 private static final int NUM_OF_ACTIVITIES_IN_MANIFEST = 12; 141 142 private static final String SHIM_APEX_PACKAGE_NAME = "com.android.apex.cts.shim"; 143 144 private static final int[] PACKAGE_INFO_MATCH_FLAGS = {MATCH_UNINSTALLED_PACKAGES, 145 MATCH_DISABLED_COMPONENTS, MATCH_SYSTEM_ONLY, MATCH_FACTORY_ONLY, MATCH_INSTANT, 146 MATCH_APEX, MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS}; 147 148 private static final String SAMPLE_APK_BASE = "/data/local/tmp/cts/content/"; 149 private static final String LONG_PACKAGE_NAME_APK = SAMPLE_APK_BASE 150 + "CtsContentLongPackageNameTestApp.apk"; 151 private static final String LONG_SHARED_USER_ID_APK = SAMPLE_APK_BASE 152 + "CtsContentLongSharedUserIdTestApp.apk"; 153 private static final String MAX_PACKAGE_NAME_APK = SAMPLE_APK_BASE 154 + "CtsContentMaxPackageNameTestApp.apk"; 155 private static final String MAX_SHARED_USER_ID_APK = SAMPLE_APK_BASE 156 + "CtsContentMaxSharedUserIdTestApp.apk"; 157 private static final String LONG_LABEL_NAME_APK = SAMPLE_APK_BASE 158 + "CtsContentLongLabelNameTestApp.apk"; 159 private static final String EMPTY_APP_PACKAGE_NAME = "android.content.cts.emptytestapp"; 160 private static final String EMPTY_APP_MAX_PACKAGE_NAME = "android.content.cts.emptytestapp27j" 161 + "EBRNRG3ozwBsGr1sVIM9U0bVTI2TdyIyeRkZgW4JrJefwNIBAmCg4AzqXiCvG6JjqA0uTCWSFu2YqAVxVd" 162 + "iRKAay19k5VFlSaM7QW9uhvlrLQqsTW01ofFzxNDbp2QfIFHZR6rebKzKBz6byQFM0DYQnYMwFWXjWkMPN" 163 + "dqkRLykoFLyBup53G68k2n8w"; 164 private static final String SHELL_PACKAGE_NAME = "com.android.shell"; 165 private static final String HELLO_WORLD_PACKAGE_NAME = "com.example.helloworld"; 166 private static final String HELLO_WORLD_APK = SAMPLE_APK_BASE + "HelloWorld5.apk"; 167 168 private static final int MAX_SAFE_LABEL_LENGTH = 1000; 169 170 @Before setup()171 public void setup() throws Exception { 172 mContext = InstrumentationRegistry.getContext(); 173 mPackageManager = mContext.getPackageManager(); 174 } 175 176 @After tearDown()177 public void tearDown() throws Exception { 178 uninstallPackage(EMPTY_APP_PACKAGE_NAME); 179 uninstallPackage(EMPTY_APP_MAX_PACKAGE_NAME); 180 uninstallPackage(HELLO_WORLD_PACKAGE_NAME); 181 } 182 183 @Test testQuery()184 public void testQuery() throws NameNotFoundException { 185 // Test query Intent Activity related methods 186 187 Intent activityIntent = new Intent(ACTIVITY_ACTION_NAME); 188 String cmpActivityName = "android.content.pm.cts.TestPmCompare"; 189 // List with different activities and the filter doesn't work, 190 List<ResolveInfo> listWithDiff = mPackageManager.queryIntentActivityOptions( 191 new ComponentName(PACKAGE_NAME, cmpActivityName), null, activityIntent, 0); 192 checkActivityInfoName(ACTIVITY_NAME, listWithDiff); 193 194 // List with the same activities to make filter work 195 List<ResolveInfo> listInSame = mPackageManager.queryIntentActivityOptions( 196 new ComponentName(PACKAGE_NAME, ACTIVITY_NAME), null, activityIntent, 0); 197 assertEquals(0, listInSame.size()); 198 199 // Test queryIntentActivities 200 List<ResolveInfo> intentActivities = 201 mPackageManager.queryIntentActivities(activityIntent, 0); 202 assertTrue(intentActivities.size() > 0); 203 checkActivityInfoName(ACTIVITY_NAME, intentActivities); 204 205 // End of Test query Intent Activity related methods 206 207 // Test queryInstrumentation 208 String targetPackage = "android"; 209 List<InstrumentationInfo> instrumentations = mPackageManager.queryInstrumentation( 210 targetPackage, 0); 211 checkInstrumentationInfoName(INSTRUMENT_NAME, instrumentations); 212 213 // Test queryIntentServices 214 Intent serviceIntent = new Intent(SERVICE_ACTION_NAME); 215 List<ResolveInfo> services = mPackageManager.queryIntentServices(serviceIntent, 216 0 /*flags*/); 217 checkServiceInfoName(SERVICE_NAME, services); 218 219 // Test queryBroadcastReceivers 220 String receiverActionName = "android.content.pm.cts.PackageManagerTest.PMTEST_RECEIVER"; 221 Intent broadcastIntent = new Intent(receiverActionName); 222 List<ResolveInfo> broadcastReceivers = new ArrayList<ResolveInfo>(); 223 broadcastReceivers = mPackageManager.queryBroadcastReceivers(broadcastIntent, 0); 224 checkActivityInfoName(RECEIVER_NAME, broadcastReceivers); 225 226 // Test queryPermissionsByGroup, queryContentProviders 227 String testPermissionsGroup = "android.permission-group.COST_MONEY"; 228 List<PermissionInfo> permissions = mPackageManager.queryPermissionsByGroup( 229 testPermissionsGroup, PackageManager.GET_META_DATA); 230 checkPermissionInfoName(CALL_ABROAD_PERMISSION_NAME, permissions); 231 232 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 233 List<ProviderInfo> providers = mPackageManager.queryContentProviders(PACKAGE_NAME, 234 appInfo.uid, 0); 235 checkProviderInfoName(PROVIDER_NAME, providers); 236 } 237 checkActivityInfoName(String expectedName, List<ResolveInfo> resolves)238 private void checkActivityInfoName(String expectedName, List<ResolveInfo> resolves) { 239 // Flag for checking if the name is contained in list array. 240 boolean isContained = false; 241 Iterator<ResolveInfo> infoIterator = resolves.iterator(); 242 String current; 243 while (infoIterator.hasNext()) { 244 current = infoIterator.next().activityInfo.name; 245 if (current.equals(expectedName)) { 246 isContained = true; 247 break; 248 } 249 } 250 assertTrue(isContained); 251 } 252 checkServiceInfoName(String expectedName, List<ResolveInfo> resolves)253 private void checkServiceInfoName(String expectedName, List<ResolveInfo> resolves) { 254 boolean isContained = false; 255 Iterator<ResolveInfo> infoIterator = resolves.iterator(); 256 String current; 257 while (infoIterator.hasNext()) { 258 current = infoIterator.next().serviceInfo.name; 259 if (current.equals(expectedName)) { 260 isContained = true; 261 break; 262 } 263 } 264 assertTrue(isContained); 265 } 266 checkPermissionInfoName(String expectedName, List<PermissionInfo> permissions)267 private void checkPermissionInfoName(String expectedName, List<PermissionInfo> permissions) { 268 List<String> names = new ArrayList<String>(); 269 for (PermissionInfo permission : permissions) { 270 names.add(permission.name); 271 } 272 boolean isContained = names.contains(expectedName); 273 assertTrue("Permission " + expectedName + " not present in " + names, isContained); 274 } 275 checkProviderInfoName(String expectedName, List<ProviderInfo> providers)276 private void checkProviderInfoName(String expectedName, List<ProviderInfo> providers) { 277 boolean isContained = false; 278 Iterator<ProviderInfo> infoIterator = providers.iterator(); 279 String current; 280 while (infoIterator.hasNext()) { 281 current = infoIterator.next().name; 282 if (current.equals(expectedName)) { 283 isContained = true; 284 break; 285 } 286 } 287 assertTrue(isContained); 288 } 289 checkInstrumentationInfoName(String expectedName, List<InstrumentationInfo> instrumentations)290 private void checkInstrumentationInfoName(String expectedName, 291 List<InstrumentationInfo> instrumentations) { 292 boolean isContained = false; 293 Iterator<InstrumentationInfo> infoIterator = instrumentations.iterator(); 294 String current; 295 while (infoIterator.hasNext()) { 296 current = infoIterator.next().name; 297 if (current.equals(expectedName)) { 298 isContained = true; 299 break; 300 } 301 } 302 assertTrue(isContained); 303 } 304 305 @Test testGetInfo()306 public void testGetInfo() throws NameNotFoundException { 307 // Test getApplicationInfo, getText 308 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 309 int discriptionRes = R.string.hello_android; 310 String expectedDisciptionRes = "Hello, Android!"; 311 CharSequence appText = mPackageManager.getText(PACKAGE_NAME, discriptionRes, appInfo); 312 assertEquals(expectedDisciptionRes, appText); 313 ComponentName activityName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME); 314 ComponentName serviceName = new ComponentName(PACKAGE_NAME, SERVICE_NAME); 315 ComponentName receiverName = new ComponentName(PACKAGE_NAME, RECEIVER_NAME); 316 ComponentName instrName = new ComponentName(PACKAGE_NAME, INSTRUMENT_NAME); 317 318 // Test getPackageInfo 319 PackageInfo packageInfo = mPackageManager.getPackageInfo(PACKAGE_NAME, 320 PackageManager.GET_INSTRUMENTATION); 321 assertEquals(PACKAGE_NAME, packageInfo.packageName); 322 323 // Test getApplicationInfo, getApplicationLabel 324 String appLabel = "Android TestCase"; 325 assertEquals(appLabel, mPackageManager.getApplicationLabel(appInfo)); 326 assertEquals(PACKAGE_NAME, appInfo.processName); 327 328 // Test getServiceInfo 329 assertEquals(SERVICE_NAME, mPackageManager.getServiceInfo(serviceName, 330 PackageManager.GET_META_DATA).name); 331 332 // Test getReceiverInfo 333 assertEquals(RECEIVER_NAME, mPackageManager.getReceiverInfo(receiverName, 0).name); 334 335 // Test getPackageArchiveInfo 336 final String apkRoute = mContext.getPackageCodePath(); 337 final String apkName = mContext.getPackageName(); 338 assertEquals(apkName, mPackageManager.getPackageArchiveInfo(apkRoute, 0).packageName); 339 340 // Test getPackagesForUid, getNameForUid 341 checkPackagesNameForUid(PACKAGE_NAME, mPackageManager.getPackagesForUid(appInfo.uid)); 342 assertEquals(PACKAGE_NAME, mPackageManager.getNameForUid(appInfo.uid)); 343 344 // Test getActivityInfo 345 assertEquals(ACTIVITY_NAME, mPackageManager.getActivityInfo(activityName, 0).name); 346 347 // Test getPackageGids 348 assertTrue(mPackageManager.getPackageGids(PACKAGE_NAME).length > 0); 349 350 // Test getPermissionInfo 351 assertEquals(GRANTED_PERMISSION_NAME, 352 mPackageManager.getPermissionInfo(GRANTED_PERMISSION_NAME, 0).name); 353 354 // Test getPermissionGroupInfo 355 assertEquals(PERMISSIONGROUP_NAME, mPackageManager.getPermissionGroupInfo( 356 PERMISSIONGROUP_NAME, 0).name); 357 358 // Test getAllPermissionGroups 359 List<PermissionGroupInfo> permissionGroups = mPackageManager.getAllPermissionGroups(0); 360 checkPermissionGroupInfoName(PERMISSIONGROUP_NAME, permissionGroups); 361 362 // Test getInstalledApplications 363 assertTrue(mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA).size() > 0); 364 365 // Test getInstalledPacakge 366 assertTrue(mPackageManager.getInstalledPackages(0).size() > 0); 367 368 // Test getInstrumentationInfo 369 assertEquals(INSTRUMENT_NAME, mPackageManager.getInstrumentationInfo(instrName, 0).name); 370 371 // Test getSystemSharedLibraryNames, in javadoc, String array and null 372 // are all OK as return value. 373 mPackageManager.getSystemSharedLibraryNames(); 374 375 // Test getLaunchIntentForPackage, Intent of activity 376 // android.content.pm.cts.TestPmCompare is set to match the condition 377 // to make sure the return of this method is not null. 378 assertEquals(MAIN_ACTION_NAME, mPackageManager.getLaunchIntentForPackage(PACKAGE_NAME) 379 .getAction()); 380 381 // Test isSafeMode. Because the test case will not run in safe mode, so 382 // the return will be false. 383 assertFalse(mPackageManager.isSafeMode()); 384 385 // Test getTargetSdkVersion 386 int expectedTargetSdk = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0) 387 .targetSdkVersion; 388 assertEquals(expectedTargetSdk, mPackageManager.getTargetSdkVersion(PACKAGE_NAME)); 389 assertThrows(PackageManager.NameNotFoundException.class, 390 () -> mPackageManager.getTargetSdkVersion( 391 "android.content.cts.non_existent_package")); 392 } 393 checkPackagesNameForUid(String expectedName, String[] uid)394 private void checkPackagesNameForUid(String expectedName, String[] uid) { 395 boolean isContained = false; 396 for (int i = 0; i < uid.length; i++) { 397 if (uid[i].equals(expectedName)) { 398 isContained = true; 399 break; 400 } 401 } 402 assertTrue(isContained); 403 } 404 checkPermissionGroupInfoName(String expectedName, List<PermissionGroupInfo> permissionGroups)405 private void checkPermissionGroupInfoName(String expectedName, 406 List<PermissionGroupInfo> permissionGroups) { 407 boolean isContained = false; 408 Iterator<PermissionGroupInfo> infoIterator = permissionGroups.iterator(); 409 String current; 410 while (infoIterator.hasNext()) { 411 current = infoIterator.next().name; 412 if (current.equals(expectedName)) { 413 isContained = true; 414 break; 415 } 416 } 417 assertTrue(isContained); 418 } 419 420 421 /** 422 * Simple test for {@link PackageManager#getPreferredActivities(List, List, String)} that tests 423 * calling it has no effect. The method is essentially a no-op because no preferred activities 424 * can be added. 425 * @see PackageManager#addPreferredActivity(IntentFilter, int, ComponentName[], ComponentName) 426 */ 427 @Test testGetPreferredActivities()428 public void testGetPreferredActivities() { 429 assertNoPreferredActivities(); 430 } 431 432 /** 433 * Helper method to test that {@link PackageManager#getPreferredActivities(List, List, String)} 434 * returns empty lists. 435 */ assertNoPreferredActivities()436 private void assertNoPreferredActivities() { 437 List<ComponentName> outActivities = new ArrayList<ComponentName>(); 438 List<IntentFilter> outFilters = new ArrayList<IntentFilter>(); 439 mPackageManager.getPreferredActivities(outFilters, outActivities, PACKAGE_NAME); 440 assertEquals(0, outActivities.size()); 441 assertEquals(0, outFilters.size()); 442 } 443 444 /** 445 * Test that calling {@link PackageManager#addPreferredActivity(IntentFilter, int, 446 * ComponentName[], ComponentName)} throws a {@link SecurityException}. 447 * <p/> 448 * The method is protected by the {@link android.permission.SET_PREFERRED_APPLICATIONS} 449 * signature permission. Even though this app declares that permission, it still should not be 450 * able to call this method because it is not signed with the platform certificate. 451 */ 452 @Test testAddPreferredActivity()453 public void testAddPreferredActivity() { 454 IntentFilter intentFilter = new IntentFilter(ACTIVITY_ACTION_NAME); 455 ComponentName[] componentName = {new ComponentName(PACKAGE_NAME, ACTIVITY_NAME)}; 456 try { 457 mPackageManager.addPreferredActivity(intentFilter, IntentFilter.MATCH_CATEGORY_HOST, 458 componentName, componentName[0]); 459 fail("addPreferredActivity unexpectedly succeeded"); 460 } catch (SecurityException e) { 461 // expected 462 } 463 assertNoPreferredActivities(); 464 } 465 466 /** 467 * Test that calling {@link PackageManager#clearPackagePreferredActivities(String)} has no 468 * effect. 469 */ 470 @Test testClearPackagePreferredActivities()471 public void testClearPackagePreferredActivities() { 472 // just ensure no unexpected exceptions are thrown, nothing else to do 473 mPackageManager.clearPackagePreferredActivities(PACKAGE_NAME); 474 } 475 checkComponentName(String expectedName, List<ComponentName> componentNames)476 private void checkComponentName(String expectedName, List<ComponentName> componentNames) { 477 boolean isContained = false; 478 Iterator<ComponentName> nameIterator = componentNames.iterator(); 479 String current; 480 while (nameIterator.hasNext()) { 481 current = nameIterator.next().getClassName(); 482 if (current.equals(expectedName)) { 483 isContained = true; 484 break; 485 } 486 } 487 assertTrue(isContained); 488 } 489 checkIntentFilterAction(String expectedName, List<IntentFilter> intentFilters)490 private void checkIntentFilterAction(String expectedName, List<IntentFilter> intentFilters) { 491 boolean isContained = false; 492 Iterator<IntentFilter> filterIterator = intentFilters.iterator(); 493 IntentFilter currentFilter; 494 String currentAction; 495 while (filterIterator.hasNext()) { 496 currentFilter = filterIterator.next(); 497 for (int i = 0; i < currentFilter.countActions(); i++) { 498 currentAction = currentFilter.getAction(i); 499 if (currentAction.equals(expectedName)) { 500 isContained = true; 501 break; 502 } 503 } 504 } 505 assertTrue(isContained); 506 } 507 508 @Test testAccessEnabledSetting()509 public void testAccessEnabledSetting() { 510 mPackageManager.setApplicationEnabledSetting(PACKAGE_NAME, 511 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); 512 assertEquals(PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 513 mPackageManager.getApplicationEnabledSetting(PACKAGE_NAME)); 514 515 ComponentName componentName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME); 516 mPackageManager.setComponentEnabledSetting(componentName, 517 PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); 518 assertEquals(PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 519 mPackageManager.getComponentEnabledSetting(componentName)); 520 } 521 522 @Test testGetApplicationEnabledSetting_notFound()523 public void testGetApplicationEnabledSetting_notFound() { 524 try { 525 mPackageManager.getApplicationEnabledSetting("this.package.does.not.exist"); 526 fail("Exception expected"); 527 } catch (IllegalArgumentException expected) { 528 } 529 } 530 531 @Test testGetIcon()532 public void testGetIcon() throws NameNotFoundException { 533 assertNotNull(mPackageManager.getApplicationIcon(PACKAGE_NAME)); 534 assertNotNull(mPackageManager.getApplicationIcon(mPackageManager.getApplicationInfo( 535 PACKAGE_NAME, 0))); 536 assertNotNull(mPackageManager 537 .getActivityIcon(new ComponentName(PACKAGE_NAME, ACTIVITY_NAME))); 538 assertNotNull(mPackageManager.getActivityIcon(new Intent(MAIN_ACTION_NAME))); 539 540 assertNotNull(mPackageManager.getDefaultActivityIcon()); 541 assertTrue(mPackageManager.isDefaultApplicationIcon( 542 mPackageManager.getDefaultActivityIcon())); 543 assertTrue(mPackageManager.isDefaultApplicationIcon(mPackageManager.getDefaultActivityIcon() 544 .getConstantState().newDrawable())); 545 546 assertFalse(mPackageManager.isDefaultApplicationIcon(mPackageManager.getActivityIcon( 547 new ComponentName(PACKAGE_NAME, ACTIVITY_NAME)))); 548 549 // getDrawable is called by ComponentInfo.loadIcon() which called by getActivityIcon() 550 // method of PackageMaganer. Here is just assurance for its functionality. 551 int iconRes = R.drawable.start; 552 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 553 assertNotNull(mPackageManager.getDrawable(PACKAGE_NAME, iconRes, appInfo)); 554 } 555 556 @Test testCheckSignaturesMatch_byPackageName()557 public void testCheckSignaturesMatch_byPackageName() { 558 // Compare the signature of this package to another package installed by this test suite 559 // (see AndroidTest.xml). Their signatures must match. 560 assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(PACKAGE_NAME, 561 "com.android.cts.stub")); 562 // This package's signature should match its own signature. 563 assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(PACKAGE_NAME, 564 PACKAGE_NAME)); 565 } 566 567 @Test testCheckSignaturesMatch_byUid()568 public void testCheckSignaturesMatch_byUid() throws NameNotFoundException { 569 // Compare the signature of this package to another package installed by this test suite 570 // (see AndroidTest.xml). Their signatures must match. 571 int uid1 = mPackageManager.getPackageInfo(PACKAGE_NAME, 0).applicationInfo.uid; 572 int uid2 = mPackageManager.getPackageInfo("com.android.cts.stub", 0).applicationInfo.uid; 573 assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(uid1, uid2)); 574 575 // A UID's signature should match its own signature. 576 assertEquals(PackageManager.SIGNATURE_MATCH, mPackageManager.checkSignatures(uid1, uid1)); 577 } 578 579 @Test testCheckSignaturesNoMatch_byPackageName()580 public void testCheckSignaturesNoMatch_byPackageName() { 581 // This test package's signature shouldn't match the system's signature. 582 assertEquals(PackageManager.SIGNATURE_NO_MATCH, mPackageManager.checkSignatures( 583 PACKAGE_NAME, "android")); 584 } 585 586 @Test testCheckSignaturesNoMatch_byUid()587 public void testCheckSignaturesNoMatch_byUid() throws NameNotFoundException { 588 // This test package's signature shouldn't match the system's signature. 589 int uid1 = mPackageManager.getPackageInfo(PACKAGE_NAME, 0).applicationInfo.uid; 590 int uid2 = mPackageManager.getPackageInfo("android", 0).applicationInfo.uid; 591 assertEquals(PackageManager.SIGNATURE_NO_MATCH, 592 mPackageManager.checkSignatures(uid1, uid2)); 593 } 594 595 @Test testCheckSignaturesUnknownPackage()596 public void testCheckSignaturesUnknownPackage() { 597 assertEquals(PackageManager.SIGNATURE_UNKNOWN_PACKAGE, mPackageManager.checkSignatures( 598 PACKAGE_NAME, "this.package.does.not.exist")); 599 } 600 601 @Test testCheckPermissionGranted()602 public void testCheckPermissionGranted() { 603 assertEquals(PackageManager.PERMISSION_GRANTED, 604 mPackageManager.checkPermission(GRANTED_PERMISSION_NAME, PACKAGE_NAME)); 605 } 606 607 @Test testCheckPermissionNotGranted()608 public void testCheckPermissionNotGranted() { 609 assertEquals(PackageManager.PERMISSION_DENIED, 610 mPackageManager.checkPermission(NOT_GRANTED_PERMISSION_NAME, PACKAGE_NAME)); 611 } 612 613 @Test testResolveMethods()614 public void testResolveMethods() { 615 // Test resolveActivity 616 Intent intent = new Intent(ACTIVITY_ACTION_NAME); 617 intent.setComponent(new ComponentName(PACKAGE_NAME, ACTIVITY_NAME)); 618 assertEquals(ACTIVITY_NAME, mPackageManager.resolveActivity(intent, 619 PackageManager.MATCH_DEFAULT_ONLY).activityInfo.name); 620 621 // Test resolveService 622 intent = new Intent(SERVICE_ACTION_NAME); 623 intent.setComponent(new ComponentName(PACKAGE_NAME, SERVICE_NAME)); 624 ResolveInfo resolveInfo = mPackageManager.resolveService(intent, 0 /*flags*/); 625 assertEquals(SERVICE_NAME, resolveInfo.serviceInfo.name); 626 627 // Test resolveContentProvider 628 String providerAuthorities = "ctstest"; 629 assertEquals(PROVIDER_NAME, 630 mPackageManager.resolveContentProvider(providerAuthorities, 0).name); 631 } 632 633 @Test testGetResources()634 public void testGetResources() throws NameNotFoundException { 635 ComponentName componentName = new ComponentName(PACKAGE_NAME, ACTIVITY_NAME); 636 int resourceId = R.xml.pm_test; 637 String xmlName = "android.content.cts:xml/pm_test"; 638 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 639 assertNotNull(mPackageManager.getXml(PACKAGE_NAME, resourceId, appInfo)); 640 assertEquals(xmlName, mPackageManager.getResourcesForActivity(componentName) 641 .getResourceName(resourceId)); 642 assertEquals(xmlName, mPackageManager.getResourcesForApplication(appInfo).getResourceName( 643 resourceId)); 644 assertEquals(xmlName, mPackageManager.getResourcesForApplication(PACKAGE_NAME) 645 .getResourceName(resourceId)); 646 } 647 648 @Test testGetResources_withConfig()649 public void testGetResources_withConfig() throws NameNotFoundException { 650 int resourceId = R.string.config_overridden_string; 651 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(PACKAGE_NAME, 0); 652 653 Configuration c1 = new Configuration(mContext.getResources().getConfiguration()); 654 c1.orientation = Configuration.ORIENTATION_PORTRAIT; 655 assertEquals("default", mPackageManager.getResourcesForApplication( 656 appInfo, c1).getString(resourceId)); 657 658 Configuration c2 = new Configuration(mContext.getResources().getConfiguration()); 659 c2.orientation = Configuration.ORIENTATION_LANDSCAPE; 660 assertEquals("landscape", mPackageManager.getResourcesForApplication( 661 appInfo, c2).getString(resourceId)); 662 } 663 664 @Test testGetPackageArchiveInfo()665 public void testGetPackageArchiveInfo() throws Exception { 666 final String apkPath = mContext.getPackageCodePath(); 667 final String apkName = mContext.getPackageName(); 668 669 final int flags = PackageManager.GET_SIGNATURES; 670 671 final PackageInfo pkgInfo = mPackageManager.getPackageArchiveInfo(apkPath, flags); 672 673 assertEquals("getPackageArchiveInfo should return the correct package name", 674 apkName, pkgInfo.packageName); 675 676 assertNotNull("Signatures should have been collected when GET_SIGNATURES flag specified", 677 pkgInfo.signatures); 678 } 679 680 @Test testGetNamesForUids_null()681 public void testGetNamesForUids_null() throws Exception { 682 assertNull(mPackageManager.getNamesForUids(null)); 683 } 684 685 @Test testGetNamesForUids_empty()686 public void testGetNamesForUids_empty() throws Exception { 687 assertNull(mPackageManager.getNamesForUids(new int[0])); 688 } 689 690 @Test testGetNamesForUids_valid()691 public void testGetNamesForUids_valid() throws Exception { 692 final int shimId = 693 mPackageManager.getApplicationInfo("com.android.cts.ctsshim", 0 /*flags*/).uid; 694 final int[] uids = new int[] { 695 1000, 696 Integer.MAX_VALUE, 697 shimId, 698 }; 699 final String[] result; 700 result = mPackageManager.getNamesForUids(uids); 701 assertNotNull(result); 702 assertEquals(3, result.length); 703 assertEquals("shared:android.uid.system", result[0]); 704 assertEquals(null, result[1]); 705 assertEquals("com.android.cts.ctsshim", result[2]); 706 } 707 708 @Test testGetPackageUid()709 public void testGetPackageUid() throws NameNotFoundException { 710 int userId = mContext.getUserId(); 711 int expectedUid = UserHandle.getUid(userId, 1000); 712 713 assertEquals(expectedUid, mPackageManager.getPackageUid("android", 0)); 714 715 int uid = mPackageManager.getApplicationInfo("com.android.cts.ctsshim", 0 /*flags*/).uid; 716 assertEquals(uid, mPackageManager.getPackageUid("com.android.cts.ctsshim", 0)); 717 } 718 719 @Test testGetPackageInfo()720 public void testGetPackageInfo() throws NameNotFoundException { 721 PackageInfo pkgInfo = mPackageManager.getPackageInfo(PACKAGE_NAME, GET_META_DATA 722 | GET_PERMISSIONS | GET_ACTIVITIES | GET_PROVIDERS | GET_SERVICES | GET_RECEIVERS); 723 assertTestPackageInfo(pkgInfo); 724 } 725 726 @Test testGetPackageInfo_notFound()727 public void testGetPackageInfo_notFound() { 728 try { 729 mPackageManager.getPackageInfo("this.package.does.not.exist", 0); 730 fail("Exception expected"); 731 } catch (NameNotFoundException expected) { 732 } 733 } 734 735 @Test testGetInstalledPackages()736 public void testGetInstalledPackages() throws Exception { 737 List<PackageInfo> pkgs = mPackageManager.getInstalledPackages(GET_META_DATA 738 | GET_PERMISSIONS | GET_ACTIVITIES | GET_PROVIDERS | GET_SERVICES | GET_RECEIVERS); 739 740 PackageInfo pkgInfo = findPackageOrFail(pkgs, PACKAGE_NAME); 741 assertTestPackageInfo(pkgInfo); 742 } 743 744 /** 745 * Asserts that the pkgInfo object correctly describes the {@link #PACKAGE_NAME} package. 746 */ assertTestPackageInfo(PackageInfo pkgInfo)747 private void assertTestPackageInfo(PackageInfo pkgInfo) { 748 // Check metadata 749 ApplicationInfo appInfo = pkgInfo.applicationInfo; 750 assertEquals(APPLICATION_NAME, appInfo.name); 751 assertEquals("Android TestCase", appInfo.loadLabel(mPackageManager)); 752 assertEquals(PACKAGE_NAME, appInfo.packageName); 753 assertTrue(appInfo.enabled); 754 // The process name defaults to the package name when not set. 755 assertEquals(PACKAGE_NAME, appInfo.processName); 756 assertEquals(0, appInfo.flags & FLAG_SYSTEM); 757 assertEquals(FLAG_INSTALLED, appInfo.flags & FLAG_INSTALLED); 758 assertEquals(FLAG_HAS_CODE, appInfo.flags & FLAG_HAS_CODE); 759 760 // Check required permissions 761 List<String> requestedPermissions = Arrays.asList(pkgInfo.requestedPermissions); 762 assertThat(requestedPermissions).containsAtLeast( 763 "android.permission.MANAGE_ACCOUNTS", 764 "android.permission.ACCESS_NETWORK_STATE", 765 "android.content.cts.permission.TEST_GRANTED"); 766 767 // Check usesPermissionFlags 768 for (int i = 0; i < pkgInfo.requestedPermissions.length; i++) { 769 final String name = pkgInfo.requestedPermissions[i]; 770 final int flags = pkgInfo.requestedPermissionsFlags[i]; 771 final boolean neverForLocation = (flags 772 & PackageInfo.REQUESTED_PERMISSION_NEVER_FOR_LOCATION) != 0; 773 if ("android.content.cts.permission.TEST_GRANTED".equals(name)) { 774 assertTrue(name + " with flags " + flags, neverForLocation); 775 } else { 776 assertFalse(name + " with flags " + flags, neverForLocation); 777 } 778 } 779 780 // Check declared permissions 781 PermissionInfo declaredPermission = (PermissionInfo) findPackageItemOrFail( 782 pkgInfo.permissions, CALL_ABROAD_PERMISSION_NAME); 783 assertEquals("Call abroad", declaredPermission.loadLabel(mPackageManager)); 784 assertEquals(PERMISSIONGROUP_NAME, declaredPermission.group); 785 assertEquals(PermissionInfo.PROTECTION_NORMAL, declaredPermission.protectionLevel); 786 787 // Check if number of activities in PackageInfo matches number of activities in manifest, 788 // to make sure no synthesized activities not in the manifest are returned. 789 assertEquals("Number of activities in manifest != Number of activities in PackageInfo", 790 NUM_OF_ACTIVITIES_IN_MANIFEST, pkgInfo.activities.length); 791 // Check activities 792 ActivityInfo activity = findPackageItemOrFail(pkgInfo.activities, ACTIVITY_NAME); 793 assertTrue(activity.enabled); 794 assertTrue(activity.exported); // Has intent filters - export by default. 795 assertEquals(PACKAGE_NAME, activity.taskAffinity); 796 assertEquals(ActivityInfo.LAUNCH_SINGLE_TOP, activity.launchMode); 797 798 // Check services 799 ServiceInfo service = findPackageItemOrFail(pkgInfo.services, SERVICE_NAME); 800 assertTrue(service.enabled); 801 assertTrue(service.exported); // Has intent filters - export by default. 802 assertEquals(PACKAGE_NAME, service.packageName); 803 assertEquals(CALL_ABROAD_PERMISSION_NAME, service.permission); 804 805 // Check ContentProviders 806 ProviderInfo provider = findPackageItemOrFail(pkgInfo.providers, PROVIDER_NAME); 807 assertTrue(provider.enabled); 808 assertFalse(provider.exported); // Don't export by default. 809 assertEquals(PACKAGE_NAME, provider.packageName); 810 assertEquals("ctstest", provider.authority); 811 812 // Check Receivers 813 ActivityInfo receiver = findPackageItemOrFail(pkgInfo.receivers, RECEIVER_NAME); 814 assertTrue(receiver.enabled); 815 assertTrue(receiver.exported); // Has intent filters - export by default. 816 assertEquals(PACKAGE_NAME, receiver.packageName); 817 } 818 819 // Tests that other packages can be queried. 820 @Test testGetInstalledPackages_OtherPackages()821 public void testGetInstalledPackages_OtherPackages() throws Exception { 822 List<PackageInfo> pkgInfos = mPackageManager.getInstalledPackages(0); 823 824 // Check a normal package. 825 PackageInfo pkgInfo = findPackageOrFail(pkgInfos, "com.android.cts.stub"); // A test package 826 assertEquals(0, pkgInfo.applicationInfo.flags & FLAG_SYSTEM); 827 828 // Check a system package. 829 pkgInfo = findPackageOrFail(pkgInfos, "android"); 830 assertEquals(FLAG_SYSTEM, pkgInfo.applicationInfo.flags & FLAG_SYSTEM); 831 } 832 833 @Test testGetInstalledApplications()834 public void testGetInstalledApplications() throws Exception { 835 List<ApplicationInfo> apps = mPackageManager.getInstalledApplications(GET_META_DATA); 836 837 ApplicationInfo app = findPackageItemOrFail( 838 apps.toArray(new ApplicationInfo[] {}), APPLICATION_NAME); 839 840 assertEquals(APPLICATION_NAME, app.name); 841 assertEquals("Android TestCase", app.loadLabel(mPackageManager)); 842 assertEquals(PACKAGE_NAME, app.packageName); 843 assertTrue(app.enabled); 844 // The process name defaults to the package name when not set. 845 assertEquals(PACKAGE_NAME, app.processName); 846 } 847 findPackageOrFail(List<PackageInfo> pkgInfos, String pkgName)848 private PackageInfo findPackageOrFail(List<PackageInfo> pkgInfos, String pkgName) { 849 for (PackageInfo pkgInfo : pkgInfos) { 850 if (pkgName.equals(pkgInfo.packageName)) { 851 return pkgInfo; 852 } 853 } 854 fail("Package not found with name " + pkgName); 855 return null; 856 } 857 findPackageItemOrFail(T[] items, String name)858 private <T extends PackageItemInfo> T findPackageItemOrFail(T[] items, String name) { 859 for (T item : items) { 860 if (name.equals(item.name)) { 861 return item; 862 } 863 } 864 fail("Package item not found with name " + name); 865 return null; 866 } 867 868 @Test testGetPackagesHoldingPermissions()869 public void testGetPackagesHoldingPermissions() { 870 List<PackageInfo> pkgInfos = mPackageManager.getPackagesHoldingPermissions( 871 new String[] { GRANTED_PERMISSION_NAME }, 0); 872 findPackageOrFail(pkgInfos, PACKAGE_NAME); 873 874 pkgInfos = mPackageManager.getPackagesHoldingPermissions( 875 new String[] { NOT_GRANTED_PERMISSION_NAME }, 0); 876 for (PackageInfo pkgInfo : pkgInfos) { 877 if (PACKAGE_NAME.equals(pkgInfo.packageName)) { 878 fail("Must not return package " + PACKAGE_NAME); 879 } 880 } 881 } 882 883 @Test testGetPermissionInfo()884 public void testGetPermissionInfo() throws NameNotFoundException { 885 // Check a normal permission. 886 String permissionName = "android.permission.INTERNET"; 887 PermissionInfo permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0); 888 assertEquals(permissionName, permissionInfo.name); 889 assertEquals(PermissionInfo.PROTECTION_NORMAL, permissionInfo.getProtection()); 890 891 // Check a dangerous (runtime) permission. 892 permissionName = "android.permission.RECORD_AUDIO"; 893 permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0); 894 assertEquals(permissionName, permissionInfo.name); 895 assertEquals(PermissionInfo.PROTECTION_DANGEROUS, permissionInfo.getProtection()); 896 assertNotNull(permissionInfo.group); 897 898 // Check a signature permission. 899 permissionName = "android.permission.MODIFY_PHONE_STATE"; 900 permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0); 901 assertEquals(permissionName, permissionInfo.name); 902 assertEquals(PermissionInfo.PROTECTION_SIGNATURE, permissionInfo.getProtection()); 903 904 // Check a special access (appop) permission. 905 permissionName = "android.permission.SYSTEM_ALERT_WINDOW"; 906 permissionInfo = mPackageManager.getPermissionInfo(permissionName, 0); 907 assertEquals(permissionName, permissionInfo.name); 908 assertEquals(PermissionInfo.PROTECTION_SIGNATURE, permissionInfo.getProtection()); 909 assertEquals(PermissionInfo.PROTECTION_FLAG_APPOP, 910 permissionInfo.getProtectionFlags() & PermissionInfo.PROTECTION_FLAG_APPOP); 911 } 912 913 @Test testGetPermissionInfo_notFound()914 public void testGetPermissionInfo_notFound() { 915 try { 916 mPackageManager.getPermissionInfo("android.permission.nonexistent.permission", 0); 917 fail("Exception expected"); 918 } catch (NameNotFoundException expected) { 919 } 920 } 921 922 @Test testGetPermissionGroupInfo()923 public void testGetPermissionGroupInfo() throws NameNotFoundException { 924 PermissionGroupInfo groupInfo = mPackageManager.getPermissionGroupInfo( 925 PERMISSIONGROUP_NAME, 0); 926 assertEquals(PERMISSIONGROUP_NAME, groupInfo.name); 927 assertEquals(PACKAGE_NAME, groupInfo.packageName); 928 assertFalse(TextUtils.isEmpty(groupInfo.loadDescription(mPackageManager))); 929 } 930 931 @Test testGetPermissionGroupInfo_notFound()932 public void testGetPermissionGroupInfo_notFound() throws NameNotFoundException { 933 try { 934 mPackageManager.getPermissionGroupInfo("this.group.does.not.exist", 0); 935 fail("Exception expected"); 936 } catch (NameNotFoundException expected) { 937 } 938 } 939 940 @Test testAddPermission_cantAddOutsideRoot()941 public void testAddPermission_cantAddOutsideRoot() { 942 PermissionInfo permissionInfo = new PermissionInfo(); 943 permissionInfo.name = "some.other.permission.tree.some-permission"; 944 permissionInfo.nonLocalizedLabel = "Some Permission"; 945 permissionInfo.protectionLevel = PermissionInfo.PROTECTION_NORMAL; 946 // Remove first 947 try { 948 mPackageManager.removePermission(permissionInfo.name); 949 } catch (SecurityException se) { 950 } 951 try { 952 mPackageManager.addPermission(permissionInfo); 953 fail("Must not add permission outside the permission tree defined in the manifest."); 954 } catch (SecurityException expected) { 955 } 956 } 957 958 @Test testAddPermission()959 public void testAddPermission() throws NameNotFoundException { 960 PermissionInfo permissionInfo = new PermissionInfo(); 961 permissionInfo.name = PERMISSION_TREE_ROOT + ".some-permission"; 962 permissionInfo.protectionLevel = PermissionInfo.PROTECTION_NORMAL; 963 permissionInfo.nonLocalizedLabel = "Some Permission"; 964 // Remove first 965 try { 966 mPackageManager.removePermission(permissionInfo.name); 967 } catch (SecurityException se) { 968 } 969 mPackageManager.addPermission(permissionInfo); 970 PermissionInfo savedInfo = mPackageManager.getPermissionInfo(permissionInfo.name, 0); 971 assertEquals(PACKAGE_NAME, savedInfo.packageName); 972 assertEquals(PermissionInfo.PROTECTION_NORMAL, savedInfo.protectionLevel); 973 } 974 975 @Test testSetSystemAppHiddenUntilInstalled()976 public void testSetSystemAppHiddenUntilInstalled() throws Exception { 977 String packageToManipulate = "com.android.cts.ctsshim"; 978 try { 979 mPackageManager.getPackageInfo(packageToManipulate, MATCH_SYSTEM_ONLY); 980 } catch (NameNotFoundException e) { 981 Log.i(TAG, "Device doesn't have " + packageToManipulate + " installed, skipping"); 982 return; 983 } 984 985 try { 986 SystemUtil.runWithShellPermissionIdentity(() -> 987 mPackageManager.setSystemAppState(packageToManipulate, 988 PackageManager.SYSTEM_APP_STATE_UNINSTALLED)); 989 SystemUtil.runWithShellPermissionIdentity(() -> 990 mPackageManager.setSystemAppState(packageToManipulate, 991 PackageManager.SYSTEM_APP_STATE_HIDDEN_UNTIL_INSTALLED_HIDDEN)); 992 993 // Setting the state to SYSTEM_APP_STATE_UNINSTALLED is an async operation in 994 // PackageManagerService with no way to listen for completion, so poll until the 995 // app is no longer found. 996 int pollingPeriodMs = 100; 997 int timeoutMs = 1000; 998 long startTimeMs = SystemClock.elapsedRealtime(); 999 boolean isAppStillVisible = true; 1000 while (SystemClock.elapsedRealtime() < startTimeMs + timeoutMs) { 1001 try { 1002 mPackageManager.getPackageInfo(packageToManipulate, MATCH_SYSTEM_ONLY); 1003 } catch (NameNotFoundException e) { 1004 // expected, stop polling 1005 isAppStillVisible = false; 1006 break; 1007 } 1008 Thread.sleep(pollingPeriodMs); 1009 } 1010 if (isAppStillVisible) { 1011 fail(packageToManipulate + " should not be found via getPackageInfo."); 1012 } 1013 } finally { 1014 SystemUtil.runWithShellPermissionIdentity(() -> 1015 mPackageManager.setSystemAppState(packageToManipulate, 1016 PackageManager.SYSTEM_APP_STATE_INSTALLED)); 1017 SystemUtil.runWithShellPermissionIdentity(() -> 1018 mPackageManager.setSystemAppState(packageToManipulate, 1019 PackageManager.SYSTEM_APP_STATE_HIDDEN_UNTIL_INSTALLED_VISIBLE)); 1020 try { 1021 mPackageManager.getPackageInfo(packageToManipulate, MATCH_SYSTEM_ONLY); 1022 } catch (NameNotFoundException e) { 1023 fail(packageToManipulate 1024 + " should be found via getPackageInfo after re-enabling."); 1025 } 1026 } 1027 } 1028 1029 @Test testGetPackageInfo_ApexSupported_ApexPackage_MatchesApex()1030 public void testGetPackageInfo_ApexSupported_ApexPackage_MatchesApex() throws Exception { 1031 assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported()); 1032 1033 PackageInfo packageInfo = mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, 1034 PackageManager.MATCH_APEX | PackageManager.MATCH_FACTORY_ONLY); 1035 assertShimApexInfoIsCorrect(packageInfo); 1036 } 1037 1038 @Test testGetPackageInfo_ApexSupported_ApexPackage_DoesNotMatchApex()1039 public void testGetPackageInfo_ApexSupported_ApexPackage_DoesNotMatchApex() { 1040 assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported()); 1041 1042 try { 1043 mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, 0 /* flags */); 1044 fail("NameNotFoundException expected"); 1045 } catch (NameNotFoundException expected) { 1046 } 1047 } 1048 1049 @Test testGetPackageInfo_ApexNotSupported_ApexPackage_MatchesApex()1050 public void testGetPackageInfo_ApexNotSupported_ApexPackage_MatchesApex() { 1051 assumeFalse("Device supports updating APEX", isUpdatingApexSupported()); 1052 1053 try { 1054 mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, PackageManager.MATCH_APEX); 1055 fail("NameNotFoundException expected"); 1056 } catch (NameNotFoundException expected) { 1057 } 1058 } 1059 1060 @Test testGetPackageInfo_ApexNotSupported_ApexPackage_DoesNotMatchApex()1061 public void testGetPackageInfo_ApexNotSupported_ApexPackage_DoesNotMatchApex() { 1062 assumeFalse("Device supports updating APEX", isUpdatingApexSupported()); 1063 1064 try { 1065 mPackageManager.getPackageInfo(SHIM_APEX_PACKAGE_NAME, 0); 1066 fail("NameNotFoundException expected"); 1067 } catch (NameNotFoundException expected) { 1068 } 1069 } 1070 1071 @Test testGetInstalledPackages_ApexSupported_MatchesApex()1072 public void testGetInstalledPackages_ApexSupported_MatchesApex() { 1073 assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported()); 1074 1075 List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages( 1076 PackageManager.MATCH_APEX | PackageManager.MATCH_FACTORY_ONLY); 1077 List<PackageInfo> shimApex = installedPackages.stream().filter( 1078 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect( 1079 Collectors.toList()); 1080 assertWithMessage("More than one shim apex found").that(shimApex).hasSize(1); 1081 assertShimApexInfoIsCorrect(shimApex.get(0)); 1082 } 1083 1084 @Test testGetInstalledPackages_ApexSupported_DoesNotMatchApex()1085 public void testGetInstalledPackages_ApexSupported_DoesNotMatchApex() { 1086 assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported()); 1087 1088 List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(0); 1089 List<PackageInfo> shimApex = installedPackages.stream().filter( 1090 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect( 1091 Collectors.toList()); 1092 assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty(); 1093 } 1094 1095 @Test testGetInstalledPackages_ApexNotSupported_MatchesApex()1096 public void testGetInstalledPackages_ApexNotSupported_MatchesApex() { 1097 assumeFalse("Device supports updating APEX", isUpdatingApexSupported()); 1098 1099 List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages( 1100 PackageManager.MATCH_APEX); 1101 List<PackageInfo> shimApex = installedPackages.stream().filter( 1102 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect( 1103 Collectors.toList()); 1104 assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty(); 1105 } 1106 1107 @Test testGetInstalledPackages_ApexNotSupported_DoesNotMatchApex()1108 public void testGetInstalledPackages_ApexNotSupported_DoesNotMatchApex() { 1109 assumeFalse("Device supports updating APEX", isUpdatingApexSupported()); 1110 1111 List<PackageInfo> installedPackages = mPackageManager.getInstalledPackages(0); 1112 List<PackageInfo> shimApex = installedPackages.stream().filter( 1113 packageInfo -> packageInfo.packageName.equals(SHIM_APEX_PACKAGE_NAME)).collect( 1114 Collectors.toList()); 1115 assertWithMessage("Shim apex wasn't supposed to be found").that(shimApex).isEmpty(); 1116 } 1117 1118 /** 1119 * Test that {@link ComponentInfo#metaData} data associated with all components in this 1120 * package will only be filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1121 */ 1122 @Test testGetInfo_noMetaData_InPackage()1123 public void testGetInfo_noMetaData_InPackage() throws Exception { 1124 final PackageInfo info = mPackageManager.getPackageInfo(PACKAGE_NAME, 1125 GET_ACTIVITIES | GET_SERVICES | GET_RECEIVERS | GET_PROVIDERS); 1126 1127 assertThat(info.applicationInfo.metaData).isNull(); 1128 Arrays.stream(info.activities).forEach(i -> assertThat(i.metaData).isNull()); 1129 Arrays.stream(info.services).forEach(i -> assertThat(i.metaData).isNull()); 1130 Arrays.stream(info.receivers).forEach(i -> assertThat(i.metaData).isNull()); 1131 Arrays.stream(info.providers).forEach(i -> assertThat(i.metaData).isNull()); 1132 } 1133 1134 /** 1135 * Test that {@link ComponentInfo#metaData} data associated with this application will only be 1136 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1137 */ 1138 @Test testGetInfo_noMetaData_InApplication()1139 public void testGetInfo_noMetaData_InApplication() throws Exception { 1140 final ApplicationInfo ai = mPackageManager.getApplicationInfo(PACKAGE_NAME, /* flags */ 0); 1141 assertThat(ai.metaData).isNull(); 1142 } 1143 1144 /** 1145 * Test that {@link ComponentInfo#metaData} data associated with this activity will only be 1146 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1147 */ 1148 @Test testGetInfo_noMetaData_InActivity()1149 public void testGetInfo_noMetaData_InActivity() throws Exception { 1150 final ComponentName componentName = new ComponentName(mContext, MockActivity.class); 1151 final ActivityInfo info = mPackageManager.getActivityInfo(componentName, /* flags */ 0); 1152 assertThat(info.metaData).isNull(); 1153 } 1154 1155 /** 1156 * Test that {@link ComponentInfo#metaData} data associated with this service will only be 1157 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1158 */ 1159 @Test testGetInfo_noMetaData_InService()1160 public void testGetInfo_noMetaData_InService() throws Exception { 1161 final ComponentName componentName = new ComponentName(mContext, MockService.class); 1162 final ServiceInfo info = mPackageManager.getServiceInfo(componentName, /* flags */ 0); 1163 assertThat(info.metaData).isNull(); 1164 } 1165 1166 /** 1167 * Test that {@link ComponentInfo#metaData} data associated with this receiver will only be 1168 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1169 */ 1170 @Test testGetInfo_noMetaData_InBroadcastReceiver()1171 public void testGetInfo_noMetaData_InBroadcastReceiver() throws Exception { 1172 final ComponentName componentName = new ComponentName(mContext, MockReceiver.class); 1173 final ActivityInfo info = mPackageManager.getReceiverInfo(componentName, /* flags */ 0); 1174 assertThat(info.metaData).isNull(); 1175 } 1176 1177 /** 1178 * Test that {@link ComponentInfo#metaData} data associated with this provider will only be 1179 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1180 */ 1181 @Test testGetInfo_noMetaData_InContentProvider()1182 public void testGetInfo_noMetaData_InContentProvider() throws Exception { 1183 final ComponentName componentName = new ComponentName(mContext, MockContentProvider.class); 1184 final ProviderInfo info = mPackageManager.getProviderInfo(componentName, /* flags */ 0); 1185 assertThat(info.metaData).isNull(); 1186 } 1187 1188 /** 1189 * Test that {@link ComponentInfo#metaData} data associated with all components in this 1190 * package will not be filled in if the {@link PackageManager#GET_META_DATA} flag is not set. 1191 */ 1192 @Test testGetInfo_checkMetaData_InPackage()1193 public void testGetInfo_checkMetaData_InPackage() throws Exception { 1194 final PackageInfo info = mPackageManager.getPackageInfo(PACKAGE_NAME, 1195 GET_META_DATA | GET_ACTIVITIES | GET_SERVICES | GET_RECEIVERS | GET_PROVIDERS); 1196 1197 checkMetaData(new PackageItemInfo(info.applicationInfo)); 1198 checkMetaData(new PackageItemInfo( 1199 findPackageItemOrFail(info.activities, "android.content.cts.MockActivity"))); 1200 checkMetaData(new PackageItemInfo( 1201 findPackageItemOrFail(info.services, "android.content.cts.MockService"))); 1202 checkMetaData(new PackageItemInfo( 1203 findPackageItemOrFail(info.receivers, "android.content.cts.MockReceiver"))); 1204 checkMetaData(new PackageItemInfo( 1205 findPackageItemOrFail(info.providers, "android.content.cts.MockContentProvider"))); 1206 } 1207 1208 /** 1209 * Test that {@link ComponentInfo#metaData} data associated with this application will only be 1210 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1211 */ 1212 @Test testGetInfo_checkMetaData_InApplication()1213 public void testGetInfo_checkMetaData_InApplication() throws Exception { 1214 final ApplicationInfo ai = mPackageManager.getApplicationInfo(PACKAGE_NAME, GET_META_DATA); 1215 checkMetaData(new PackageItemInfo(ai)); 1216 } 1217 1218 /** 1219 * Test that {@link ComponentInfo#metaData} data associated with this activity will only be 1220 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1221 */ 1222 @Test testGetInfo_checkMetaData_InActivity()1223 public void testGetInfo_checkMetaData_InActivity() throws Exception { 1224 final ComponentName componentName = new ComponentName(mContext, MockActivity.class); 1225 final ActivityInfo ai = mPackageManager.getActivityInfo(componentName, GET_META_DATA); 1226 checkMetaData(new PackageItemInfo(ai)); 1227 } 1228 1229 /** 1230 * Test that {@link ComponentInfo#metaData} data associated with this service will only be 1231 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1232 */ 1233 @Test testGetInfo_checkMetaData_InService()1234 public void testGetInfo_checkMetaData_InService() throws Exception { 1235 final ComponentName componentName = new ComponentName(mContext, MockService.class); 1236 final ServiceInfo info = mPackageManager.getServiceInfo(componentName, GET_META_DATA); 1237 checkMetaData(new PackageItemInfo(info)); 1238 } 1239 1240 /** 1241 * Test that {@link ComponentInfo#metaData} data associated with this receiver will only be 1242 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1243 */ 1244 @Test testGetInfo_checkMetaData_InBroadcastReceiver()1245 public void testGetInfo_checkMetaData_InBroadcastReceiver() throws Exception { 1246 final ComponentName componentName = new ComponentName(mContext, MockReceiver.class); 1247 final ActivityInfo info = mPackageManager.getReceiverInfo(componentName, GET_META_DATA); 1248 checkMetaData(new PackageItemInfo(info)); 1249 } 1250 1251 /** 1252 * Test that {@link ComponentInfo#metaData} data associated with this provider will only be 1253 * filled in if the {@link PackageManager#GET_META_DATA} flag is set. 1254 */ 1255 @Test testGetInfo_checkMetaData_InContentProvider()1256 public void testGetInfo_checkMetaData_InContentProvider() throws Exception { 1257 final ComponentName componentName = new ComponentName(mContext, MockContentProvider.class); 1258 final ProviderInfo info = mPackageManager.getProviderInfo(componentName, GET_META_DATA); 1259 checkMetaData(new PackageItemInfo(info)); 1260 } 1261 checkMetaData(@onNull PackageItemInfo ci)1262 private void checkMetaData(@NonNull PackageItemInfo ci) 1263 throws IOException, XmlPullParserException, NameNotFoundException { 1264 final Bundle metaData = ci.metaData; 1265 final Resources res = mPackageManager.getResourcesForApplication(ci.packageName); 1266 assertWithMessage("No meta-data found").that(metaData).isNotNull(); 1267 1268 assertThat(metaData.getString("android.content.cts.string")).isEqualTo("foo"); 1269 assertThat(metaData.getBoolean("android.content.cts.boolean")).isTrue(); 1270 assertThat(metaData.getInt("android.content.cts.integer")).isEqualTo(100); 1271 assertThat(metaData.getInt("android.content.cts.color")).isEqualTo(0xff000000); 1272 assertThat(metaData.getFloat("android.content.cts.float")).isEqualTo(100.1f); 1273 assertThat(metaData.getInt("android.content.cts.reference")).isEqualTo(R.xml.metadata); 1274 1275 XmlResourceParser xml = null; 1276 TypedArray a = null; 1277 try { 1278 xml = ci.loadXmlMetaData(mPackageManager, "android.content.cts.reference"); 1279 assertThat(xml).isNotNull(); 1280 1281 int type; 1282 while ((type = xml.next()) != XmlPullParser.START_TAG 1283 && type != XmlPullParser.END_DOCUMENT) { 1284 // Seek parser to start tag. 1285 } 1286 assertThat(type).isEqualTo(XmlPullParser.START_TAG); 1287 assertThat(xml.getName()).isEqualTo("thedata"); 1288 1289 assertThat(xml.getAttributeValue(null, "rawText")).isEqualTo("some raw text"); 1290 assertThat(xml.getAttributeIntValue(null, "rawColor", 0)).isEqualTo(0xffffff00); 1291 assertThat(xml.getAttributeValue(null, "rawColor")).isEqualTo("#ffffff00"); 1292 1293 a = res.obtainAttributes(xml, new int[] {android.R.attr.text, android.R.attr.color}); 1294 assertThat(a.getString(0)).isEqualTo("metadata text"); 1295 assertThat(a.getColor(1, 0)).isEqualTo(0xffff0000); 1296 assertThat(a.getString(1)).isEqualTo("#ffff0000"); 1297 } finally { 1298 if (a != null) { 1299 a.recycle(); 1300 } 1301 if (xml != null) { 1302 xml.close(); 1303 } 1304 } 1305 } 1306 1307 @Test testGetApplicationInfo_ApexSupported_MatchesApex()1308 public void testGetApplicationInfo_ApexSupported_MatchesApex() throws Exception { 1309 assumeTrue("Device doesn't support updating APEX", isUpdatingApexSupported()); 1310 1311 ApplicationInfo ai = mPackageManager.getApplicationInfo( 1312 SHIM_APEX_PACKAGE_NAME, PackageManager.MATCH_APEX); 1313 assertThat(ai.sourceDir).isEqualTo("/system/apex/com.android.apex.cts.shim.apex"); 1314 assertThat(ai.publicSourceDir).isEqualTo(ai.sourceDir); 1315 assertThat(ai.flags & ApplicationInfo.FLAG_SYSTEM).isEqualTo(ApplicationInfo.FLAG_SYSTEM); 1316 assertThat(ai.flags & ApplicationInfo.FLAG_INSTALLED) 1317 .isEqualTo(ApplicationInfo.FLAG_INSTALLED); 1318 } 1319 1320 @Test testGetApplicationInfo_icon_MatchesUseRoundIcon()1321 public void testGetApplicationInfo_icon_MatchesUseRoundIcon() throws Exception { 1322 installPackage(HELLO_WORLD_APK); 1323 final boolean useRoundIcon = mContext.getResources().getBoolean( 1324 mContext.getResources().getIdentifier("config_useRoundIcon", "bool", "android")); 1325 final ApplicationInfo info = mPackageManager.getApplicationInfo(HELLO_WORLD_PACKAGE_NAME, 1326 0 /*flags*/); 1327 assertThat(info.icon).isEqualTo((useRoundIcon ? info.roundIconRes : info.iconRes)); 1328 } 1329 isUpdatingApexSupported()1330 private boolean isUpdatingApexSupported() { 1331 return SystemProperties.getBoolean("ro.apex.updatable", false); 1332 } 1333 assertShimApexInfoIsCorrect(PackageInfo packageInfo)1334 private static void assertShimApexInfoIsCorrect(PackageInfo packageInfo) { 1335 assertThat(packageInfo.packageName).isEqualTo(SHIM_APEX_PACKAGE_NAME); 1336 assertThat(packageInfo.getLongVersionCode()).isEqualTo(1); 1337 assertThat(packageInfo.isApex).isTrue(); 1338 assertThat(packageInfo.applicationInfo.sourceDir).isEqualTo( 1339 "/system/apex/com.android.apex.cts.shim.apex"); 1340 assertThat(packageInfo.applicationInfo.publicSourceDir) 1341 .isEqualTo(packageInfo.applicationInfo.sourceDir); 1342 // Verify that legacy mechanism for handling signatures is supported. 1343 Signature[] pastSigningCertificates = 1344 packageInfo.signingInfo.getSigningCertificateHistory(); 1345 assertThat(packageInfo.signatures) 1346 .asList().containsExactly((Object[]) pastSigningCertificates); 1347 } 1348 1349 /** 1350 * Runs a test for all combinations of a set of flags 1351 * @param flagValues Which flags to use 1352 * @param test The test 1353 */ runTestWithFlags(int[] flagValues, Consumer<Integer> test)1354 public void runTestWithFlags(int[] flagValues, Consumer<Integer> test) { 1355 for (int i = 0; i < (1 << flagValues.length); i++) { 1356 int flags = 0; 1357 for (int j = 0; j < flagValues.length; j++) { 1358 if ((i & (1 << j)) != 0) { 1359 flags |= flagValues[j]; 1360 } 1361 } 1362 try { 1363 test.accept(flags); 1364 } catch (Throwable t) { 1365 throw new AssertionError( 1366 "Test failed for flags 0x" + String.format("%08x", flags), t); 1367 } 1368 } 1369 } 1370 1371 /** 1372 * Test that the MATCH_FACTORY_ONLY flag doesn't add new package names in the result of 1373 * getInstalledPackages. 1374 */ 1375 @Test testGetInstalledPackages_WithFactoryFlag_IsSubset()1376 public void testGetInstalledPackages_WithFactoryFlag_IsSubset() { 1377 runTestWithFlags(PACKAGE_INFO_MATCH_FLAGS, 1378 this::testGetInstalledPackages_WithFactoryFlag_IsSubset); 1379 } testGetInstalledPackages_WithFactoryFlag_IsSubset(int flags)1380 public void testGetInstalledPackages_WithFactoryFlag_IsSubset(int flags) { 1381 List<PackageInfo> packageInfos = mPackageManager.getInstalledPackages(flags); 1382 List<PackageInfo> packageInfos2 = mPackageManager.getInstalledPackages( 1383 flags | MATCH_FACTORY_ONLY); 1384 Set<String> supersetNames = 1385 packageInfos.stream().map(pi -> pi.packageName).collect(Collectors.toSet()); 1386 1387 for (PackageInfo pi : packageInfos2) { 1388 if (!supersetNames.contains(pi.packageName)) { 1389 throw new AssertionError( 1390 "The subset contains packages that the superset doesn't contain."); 1391 } 1392 } 1393 } 1394 1395 /** 1396 * Test that the MATCH_FACTORY_ONLY flag filters out all non-system packages in the result of 1397 * getInstalledPackages. 1398 */ 1399 @Test testGetInstalledPackages_WithFactoryFlag_ImpliesSystem()1400 public void testGetInstalledPackages_WithFactoryFlag_ImpliesSystem() { 1401 runTestWithFlags(PACKAGE_INFO_MATCH_FLAGS, 1402 this::testGetInstalledPackages_WithFactoryFlag_ImpliesSystem); 1403 } testGetInstalledPackages_WithFactoryFlag_ImpliesSystem(int flags)1404 public void testGetInstalledPackages_WithFactoryFlag_ImpliesSystem(int flags) { 1405 List<PackageInfo> packageInfos = 1406 mPackageManager.getInstalledPackages(flags | MATCH_FACTORY_ONLY); 1407 for (PackageInfo pi : packageInfos) { 1408 if (!pi.applicationInfo.isSystemApp()) { 1409 throw new AssertionError(pi.packageName + " is not a system app."); 1410 } 1411 } 1412 } 1413 1414 /** 1415 * Test that the MATCH_FACTORY_ONLY flag doesn't add the same package multiple times since there 1416 * may be multiple versions of a system package on the device. 1417 */ 1418 @Test testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates()1419 public void testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates() { 1420 runTestWithFlags(PACKAGE_INFO_MATCH_FLAGS, 1421 this::testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates); 1422 } 1423 1424 // TODO(b/200519752): Remove once the bug is fixed containsUpdatedApex()1425 private boolean containsUpdatedApex() { 1426 List<PackageInfo> installedApexPackages = 1427 mPackageManager.getInstalledPackages(PackageManager.MATCH_APEX); 1428 return installedApexPackages.stream().anyMatch( 1429 p -> p.applicationInfo.sourceDir.startsWith("/data/apex")); 1430 } 1431 testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates(int flags)1432 public void testGetInstalledPackages_WithFactoryFlag_ContainsNoDuplicates(int flags) { 1433 // TODO(b/200519752): Due to the bug, if there are updated APEX modules, then test will fail 1434 // for flag: 0x40002000 and its superset. Skip under that specific condition. 1435 int flagToSkip = MATCH_UNINSTALLED_PACKAGES | MATCH_APEX; 1436 if (containsUpdatedApex() && (flags & flagToSkip) == flagToSkip) { 1437 // Return silently so that the test still gets run for other flag combination. 1438 return; 1439 } 1440 1441 List<PackageInfo> packageInfos = 1442 mPackageManager.getInstalledPackages(flags | MATCH_FACTORY_ONLY); 1443 Set<String> foundPackages = new HashSet<>(); 1444 for (PackageInfo pi : packageInfos) { 1445 if (foundPackages.contains(pi.packageName)) { 1446 throw new AssertionError(pi.packageName + " is listed at least twice."); 1447 } 1448 foundPackages.add(pi.packageName); 1449 } 1450 } 1451 1452 @Test testInstallTestOnlyPackagePermission_onlyGrantedToShell()1453 public void testInstallTestOnlyPackagePermission_onlyGrantedToShell() { 1454 List<PackageInfo> packages = mPackageManager.getPackagesHoldingPermissions( 1455 new String[]{INSTALL_TEST_ONLY_PACKAGE}, /* flags= */ 0); 1456 1457 assertThat(packages).hasSize(1); 1458 assertThat(packages.get(0).packageName).isEqualTo(SHELL_PACKAGE_NAME); 1459 } 1460 1461 @Test testInstall_withLongPackageName_fail()1462 public void testInstall_withLongPackageName_fail() { 1463 assertThat(installPackage(LONG_PACKAGE_NAME_APK)).isFalse(); 1464 } 1465 1466 @Test testInstall_withLongSharedUserId_fail()1467 public void testInstall_withLongSharedUserId_fail() { 1468 assertThat(installPackage(LONG_SHARED_USER_ID_APK)).isFalse(); 1469 } 1470 1471 @Test testInstall_withMaxPackageName_success()1472 public void testInstall_withMaxPackageName_success() { 1473 assertThat(installPackage(MAX_PACKAGE_NAME_APK)).isTrue(); 1474 } 1475 1476 @Test testInstall_withMaxSharedUserId_success()1477 public void testInstall_withMaxSharedUserId_success() { 1478 assertThat(installPackage(MAX_SHARED_USER_ID_APK)).isTrue(); 1479 } 1480 installPackage(String apkPath)1481 private boolean installPackage(String apkPath) { 1482 return SystemUtil.runShellCommand("pm install -t " + apkPath).equals("Success\n"); 1483 } 1484 uninstallPackage(String packageName)1485 private void uninstallPackage(String packageName) { 1486 SystemUtil.runShellCommand("pm uninstall " + packageName); 1487 } 1488 1489 @Test loadApplicationLabel_withLongLabelName_truncated()1490 public void loadApplicationLabel_withLongLabelName_truncated() throws Exception { 1491 assertThat(installPackage(LONG_LABEL_NAME_APK)).isTrue(); 1492 final ApplicationInfo info = mPackageManager.getApplicationInfo( 1493 EMPTY_APP_PACKAGE_NAME, 0 /* flags */); 1494 final CharSequence resLabel = mPackageManager.getText( 1495 EMPTY_APP_PACKAGE_NAME, info.labelRes, info); 1496 1497 assertThat(resLabel.length()).isGreaterThan(MAX_SAFE_LABEL_LENGTH); 1498 assertThat(info.loadLabel(mPackageManager).length()).isEqualTo(MAX_SAFE_LABEL_LENGTH); 1499 } 1500 1501 @Test loadComponentLabel_withLongLabelName_truncated()1502 public void loadComponentLabel_withLongLabelName_truncated() throws Exception { 1503 assertThat(installPackage(LONG_LABEL_NAME_APK)).isTrue(); 1504 final ComponentName componentName = ComponentName.createRelative( 1505 EMPTY_APP_PACKAGE_NAME, ".MockActivity"); 1506 final ApplicationInfo appInfo = mPackageManager.getApplicationInfo( 1507 EMPTY_APP_PACKAGE_NAME, 0 /* flags */); 1508 final ActivityInfo activityInfo = mPackageManager.getActivityInfo( 1509 componentName, 0 /* flags */); 1510 final CharSequence resLabel = mPackageManager.getText( 1511 EMPTY_APP_PACKAGE_NAME, activityInfo.labelRes, appInfo); 1512 1513 assertThat(resLabel.length()).isGreaterThan(MAX_SAFE_LABEL_LENGTH); 1514 assertThat(activityInfo.loadLabel(mPackageManager).length()) 1515 .isEqualTo(MAX_SAFE_LABEL_LENGTH); 1516 } 1517 } 1518