Debian Codegraph @

core/java/android/app/ApplicationPackageManager.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2010 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.app;
18
19 import static android.app.admin.DevicePolicyResources.Drawables.Style.SOLID_COLORED;
20 import static android.app.admin.DevicePolicyResources.Drawables.Style.SOLID_NOT_COLORED;
21 import static android.app.admin.DevicePolicyResources.Drawables.WORK_PROFILE_ICON;
22 import static android.app.admin.DevicePolicyResources.Drawables.WORK_PROFILE_ICON_BADGE;
23 import static android.app.admin.DevicePolicyResources.UNDEFINED;
24 import static android.content.pm.Checksum.TYPE_PARTIAL_MERKLE_ROOT_1M_SHA256;
25 import static android.content.pm.Checksum.TYPE_PARTIAL_MERKLE_ROOT_1M_SHA512;
26 import static android.content.pm.Checksum.TYPE_WHOLE_MD5;
27 import static android.content.pm.Checksum.TYPE_WHOLE_MERKLE_ROOT_4K_SHA256;
28 import static android.content.pm.Checksum.TYPE_WHOLE_SHA1;
29 import static android.content.pm.Checksum.TYPE_WHOLE_SHA256;
30 import static android.content.pm.Checksum.TYPE_WHOLE_SHA512;
31
32 import android.annotation.CallbackExecutor;
33 import android.annotation.DrawableRes;
34 import android.annotation.NonNull;
35 import android.annotation.Nullable;
36 import android.annotation.StringRes;
37 import android.annotation.UserIdInt;
38 import android.annotation.XmlRes;
39 import android.app.admin.DevicePolicyManager;
40 import android.app.role.RoleManager;
41 import android.compat.annotation.UnsupportedAppUsage;
42 import android.content.ComponentName;
43 import android.content.ContentResolver;
44 import android.content.Context;
45 import android.content.Intent;
46 import android.content.IntentFilter;
47 import android.content.IntentSender;
48 import android.content.pm.ActivityInfo;
49 import android.content.pm.ApkChecksum;
50 import android.content.pm.ApplicationInfo;
51 import android.content.pm.ChangedPackages;
52 import android.content.pm.Checksum;
53 import android.content.pm.ComponentInfo;
54 import android.content.pm.FeatureInfo;
55 import android.content.pm.IOnChecksumsReadyListener;
56 import android.content.pm.IPackageDataObserver;
57 import android.content.pm.IPackageDeleteObserver;
58 import android.content.pm.IPackageManager;
59 import android.content.pm.IPackageMoveObserver;
60 import android.content.pm.IPackageStatsObserver;
61 import android.content.pm.InstallSourceInfo;
62 import android.content.pm.InstantAppInfo;
63 import android.content.pm.InstrumentationInfo;
64 import android.content.pm.IntentFilterVerificationInfo;
65 import android.content.pm.KeySet;
66 import android.content.pm.ModuleInfo;
67 import android.content.pm.PackageInfo;
68 import android.content.pm.PackageInstaller;
69 import android.content.pm.PackageItemInfo;
70 import android.content.pm.PackageManager;
71 import android.content.pm.ParceledListSlice;
72 import android.content.pm.PermissionGroupInfo;
73 import android.content.pm.PermissionInfo;
74 import android.content.pm.ProviderInfo;
75 import android.content.pm.ResolveInfo;
76 import android.content.pm.ServiceInfo;
77 import android.content.pm.SharedLibraryInfo;
78 import android.content.pm.SuspendDialogInfo;
79 import android.content.pm.VerifierDeviceIdentity;
80 import android.content.pm.VersionedPackage;
81 import android.content.pm.dex.ArtManager;
82 import android.content.res.Configuration;
83 import android.content.res.Resources;
84 import android.content.res.XmlResourceParser;
85 import android.graphics.Bitmap;
86 import android.graphics.Canvas;
87 import android.graphics.Rect;
88 import android.graphics.drawable.BitmapDrawable;
89 import android.graphics.drawable.Drawable;
90 import android.graphics.drawable.LayerDrawable;
91 import android.os.Build;
92 import android.os.Bundle;
93 import android.os.Handler;
94 import android.os.Looper;
95 import android.os.Message;
96 import android.os.ParcelableException;
97 import android.os.PersistableBundle;
98 import android.os.Process;
99 import android.os.RemoteException;
100 import android.os.StrictMode;
101 import android.os.SystemProperties;
102 import android.os.UserHandle;
103 import android.os.UserManager;
104 import android.os.storage.StorageManager;
105 import android.os.storage.VolumeInfo;
106 import android.permission.PermissionControllerManager;
107 import android.permission.PermissionManager;
108 import android.provider.Settings;
109 import android.system.ErrnoException;
110 import android.system.Os;
111 import android.system.OsConstants;
112 import android.system.StructStat;
113 import android.text.TextUtils;
114 import android.util.ArrayMap;
115 import android.util.ArraySet;
116 import android.util.LauncherIcons;
117 import android.util.Log;
118
119 import com.android.internal.annotations.GuardedBy;
120 import com.android.internal.annotations.Immutable;
121 import com.android.internal.annotations.VisibleForTesting;
122 import com.android.internal.os.SomeArgs;
123 import com.android.internal.util.UserIcons;
124
125 import dalvik.system.VMRuntime;
126
127 import libcore.util.EmptyArray;
128
129 import java.lang.ref.WeakReference;
130 import java.security.cert.Certificate;
131 import java.security.cert.CertificateEncodingException;
132 import java.security.cert.X509Certificate;
133 import java.util.ArrayList;
134 import java.util.Arrays;
135 import java.util.Collections;
136 import java.util.Iterator;
137 import java.util.List;
138 import java.util.Objects;
139 import java.util.Set;
140 import java.util.concurrent.Executor;
141 import java.util.function.Consumer;
142
143 /** @hide */
144 public class ApplicationPackageManager extends PackageManager {
145 private static final String TAG = "ApplicationPackageManager";
146 private static final boolean DEBUG_ICONS = false;
147
148 private static final int DEFAULT_EPHEMERAL_COOKIE_MAX_SIZE_BYTES = 16384; // 16KB
149
150 // Default flags to use with PackageManager when no flags are given.
151 private static final int sDefaultFlags = GET_SHARED_LIBRARY_FILES;
152
153 /** Default set of checksums - includes all available checksums.
154 * @see PackageManager#requestChecksums */
155 private static final int DEFAULT_CHECKSUMS =
156 TYPE_WHOLE_MERKLE_ROOT_4K_SHA256 | TYPE_WHOLE_MD5 | TYPE_WHOLE_SHA1 | TYPE_WHOLE_SHA256
157 | TYPE_WHOLE_SHA512 | TYPE_PARTIAL_MERKLE_ROOT_1M_SHA256
158 | TYPE_PARTIAL_MERKLE_ROOT_1M_SHA512;
159
160 // Name of the resource which provides background permission button string
161 public static final String APP_PERMISSION_BUTTON_ALLOW_ALWAYS =
162 "app_permission_button_allow_always";
163
164 // Name of the package which the permission controller's resources are in.
165 public static final String PERMISSION_CONTROLLER_RESOURCE_PACKAGE =
166 "com.android.permissioncontroller";
167
168 private volatile UserManager mUserManager;
169 private volatile PermissionManager mPermissionManager;
170 private volatile PackageInstaller mInstaller;
171 private volatile ArtManager mArtManager;
172 private volatile DevicePolicyManager mDevicePolicyManager;
173 private volatile String mPermissionsControllerPackageName;
174
175 @GuardedBy("mDelegates")
176 private final ArrayList<MoveCallbackDelegate> mDelegates = new ArrayList<>();
177
178 UserManager getUserManager() {
179 if (mUserManager == null) {
180 mUserManager = UserManager.get(mContext);
181 }
182 return mUserManager;
183 }
184
185 DevicePolicyManager getDevicePolicyManager() {
186 if (mDevicePolicyManager == null) {
187 mDevicePolicyManager = mContext.getSystemService(DevicePolicyManager.class);
188 }
189 return mDevicePolicyManager;
190 }
191
192 private PermissionManager getPermissionManager() {
193 if (mPermissionManager == null) {
194 mPermissionManager = mContext.getSystemService(PermissionManager.class);
195 }
196 return mPermissionManager;
197 }
198
199 @Override
200 public int getUserId() {
201 return mContext.getUserId();
202 }
203
204 @Override
205 public PackageInfo getPackageInfo(String packageName, int flags)
206 throws NameNotFoundException {
207 return getPackageInfo(packageName, PackageInfoFlags.of(flags));
208 }
209
210 @Override
211 public PackageInfo getPackageInfo(String packageName, PackageInfoFlags flags)
212 throws NameNotFoundException {
213 return getPackageInfoAsUser(packageName, flags, getUserId());
214 }
215
216 @Override
217 public PackageInfo getPackageInfo(VersionedPackage versionedPackage, int flags)
218 throws NameNotFoundException {
219 return getPackageInfo(versionedPackage, PackageInfoFlags.of(flags));
220 }
221
222 @Override
223 public PackageInfo getPackageInfo(VersionedPackage versionedPackage, PackageInfoFlags flags)
224 throws NameNotFoundException {
225 final int userId = getUserId();
226 try {
227 PackageInfo pi = mPM.getPackageInfoVersioned(versionedPackage,
228 updateFlagsForPackage(flags.getValue(), userId), userId);
229 if (pi != null) {
230 return pi;
231 }
232 } catch (RemoteException e) {
233 throw e.rethrowFromSystemServer();
234 }
235 throw new NameNotFoundException(versionedPackage.toString());
236 }
237
238 @Override
239 public PackageInfo getPackageInfoAsUser(String packageName, int flags, int userId)
240 throws NameNotFoundException {
241 return getPackageInfoAsUser(packageName, PackageInfoFlags.of(flags), userId);
242 }
243
244 @Override
245 public PackageInfo getPackageInfoAsUser(String packageName, PackageInfoFlags flags, int userId)
246 throws NameNotFoundException {
247 PackageInfo pi =
248 getPackageInfoAsUserCached(
249 packageName,
250 updateFlagsForPackage(flags.getValue(), userId),
251 userId);
252 if (pi == null) {
253 throw new NameNotFoundException(packageName);
254 }
255 return pi;
256 }
257
258 @Override
259 public String[] currentToCanonicalPackageNames(String[] names) {
260 try {
261 return mPM.currentToCanonicalPackageNames(names);
262 } catch (RemoteException e) {
263 throw e.rethrowFromSystemServer();
264 }
265 }
266
267 @Override
268 public String[] canonicalToCurrentPackageNames(String[] names) {
269 try {
270 return mPM.canonicalToCurrentPackageNames(names);
271 } catch (RemoteException e) {
272 throw e.rethrowFromSystemServer();
273 }
274 }
275
276 @Override
277 public Intent getLaunchIntentForPackage(String packageName) {
278 // First see if the package has an INFO activity; the existence of
279 // such an activity is implied to be the desired front-door for the
280 // overall package (such as if it has multiple launcher entries).
281 Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
282 intentToResolve.addCategory(Intent.CATEGORY_INFO);
283 intentToResolve.setPackage(packageName);
284 List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0);
285
286 // Otherwise, try to find a main launcher activity.
287 if (ris == null || ris.size() <= 0) {
288 // reuse the intent instance
289 intentToResolve.removeCategory(Intent.CATEGORY_INFO);
290 intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
291 intentToResolve.setPackage(packageName);
292 ris = queryIntentActivities(intentToResolve, 0);
293 }
294 if (ris == null || ris.size() <= 0) {
295 return null;
296 }
297 Intent intent = new Intent(intentToResolve);
298 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
299 intent.setClassName(ris.get(0).activityInfo.packageName,
300 ris.get(0).activityInfo.name);
301 return intent;
302 }
303
304 @Override
305 public Intent getLeanbackLaunchIntentForPackage(String packageName) {
306 return getLaunchIntentForPackageAndCategory(packageName, Intent.CATEGORY_LEANBACK_LAUNCHER);
307 }
308
309 @Override
310 public Intent getCarLaunchIntentForPackage(String packageName) {
311 return getLaunchIntentForPackageAndCategory(packageName, Intent.CATEGORY_CAR_LAUNCHER);
312 }
313
314 private Intent getLaunchIntentForPackageAndCategory(String packageName, String category) {
315 // Try to find a main launcher activity for the given categories.
316 Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
317 intentToResolve.addCategory(category);
318 intentToResolve.setPackage(packageName);
319 List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0);
320
321 if (ris == null || ris.size() <= 0) {
322 return null;
323 }
324 Intent intent = new Intent(intentToResolve);
325 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
326 intent.setClassName(ris.get(0).activityInfo.packageName,
327 ris.get(0).activityInfo.name);
328 return intent;
329 }
330
331 @Override
332 public @NonNull IntentSender getLaunchIntentSenderForPackage(@NonNull String packageName) {
333 try {
334 return mPM.getLaunchIntentSenderForPackage(packageName, mContext.getPackageName(),
335 mContext.getAttributionTag(), getUserId());
336 } catch (RemoteException e) {
337 throw e.rethrowFromSystemServer();
338 }
339 }
340
341 @Override
342 public int[] getPackageGids(String packageName) throws NameNotFoundException {
343 return getPackageGids(packageName, 0);
344 }
345
346 @Override
347 public int[] getPackageGids(String packageName, int flags)
348 throws NameNotFoundException {
349 return getPackageGids(packageName, PackageInfoFlags.of(flags));
350 }
351
352 @Override
353 public int[] getPackageGids(String packageName, PackageInfoFlags flags)
354 throws NameNotFoundException {
355 final int userId = getUserId();
356 try {
357 int[] gids = mPM.getPackageGids(packageName,
358 updateFlagsForPackage(flags.getValue(), userId), userId);
359 if (gids != null) {
360 return gids;
361 }
362 } catch (RemoteException e) {
363 throw e.rethrowFromSystemServer();
364 }
365
366 throw new NameNotFoundException(packageName);
367 }
368
369 @Override
370 public int getPackageUid(String packageName, int flags) throws NameNotFoundException {
371 return getPackageUid(packageName, PackageInfoFlags.of(flags));
372 }
373
374 @Override
375 public int getPackageUid(String packageName, PackageInfoFlags flags)
376 throws NameNotFoundException {
377 return getPackageUidAsUser(packageName, flags, getUserId());
378 }
379
380 @Override
381 public int getPackageUidAsUser(String packageName, int userId) throws NameNotFoundException {
382 return getPackageUidAsUser(packageName, 0, userId);
383 }
384
385 @Override
386 public int getPackageUidAsUser(String packageName, int flags, int userId)
387 throws NameNotFoundException {
388 return getPackageUidAsUser(packageName, PackageInfoFlags.of(flags), userId);
389 }
390
391 @Override
392 public int getPackageUidAsUser(String packageName, PackageInfoFlags flags, int userId)
393 throws NameNotFoundException {
394 try {
395 int uid = mPM.getPackageUid(packageName,
396 updateFlagsForPackage(flags.getValue(), userId), userId);
397 if (uid >= 0) {
398 return uid;
399 }
400 } catch (RemoteException e) {
401 throw e.rethrowFromSystemServer();
402 }
403
404 throw new NameNotFoundException(packageName);
405 }
406
407 @Override
408 @SuppressWarnings("unchecked")
409 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
410 return getPermissionManager().getAllPermissionGroups(flags);
411 }
412
413 @Override
414 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags)
415 throws NameNotFoundException {
416 final PermissionGroupInfo permissionGroupInfo = getPermissionManager()
417 .getPermissionGroupInfo(groupName, flags);
418 if (permissionGroupInfo == null) {
419 throw new NameNotFoundException(groupName);
420 }
421 return permissionGroupInfo;
422 }
423
424 @Override
425 public PermissionInfo getPermissionInfo(String permName, int flags)
426 throws NameNotFoundException {
427 final PermissionInfo permissionInfo = getPermissionManager().getPermissionInfo(permName,
428 flags);
429 if (permissionInfo == null) {
430 throw new NameNotFoundException(permName);
431 }
432 return permissionInfo;
433 }
434
435 @Override
436 @SuppressWarnings("unchecked")
437 public List<PermissionInfo> queryPermissionsByGroup(String groupName, int flags)
438 throws NameNotFoundException {
439 final List<PermissionInfo> permissionInfos = getPermissionManager().queryPermissionsByGroup(
440 groupName, flags);
441 if (permissionInfos == null) {
442 throw new NameNotFoundException(groupName);
443 }
444 return permissionInfos;
445 }
446
447 @Override
448 public void getPlatformPermissionsForGroup(@NonNull String permissionGroupName,
449 @NonNull @CallbackExecutor Executor executor,
450 @NonNull Consumer<List<String>> callback) {
451 final PermissionControllerManager permissionControllerManager = mContext.getSystemService(
452 PermissionControllerManager.class);
453 permissionControllerManager.getPlatformPermissionsForGroup(permissionGroupName, executor,
454 callback);
455 }
456
457 @Override
458 public void getGroupOfPlatformPermission(@NonNull String permissionName,
459 @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<String> callback) {
460 final PermissionControllerManager permissionControllerManager = mContext.getSystemService(
461 PermissionControllerManager.class);
462 permissionControllerManager.getGroupOfPlatformPermission(permissionName, executor,
463 callback);
464 }
465
466 @Override
467 public boolean arePermissionsIndividuallyControlled() {
468 return mContext.getResources().getBoolean(
469 com.android.internal.R.bool.config_permissionsIndividuallyControlled);
470 }
471
472 @Override
473 public boolean isWirelessConsentModeEnabled() {
474 return mContext.getResources().getBoolean(
475 com.android.internal.R.bool.config_wirelessConsentRequired);
476 }
477
478 @Override
479 public ApplicationInfo getApplicationInfo(String packageName, int flags)
480 throws NameNotFoundException {
481 return getApplicationInfo(packageName, ApplicationInfoFlags.of(flags));
482 }
483
484 @Override
485 public ApplicationInfo getApplicationInfo(String packageName, ApplicationInfoFlags flags)
486 throws NameNotFoundException {
487 return getApplicationInfoAsUser(packageName, flags, getUserId());
488 }
489
490 @Override
491 public ApplicationInfo getApplicationInfoAsUser(String packageName, int flags, int userId)
492 throws NameNotFoundException {
493 return getApplicationInfoAsUser(packageName, ApplicationInfoFlags.of(flags), userId);
494 }
495
496 @Override
497 public ApplicationInfo getApplicationInfoAsUser(String packageName, ApplicationInfoFlags flags,
498 int userId) throws NameNotFoundException {
499 ApplicationInfo ai = getApplicationInfoAsUserCached(
500 packageName,
501 updateFlagsForApplication(flags.getValue(), userId),
502 userId);
503 if (ai == null) {
504 throw new NameNotFoundException(packageName);
505 }
506 return maybeAdjustApplicationInfo(ai);
507 }
508
509 private static ApplicationInfo maybeAdjustApplicationInfo(ApplicationInfo info) {
510 // If we're dealing with a multi-arch application that has both
511 // 32 and 64 bit shared libraries, we might need to choose the secondary
512 // depending on what the current runtime's instruction set is.
513 if (info.primaryCpuAbi != null && info.secondaryCpuAbi != null) {
514 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
515
516 // Get the instruction set that the libraries of secondary Abi is supported.
517 // In presence of a native bridge this might be different than the one secondary Abi used.
518 String secondaryIsa = VMRuntime.getInstructionSet(info.secondaryCpuAbi);
519 final String secondaryDexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
520 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
521
522 // If the runtimeIsa is the same as the primary isa, then we do nothing.
523 // Everything will be set up correctly because info.nativeLibraryDir will
524 // correspond to the right ISA.
525 if (runtimeIsa.equals(secondaryIsa)) {
526 ApplicationInfo modified = new ApplicationInfo(info);
527 modified.nativeLibraryDir = info.secondaryNativeLibraryDir;
528 return modified;
529 }
530 }
531 return info;
532 }
533
534 @Override
535 public int getTargetSdkVersion(@NonNull String packageName) throws NameNotFoundException {
536 try {
537 int version = mPM.getTargetSdkVersion(packageName);
538 if (version != -1) {
539 return version;
540 }
541 } catch (RemoteException e) {
542 throw e.rethrowFromSystemServer();
543 }
544 throw new PackageManager.NameNotFoundException(packageName);
545 }
546
547 @Override
548 public ActivityInfo getActivityInfo(ComponentName className, int flags)
549 throws NameNotFoundException {
550 return getActivityInfo(className, ComponentInfoFlags.of(flags));
551 }
552
553 @Override
554 public ActivityInfo getActivityInfo(ComponentName className, ComponentInfoFlags flags)
555 throws NameNotFoundException {
556 final int userId = getUserId();
557 try {
558 ActivityInfo ai = mPM.getActivityInfo(className,
559 updateFlagsForComponent(flags.getValue(), userId, null), userId);
560 if (ai != null) {
561 return ai;
562 }
563 } catch (RemoteException e) {
564 throw e.rethrowFromSystemServer();
565 }
566
567 throw new NameNotFoundException(className.toString());
568 }
569
570 @Override
571 public ActivityInfo getReceiverInfo(ComponentName className, int flags)
572 throws NameNotFoundException {
573 return getReceiverInfo(className, ComponentInfoFlags.of(flags));
574 }
575
576 @Override
577 public ActivityInfo getReceiverInfo(ComponentName className, ComponentInfoFlags flags)
578 throws NameNotFoundException {
579 final int userId = getUserId();
580 try {
581 ActivityInfo ai = mPM.getReceiverInfo(className,
582 updateFlagsForComponent(flags.getValue(), userId, null), userId);
583 if (ai != null) {
584 return ai;
585 }
586 } catch (RemoteException e) {
587 throw e.rethrowFromSystemServer();
588 }
589
590 throw new NameNotFoundException(className.toString());
591 }
592
593 @Override
594 public ServiceInfo getServiceInfo(ComponentName className, int flags)
595 throws NameNotFoundException {
596 return getServiceInfo(className, ComponentInfoFlags.of(flags));
597 }
598
599 @Override
600 public ServiceInfo getServiceInfo(ComponentName className, ComponentInfoFlags flags)
601 throws NameNotFoundException {
602 final int userId = getUserId();
603 try {
604 ServiceInfo si = mPM.getServiceInfo(className,
605 updateFlagsForComponent(flags.getValue(), userId, null), userId);
606 if (si != null) {
607 return si;
608 }
609 } catch (RemoteException e) {
610 throw e.rethrowFromSystemServer();
611 }
612
613 throw new NameNotFoundException(className.toString());
614 }
615
616 @Override
617 public ProviderInfo getProviderInfo(ComponentName className, int flags)
618 throws NameNotFoundException {
619 return getProviderInfo(className, ComponentInfoFlags.of(flags));
620 }
621
622 @Override
623 public ProviderInfo getProviderInfo(ComponentName className, ComponentInfoFlags flags)
624 throws NameNotFoundException {
625 final int userId = getUserId();
626 try {
627 ProviderInfo pi = mPM.getProviderInfo(className,
628 updateFlagsForComponent(flags.getValue(), userId, null), userId);
629 if (pi != null) {
630 return pi;
631 }
632 } catch (RemoteException e) {
633 throw e.rethrowFromSystemServer();
634 }
635
636 throw new NameNotFoundException(className.toString());
637 }
638
639 @Override
640 public String[] getSystemSharedLibraryNames() {
641 try {
642 return mPM.getSystemSharedLibraryNames();
643 } catch (RemoteException e) {
644 throw e.rethrowFromSystemServer();
645 }
646 }
647
648 /** @hide */
649 @Override
650 public @NonNull List<SharedLibraryInfo> getSharedLibraries(int flags) {
651 return this.getSharedLibraries(PackageInfoFlags.of(flags));
652 }
653
654 /** @hide
655 * @param flags */
656 @Override
657 public @NonNull List<SharedLibraryInfo> getSharedLibraries(PackageInfoFlags flags) {
658 return getSharedLibrariesAsUser(flags, getUserId());
659 }
660
661 /** @hide */
662 @Override
663 public @NonNull List<SharedLibraryInfo> getSharedLibrariesAsUser(int flags, int userId) {
664 return getSharedLibrariesAsUser(PackageInfoFlags.of(flags), userId);
665 }
666
667 /** @hide */
668 @Override
669 @SuppressWarnings("unchecked")
670 public @NonNull List<SharedLibraryInfo> getSharedLibrariesAsUser(PackageInfoFlags flags,
671 int userId) {
672 try {
673 ParceledListSlice<SharedLibraryInfo> sharedLibs = mPM.getSharedLibraries(
674 mContext.getOpPackageName(), flags.getValue(), userId);
675 if (sharedLibs == null) {
676 return Collections.emptyList();
677 }
678 return sharedLibs.getList();
679 } catch (RemoteException e) {
680 throw e.rethrowFromSystemServer();
681 }
682 }
683
684 @NonNull
685 @Override
686 public List<SharedLibraryInfo> getDeclaredSharedLibraries(@NonNull String packageName,
687 int flags) {
688 return getDeclaredSharedLibraries(packageName, PackageInfoFlags.of(flags));
689 }
690
691 @NonNull
692 @Override
693 @SuppressWarnings("unchecked")
694 public List<SharedLibraryInfo> getDeclaredSharedLibraries(@NonNull String packageName,
695 PackageInfoFlags flags) {
696 try {
697 ParceledListSlice<SharedLibraryInfo> sharedLibraries = mPM.getDeclaredSharedLibraries(
698 packageName, flags.getValue(), mContext.getUserId());
699 return sharedLibraries != null ? sharedLibraries.getList() : Collections.emptyList();
700 } catch (RemoteException e) {
701 throw e.rethrowFromSystemServer();
702 }
703 }
704
705 /** @hide */
706 @Override
707 public @NonNull String getServicesSystemSharedLibraryPackageName() {
708 try {
709 return mPM.getServicesSystemSharedLibraryPackageName();
710 } catch (RemoteException e) {
711 throw e.rethrowFromSystemServer();
712 }
713 }
714
715 /**
716 * @hide
717 */
718 public @NonNull String getSharedSystemSharedLibraryPackageName() {
719 try {
720 return mPM.getSharedSystemSharedLibraryPackageName();
721 } catch (RemoteException e) {
722 throw e.rethrowFromSystemServer();
723 }
724 }
725
726 @Override
727 public ChangedPackages getChangedPackages(int sequenceNumber) {
728 try {
729 return mPM.getChangedPackages(sequenceNumber, getUserId());
730 } catch (RemoteException e) {
731 throw e.rethrowFromSystemServer();
732 }
733 }
734
735 @Override
736 @SuppressWarnings("unchecked")
737 public FeatureInfo[] getSystemAvailableFeatures() {
738 try {
739 ParceledListSlice<FeatureInfo> parceledList =
740 mPM.getSystemAvailableFeatures();
741 if (parceledList == null) {
742 return new FeatureInfo[0];
743 }
744 final List<FeatureInfo> list = parceledList.getList();
745 final FeatureInfo[] res = new FeatureInfo[list.size()];
746 for (int i = 0; i < res.length; i++) {
747 res[i] = list.get(i);
748 }
749 return res;
750 } catch (RemoteException e) {
751 throw e.rethrowFromSystemServer();
752 }
753 }
754
755 @Override
756 public boolean hasSystemFeature(String name) {
757 return hasSystemFeature(name, 0);
758 }
759
760 /**
761 * Identifies a single hasSystemFeature query.
762 */
763 @Immutable
764 private static final class HasSystemFeatureQuery {
765 public final String name;
766 public final int version;
767 public HasSystemFeatureQuery(String n, int v) {
768 name = n;
769 version = v;
770 }
771 @Override
772 public String toString() {
773 return String.format("HasSystemFeatureQuery(name=\"%s\", version=%d)",
774 name, version);
775 }
776 @Override
777 public boolean equals(@Nullable Object o) {
778 if (o instanceof HasSystemFeatureQuery) {
779 HasSystemFeatureQuery r = (HasSystemFeatureQuery) o;
780 return Objects.equals(name, r.name) && version == r.version;
781 } else {
782 return false;
783 }
784 }
785 @Override
786 public int hashCode() {
787 return Objects.hashCode(name) * 13 + version;
788 }
789 }
790
791 // Make this cache relatively large. There are many system features and
792 // none are ever invalidated. MPTS tests suggests that the cache should
793 // hold at least 150 entries.
794 private final static PropertyInvalidatedCache<HasSystemFeatureQuery, Boolean>
795 mHasSystemFeatureCache =
796 new PropertyInvalidatedCache<HasSystemFeatureQuery, Boolean>(
797 256, "cache_key.has_system_feature") {
798 @Override
799 public Boolean recompute(HasSystemFeatureQuery query) {
800 try {
801 return ActivityThread.currentActivityThread().getPackageManager().
802 hasSystemFeature(query.name, query.version);
803 } catch (RemoteException e) {
804 throw e.rethrowFromSystemServer();
805 }
806 }
807 };
808
809 @Override
810 public boolean hasSystemFeature(String name, int version) {
811 return mHasSystemFeatureCache.query(new HasSystemFeatureQuery(name, version));
812 }
813
814 /** @hide */
815 public void disableHasSystemFeatureCache() {
816 mHasSystemFeatureCache.disableLocal();
817 }
818
819 /** @hide */
820 public static void invalidateHasSystemFeatureCache() {
821 mHasSystemFeatureCache.invalidateCache();
822 }
823
824 @Override
825 public int checkPermission(String permName, String pkgName) {
826 return PermissionManager.checkPackageNamePermission(permName, pkgName, getUserId());
827 }
828
829 @Override
830 public boolean isPermissionRevokedByPolicy(String permName, String pkgName) {
831 return getPermissionManager().isPermissionRevokedByPolicy(pkgName, permName);
832 }
833
834 /**
835 * @hide
836 */
837 @Override
838 public String getPermissionControllerPackageName() {
839 if (mPermissionsControllerPackageName == null) {
840 try {
841 mPermissionsControllerPackageName = mPM.getPermissionControllerPackageName();
842 } catch (RemoteException e) {
843 throw e.rethrowFromSystemServer();
844 }
845 }
846 return mPermissionsControllerPackageName;
847 }
848
849 /**
850 * @hide
851 */
852 @Override
853 public String getSdkSandboxPackageName() {
854 try {
855 return mPM.getSdkSandboxPackageName();
856 } catch (RemoteException e) {
857 throw e.rethrowFromSystemServer();
858 }
859 }
860
861 @Override
862 public boolean addPermission(PermissionInfo info) {
863 return getPermissionManager().addPermission(info, false);
864 }
865
866 @Override
867 public boolean addPermissionAsync(PermissionInfo info) {
868 return getPermissionManager().addPermission(info, true);
869 }
870
871 @Override
872 public void removePermission(String name) {
873 getPermissionManager().removePermission(name);
874 }
875
876 @Override
877 public void grantRuntimePermission(String packageName, String permissionName,
878 UserHandle user) {
879 getPermissionManager().grantRuntimePermission(packageName, permissionName, user);
880 }
881
882 @Override
883 public void revokeRuntimePermission(String packageName, String permName, UserHandle user) {
884 revokeRuntimePermission(packageName, permName, user, null);
885 }
886
887 @Override
888 public void revokeRuntimePermission(String packageName, String permName, UserHandle user,
889 String reason) {
890 getPermissionManager().revokeRuntimePermission(packageName, permName, user, reason);
891 }
892
893 @Override
894 public int getPermissionFlags(String permName, String packageName, UserHandle user) {
895 return getPermissionManager().getPermissionFlags(packageName, permName, user);
896 }
897
898 @Override
899 public void updatePermissionFlags(String permName, String packageName,
900 int flagMask, int flagValues, UserHandle user) {
901 getPermissionManager().updatePermissionFlags(packageName, permName, flagMask, flagValues,
902 user);
903 }
904
905 @Override
906 public @NonNull Set<String> getWhitelistedRestrictedPermissions(
907 @NonNull String packageName, @PermissionWhitelistFlags int flags) {
908 return getPermissionManager().getAllowlistedRestrictedPermissions(packageName, flags);
909 }
910
911 @Override
912 public boolean addWhitelistedRestrictedPermission(@NonNull String packageName,
913 @NonNull String permName, @PermissionWhitelistFlags int flags) {
914 return getPermissionManager().addAllowlistedRestrictedPermission(packageName, permName,
915 flags);
916 }
917
918 @Override
919 public boolean setAutoRevokeWhitelisted(@NonNull String packageName, boolean whitelisted) {
920 return getPermissionManager().setAutoRevokeExempted(packageName, whitelisted);
921 }
922
923 @Override
924 public boolean isAutoRevokeWhitelisted(@NonNull String packageName) {
925 return getPermissionManager().isAutoRevokeExempted(packageName);
926 }
927
928 @Override
929 public boolean removeWhitelistedRestrictedPermission(@NonNull String packageName,
930 @NonNull String permName, @PermissionWhitelistFlags int flags) {
931 return getPermissionManager().removeAllowlistedRestrictedPermission(packageName, permName,
932 flags);
933 }
934
935 @Override
936 @UnsupportedAppUsage
937 public boolean shouldShowRequestPermissionRationale(String permName) {
938 return getPermissionManager().shouldShowRequestPermissionRationale(permName);
939 }
940
941 @Override
942 public CharSequence getBackgroundPermissionOptionLabel() {
943 try {
944
945 String permissionController = getPermissionControllerPackageName();
946 Context context =
947 mContext.createPackageContext(permissionController, 0);
948
949 int textId = context.getResources().getIdentifier(APP_PERMISSION_BUTTON_ALLOW_ALWAYS,
950 "string", PERMISSION_CONTROLLER_RESOURCE_PACKAGE);
951 if (textId != 0) {
952 return context.getText(textId);
953 }
954 } catch (NameNotFoundException e) {
955 Log.e(TAG, "Permission controller not found.", e);
956 }
957 return "";
958 }
959
960 @Override
961 public int checkSignatures(String pkg1, String pkg2) {
962 try {
963 return mPM.checkSignatures(pkg1, pkg2);
964 } catch (RemoteException e) {
965 throw e.rethrowFromSystemServer();
966 }
967 }
968
969 @Override
970 public int checkSignatures(int uid1, int uid2) {
971 try {
972 return mPM.checkUidSignatures(uid1, uid2);
973 } catch (RemoteException e) {
974 throw e.rethrowFromSystemServer();
975 }
976 }
977
978 @Override
979 public boolean hasSigningCertificate(
980 String packageName, byte[] certificate, @CertificateInputType int type) {
981 try {
982 return mPM.hasSigningCertificate(packageName, certificate, type);
983 } catch (RemoteException e) {
984 throw e.rethrowFromSystemServer();
985 }
986 }
987
988 @Override
989 public boolean hasSigningCertificate(
990 int uid, byte[] certificate, @CertificateInputType int type) {
991 try {
992 return mPM.hasUidSigningCertificate(uid, certificate, type);
993 } catch (RemoteException e) {
994 throw e.rethrowFromSystemServer();
995 }
996 }
997
998 private static List<byte[]> encodeCertificates(List<Certificate> certs) throws
999 CertificateEncodingException {
1000 if (certs == null) {
1001 return null;
1002 }
1003 List<byte[]> result = new ArrayList<>(certs.size());
1004 for (Certificate cert : certs) {
1005 if (!(cert instanceof X509Certificate)) {
1006 throw new CertificateEncodingException("Only X509 certificates supported.");
1007 }
1008 result.add(cert.getEncoded());
1009 }
1010 return result;
1011 }
1012
1013 @Override
1014 public void requestChecksums(@NonNull String packageName, boolean includeSplits,
1015 @Checksum.TypeMask int required, @NonNull List<Certificate> trustedInstallers,
1016 @NonNull OnChecksumsReadyListener onChecksumsReadyListener)
1017 throws CertificateEncodingException, NameNotFoundException {
1018 Objects.requireNonNull(packageName);
1019 Objects.requireNonNull(onChecksumsReadyListener);
1020 Objects.requireNonNull(trustedInstallers);
1021 if (trustedInstallers == TRUST_ALL) {
1022 trustedInstallers = null;
1023 } else if (trustedInstallers == TRUST_NONE) {
1024 trustedInstallers = Collections.emptyList();
1025 } else if (trustedInstallers.isEmpty()) {
1026 throw new IllegalArgumentException(
1027 "trustedInstallers has to be one of TRUST_ALL/TRUST_NONE or a non-empty "
1028 + "list of certificates.");
1029 }
1030 try {
1031 IOnChecksumsReadyListener onChecksumsReadyListenerDelegate =
1032 new IOnChecksumsReadyListener.Stub() {
1033 @Override
1034 public void onChecksumsReady(List<ApkChecksum> checksums)
1035 throws RemoteException {
1036 onChecksumsReadyListener.onChecksumsReady(checksums);
1037 }
1038 };
1039 mPM.requestPackageChecksums(packageName, includeSplits, DEFAULT_CHECKSUMS, required,
1040 encodeCertificates(trustedInstallers), onChecksumsReadyListenerDelegate,
1041 getUserId());
1042 } catch (ParcelableException e) {
1043 e.maybeRethrow(PackageManager.NameNotFoundException.class);
1044 throw new RuntimeException(e);
1045 } catch (RemoteException e) {
1046 throw e.rethrowFromSystemServer();
1047 }
1048 }
1049
1050 /**
1051 * Wrap the cached value in a class that does deep compares on string
1052 * arrays. The comparison is needed only for the verification mode of
1053 * PropertyInvalidatedCache; this mode is only enabled for debugging.
1054 * The return result is an array of strings but the order in the array
1055 * is not important. To properly compare two arrays, the arrays are
1056 * sorted before the comparison.
1057 */
1058 private static class GetPackagesForUidResult {
1059 private final String [] mValue;
1060 GetPackagesForUidResult(String []s) {
1061 mValue = s;
1062 }
1063 public String[] value() {
1064 return mValue;
1065 }
1066 @Override
1067 public String toString() {
1068 return Arrays.toString(mValue);
1069 }
1070 @Override
1071 public int hashCode() {
1072 return Arrays.hashCode(mValue);
1073 }
1074 /**
1075 * Arrays.sort() throws an NPE if passed a null pointer, so nulls
1076 * are handled first.
1077 */
1078 @Override
1079 public boolean equals(@Nullable Object o) {
1080 if (o instanceof GetPackagesForUidResult) {
1081 String [] r = ((GetPackagesForUidResult) o).mValue;
1082 String [] l = mValue;
1083 if ((r == null) != (l == null)) {
1084 return false;
1085 } else if (r == null) {
1086 return true;
1087 }
1088 // Both arrays are non-null. Sort before comparing.
1089 Arrays.sort(r);
1090 Arrays.sort(l);
1091 return Arrays.equals(l, r);
1092 } else {
1093 return false;
1094 }
1095 }
1096 }
1097
1098 private static final String CACHE_KEY_PACKAGES_FOR_UID_PROPERTY =
1099 "cache_key.get_packages_for_uid";
1100 private static final PropertyInvalidatedCache<Integer, GetPackagesForUidResult>
1101 mGetPackagesForUidCache =
1102 new PropertyInvalidatedCache<Integer, GetPackagesForUidResult>(
1103 32, CACHE_KEY_PACKAGES_FOR_UID_PROPERTY) {
1104 @Override
1105 public GetPackagesForUidResult recompute(Integer uid) {
1106 try {
1107 return new GetPackagesForUidResult(
1108 ActivityThread.currentActivityThread().
1109 getPackageManager().getPackagesForUid(uid));
1110 } catch (RemoteException e) {
1111 throw e.rethrowFromSystemServer();
1112 }
1113 }
1114 @Override
1115 public String queryToString(Integer uid) {
1116 return String.format("uid=%d", uid.intValue());
1117 }
1118 };
1119
1120 @Override
1121 public String[] getPackagesForUid(int uid) {
1122 return mGetPackagesForUidCache.query(uid).value();
1123 }
1124
1125 /** @hide */
1126 public static void disableGetPackagesForUidCache() {
1127 mGetPackagesForUidCache.disableLocal();
1128 }
1129
1130 /** @hide */
1131 public static void invalidateGetPackagesForUidCache() {
1132 PropertyInvalidatedCache.invalidateCache(CACHE_KEY_PACKAGES_FOR_UID_PROPERTY);
1133 }
1134
1135 @Override
1136 public String getNameForUid(int uid) {
1137 try {
1138 return mPM.getNameForUid(uid);
1139 } catch (RemoteException e) {
1140 throw e.rethrowFromSystemServer();
1141 }
1142 }
1143
1144 @Override
1145 public String[] getNamesForUids(int[] uids) {
1146 try {
1147 return mPM.getNamesForUids(uids);
1148 } catch (RemoteException e) {
1149 throw e.rethrowFromSystemServer();
1150 }
1151 }
1152
1153 @Override
1154 public int getUidForSharedUser(String sharedUserName)
1155 throws NameNotFoundException {
1156 try {
1157 int uid = mPM.getUidForSharedUser(sharedUserName);
1158 if (uid != Process.INVALID_UID) {
1159 return uid;
1160 }
1161 } catch (RemoteException e) {
1162 throw e.rethrowFromSystemServer();
1163 }
1164 throw new NameNotFoundException("No shared userid for user:"+sharedUserName);
1165 }
1166
1167 @Override
1168 public List<ModuleInfo> getInstalledModules(int flags) {
1169 try {
1170 return mPM.getInstalledModules(flags);
1171 } catch (RemoteException e) {
1172 throw e.rethrowFromSystemServer();
1173 }
1174 }
1175
1176 @Override
1177 public ModuleInfo getModuleInfo(String packageName, int flags) throws NameNotFoundException {
1178 try {
1179 ModuleInfo mi = mPM.getModuleInfo(packageName, flags);
1180 if (mi != null) {
1181 return mi;
1182 }
1183 } catch (RemoteException e) {
1184 throw e.rethrowFromSystemServer();
1185 }
1186
1187 throw new NameNotFoundException("No module info for package: " + packageName);
1188 }
1189
1190 @SuppressWarnings("unchecked")
1191 @Override
1192 public List<PackageInfo> getInstalledPackages(int flags) {
1193 return getInstalledPackages(PackageInfoFlags.of(flags));
1194 }
1195
1196 @SuppressWarnings("unchecked")
1197 @Override
1198 public List<PackageInfo> getInstalledPackages(PackageInfoFlags flags) {
1199 return getInstalledPackagesAsUser(flags, getUserId());
1200 }
1201
1202 /** @hide */
1203 @Override
1204 @SuppressWarnings("unchecked")
1205 public List<PackageInfo> getInstalledPackagesAsUser(int flags, int userId) {
1206 return getInstalledPackagesAsUser(PackageInfoFlags.of(flags), userId);
1207 }
1208
1209 /** @hide */
1210 @Override
1211 @SuppressWarnings("unchecked")
1212 public List<PackageInfo> getInstalledPackagesAsUser(PackageInfoFlags flags, int userId) {
1213 try {
1214 ParceledListSlice<PackageInfo> parceledList =
1215 mPM.getInstalledPackages(updateFlagsForPackage(flags.getValue(), userId),
1216 userId);
1217 if (parceledList == null) {
1218 return Collections.emptyList();
1219 }
1220 return parceledList.getList();
1221 } catch (RemoteException e) {
1222 throw e.rethrowFromSystemServer();
1223 }
1224 }
1225
1226 @SuppressWarnings("unchecked")
1227 @Override
1228 public List<PackageInfo> getPackagesHoldingPermissions(String[] permissions, int flags) {
1229 return this.getPackagesHoldingPermissions(permissions, PackageInfoFlags.of(flags));
1230 }
1231
1232 @SuppressWarnings("unchecked")
1233 @Override
1234 public List<PackageInfo> getPackagesHoldingPermissions(String[] permissions,
1235 PackageInfoFlags flags) {
1236 final int userId = getUserId();
1237 try {
1238 ParceledListSlice<PackageInfo> parceledList =
1239 mPM.getPackagesHoldingPermissions(permissions,
1240 updateFlagsForPackage(flags.getValue(), userId), userId);
1241 if (parceledList == null) {
1242 return Collections.emptyList();
1243 }
1244 return parceledList.getList();
1245 } catch (RemoteException e) {
1246 throw e.rethrowFromSystemServer();
1247 }
1248 }
1249
1250 @SuppressWarnings("unchecked")
1251 @Override
1252 public List<ApplicationInfo> getInstalledApplications(int flags) {
1253 return getInstalledApplicationsAsUser(flags, getUserId());
1254 }
1255
1256 @Override
1257 public List<ApplicationInfo> getInstalledApplications(ApplicationInfoFlags flags) {
1258 return getInstalledApplicationsAsUser(flags, getUserId());
1259 }
1260
1261 /** @hide */
1262 @SuppressWarnings("unchecked")
1263 @Override
1264 public List<ApplicationInfo> getInstalledApplicationsAsUser(int flags, int userId) {
1265 return getInstalledApplicationsAsUser(ApplicationInfoFlags.of(flags), userId);
1266 }
1267
1268 /** @hide */
1269 @SuppressWarnings("unchecked")
1270 @Override
1271 public List<ApplicationInfo> getInstalledApplicationsAsUser(ApplicationInfoFlags flags,
1272 int userId) {
1273 try {
1274 ParceledListSlice<ApplicationInfo> parceledList =
1275 mPM.getInstalledApplications(updateFlagsForApplication(
1276 flags.getValue(), userId), userId);
1277 if (parceledList == null) {
1278 return Collections.emptyList();
1279 }
1280 return parceledList.getList();
1281 } catch (RemoteException e) {
1282 throw e.rethrowFromSystemServer();
1283 }
1284 }
1285
1286 /** @hide */
1287 @SuppressWarnings("unchecked")
1288 @Override
1289 public List<InstantAppInfo> getInstantApps() {
1290 try {
1291 ParceledListSlice<InstantAppInfo> slice = mPM.getInstantApps(getUserId());
1292 if (slice != null) {
1293 return slice.getList();
1294 }
1295 return Collections.emptyList();
1296 } catch (RemoteException e) {
1297 throw e.rethrowFromSystemServer();
1298 }
1299 }
1300
1301 /** @hide */
1302 @Override
1303 public Drawable getInstantAppIcon(String packageName) {
1304 try {
1305 Bitmap bitmap = mPM.getInstantAppIcon(packageName, getUserId());
1306 if (bitmap != null) {
1307 return new BitmapDrawable(null, bitmap);
1308 }
1309 return null;
1310 } catch (RemoteException e) {
1311 throw e.rethrowFromSystemServer();
1312 }
1313 }
1314
1315 @Override
1316 public boolean isInstantApp() {
1317 return isInstantApp(mContext.getPackageName());
1318 }
1319
1320 @Override
1321 public boolean isInstantApp(String packageName) {
1322 try {
1323 return mPM.isInstantApp(packageName, getUserId());
1324 } catch (RemoteException e) {
1325 throw e.rethrowFromSystemServer();
1326 }
1327 }
1328
1329 public int getInstantAppCookieMaxBytes() {
1330 return Settings.Global.getInt(mContext.getContentResolver(),
1331 Settings.Global.EPHEMERAL_COOKIE_MAX_SIZE_BYTES,
1332 DEFAULT_EPHEMERAL_COOKIE_MAX_SIZE_BYTES);
1333 }
1334
1335 @Override
1336 public int getInstantAppCookieMaxSize() {
1337 return getInstantAppCookieMaxBytes();
1338 }
1339
1340 @Override
1341 public @NonNull byte[] getInstantAppCookie() {
1342 try {
1343 final byte[] cookie = mPM.getInstantAppCookie(mContext.getPackageName(), getUserId());
1344 if (cookie != null) {
1345 return cookie;
1346 } else {
1347 return EmptyArray.BYTE;
1348 }
1349 } catch (RemoteException e) {
1350 throw e.rethrowFromSystemServer();
1351 }
1352 }
1353
1354 @Override
1355 public void clearInstantAppCookie() {
1356 updateInstantAppCookie(null);
1357 }
1358
1359 @Override
1360 public void updateInstantAppCookie(@NonNull byte[] cookie) {
1361 if (cookie != null && cookie.length > getInstantAppCookieMaxBytes()) {
1362 throw new IllegalArgumentException("instant cookie longer than "
1363 + getInstantAppCookieMaxBytes());
1364 }
1365 try {
1366 mPM.setInstantAppCookie(mContext.getPackageName(), cookie, getUserId());
1367 } catch (RemoteException e) {
1368 throw e.rethrowFromSystemServer();
1369 }
1370 }
1371
1372 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1373 @Override
1374 public boolean setInstantAppCookie(@NonNull byte[] cookie) {
1375 try {
1376 return mPM.setInstantAppCookie(mContext.getPackageName(), cookie, getUserId());
1377 } catch (RemoteException e) {
1378 throw e.rethrowFromSystemServer();
1379 }
1380 }
1381
1382 @Override
1383 public ResolveInfo resolveActivity(Intent intent, int flags) {
1384 return resolveActivity(intent, ResolveInfoFlags.of(flags));
1385 }
1386
1387 @Override
1388 public ResolveInfo resolveActivity(Intent intent, ResolveInfoFlags flags) {
1389 return resolveActivityAsUser(intent, flags, getUserId());
1390 }
1391
1392 @Override
1393 public ResolveInfo resolveActivityAsUser(Intent intent, int flags, int userId) {
1394 return resolveActivityAsUser(intent, ResolveInfoFlags.of(flags), userId);
1395 }
1396
1397 @Override
1398 public ResolveInfo resolveActivityAsUser(Intent intent, ResolveInfoFlags flags, int userId) {
1399 try {
1400 return mPM.resolveIntent(
1401 intent,
1402 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1403 updateFlagsForComponent(flags.getValue(), userId, intent),
1404 userId);
1405 } catch (RemoteException e) {
1406 throw e.rethrowFromSystemServer();
1407 }
1408 }
1409
1410 @Override
1411 public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) {
1412 return queryIntentActivities(intent, ResolveInfoFlags.of(flags));
1413 }
1414
1415 @Override
1416 public List<ResolveInfo> queryIntentActivities(Intent intent, ResolveInfoFlags flags) {
1417 return queryIntentActivitiesAsUser(intent, flags, getUserId());
1418 }
1419
1420 /** @hide Same as above but for a specific user */
1421 @Override
1422 public List<ResolveInfo> queryIntentActivitiesAsUser(Intent intent, int flags, int userId) {
1423 return queryIntentActivitiesAsUser(intent, ResolveInfoFlags.of(flags), userId);
1424 }
1425
1426 /** @hide Same as above but for a specific user */
1427 @Override
1428 @SuppressWarnings("unchecked")
1429 public List<ResolveInfo> queryIntentActivitiesAsUser(Intent intent, ResolveInfoFlags flags,
1430 int userId) {
1431 try {
1432 ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentActivities(
1433 intent,
1434 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1435 updateFlagsForComponent(flags.getValue(), userId, intent),
1436 userId);
1437 if (parceledList == null) {
1438 return Collections.emptyList();
1439 }
1440 return parceledList.getList();
1441 } catch (RemoteException e) {
1442 throw e.rethrowFromSystemServer();
1443 }
1444 }
1445
1446 @Override
1447 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, Intent[] specifics,
1448 Intent intent, int flags) {
1449 return queryIntentActivityOptions(caller,
1450 specifics == null ? null : new ArrayList<>(Arrays.asList(specifics)),
1451 intent, ResolveInfoFlags.of(flags));
1452 }
1453
1454 @Override
1455 @SuppressWarnings("unchecked")
1456 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1457 List<Intent> specifics, Intent intent, ResolveInfoFlags flags) {
1458 final int userId = getUserId();
1459 final ContentResolver resolver = mContext.getContentResolver();
1460
1461 String[] specificTypes = null;
1462 if (specifics != null) {
1463 final int numSpecifics = specifics.size();
1464 for (int i = 0; i < numSpecifics; i++) {
1465 Intent sp = specifics.get(i);
1466 if (sp != null) {
1467 String t = sp.resolveTypeIfNeeded(resolver);
1468 if (t != null) {
1469 if (specificTypes == null) {
1470 specificTypes = new String[numSpecifics];
1471 }
1472 specificTypes[i] = t;
1473 }
1474 }
1475 }
1476 }
1477
1478 try {
1479 ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentActivityOptions(
1480 caller,
1481 specifics == null ? null : specifics.toArray(new Intent[0]),
1482 specificTypes,
1483 intent,
1484 intent.resolveTypeIfNeeded(resolver),
1485 updateFlagsForComponent(flags.getValue(), userId, intent),
1486 userId);
1487 if (parceledList == null) {
1488 return Collections.emptyList();
1489 }
1490 return parceledList.getList();
1491 } catch (RemoteException e) {
1492 throw e.rethrowFromSystemServer();
1493 }
1494 }
1495
1496 /**
1497 * @hide
1498 */
1499 @Override
1500 public List<ResolveInfo> queryBroadcastReceiversAsUser(Intent intent, int flags, int userId) {
1501 return queryBroadcastReceiversAsUser(intent, ResolveInfoFlags.of(flags), userId);
1502 }
1503
1504 /**
1505 * @hide
1506 */
1507 @Override
1508 @SuppressWarnings("unchecked")
1509 public List<ResolveInfo> queryBroadcastReceiversAsUser(Intent intent, ResolveInfoFlags flags,
1510 int userId) {
1511 try {
1512 ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentReceivers(
1513 intent,
1514 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1515 updateFlagsForComponent(flags.getValue(), userId, intent),
1516 userId);
1517 if (parceledList == null) {
1518 return Collections.emptyList();
1519 }
1520 return parceledList.getList();
1521 } catch (RemoteException e) {
1522 throw e.rethrowFromSystemServer();
1523 }
1524 }
1525
1526 @Override
1527 public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
1528 return queryBroadcastReceivers(intent, ResolveInfoFlags.of(flags));
1529 }
1530
1531 @Override
1532 public List<ResolveInfo> queryBroadcastReceivers(Intent intent, ResolveInfoFlags flags) {
1533 return queryBroadcastReceiversAsUser(intent, flags, getUserId());
1534 }
1535
1536 @Override
1537 public ResolveInfo resolveServiceAsUser(Intent intent, int flags, @UserIdInt int userId) {
1538 return resolveServiceAsUser(intent, ResolveInfoFlags.of(flags), userId);
1539 }
1540
1541 @Override
1542 public ResolveInfo resolveServiceAsUser(Intent intent, ResolveInfoFlags flags,
1543 @UserIdInt int userId) {
1544 try {
1545 return mPM.resolveService(
1546 intent,
1547 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1548 updateFlagsForComponent(flags.getValue(), userId, intent),
1549 userId);
1550 } catch (RemoteException e) {
1551 throw e.rethrowFromSystemServer();
1552 }
1553 }
1554
1555 @Override
1556 public ResolveInfo resolveService(Intent intent, int flags) {
1557 return resolveService(intent, ResolveInfoFlags.of(flags));
1558 }
1559
1560 @Override
1561 public ResolveInfo resolveService(Intent intent, ResolveInfoFlags flags) {
1562 return resolveServiceAsUser(intent, flags, getUserId());
1563 }
1564
1565 @Override
1566 public List<ResolveInfo> queryIntentServicesAsUser(Intent intent, int flags, int userId) {
1567 return queryIntentServicesAsUser(intent, ResolveInfoFlags.of(flags), userId);
1568 }
1569
1570 @Override
1571 @SuppressWarnings("unchecked")
1572 public List<ResolveInfo> queryIntentServicesAsUser(Intent intent, ResolveInfoFlags flags,
1573 int userId) {
1574 try {
1575 ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentServices(
1576 intent,
1577 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1578 updateFlagsForComponent(flags.getValue(), userId, intent),
1579 userId);
1580 if (parceledList == null) {
1581 return Collections.emptyList();
1582 }
1583 return parceledList.getList();
1584 } catch (RemoteException e) {
1585 throw e.rethrowFromSystemServer();
1586 }
1587 }
1588
1589 @Override
1590 public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
1591 return queryIntentServices(intent, ResolveInfoFlags.of(flags));
1592 }
1593
1594 @Override
1595 public List<ResolveInfo> queryIntentServices(Intent intent, ResolveInfoFlags flags) {
1596 return queryIntentServicesAsUser(intent, flags, getUserId());
1597 }
1598
1599 @Override
1600 public List<ResolveInfo> queryIntentContentProvidersAsUser(
1601 Intent intent, int flags, int userId) {
1602 return queryIntentContentProvidersAsUser(intent, ResolveInfoFlags.of(flags), userId);
1603 }
1604
1605 @Override
1606 @SuppressWarnings("unchecked")
1607 public List<ResolveInfo> queryIntentContentProvidersAsUser(
1608 Intent intent, ResolveInfoFlags flags, int userId) {
1609 try {
1610 ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentContentProviders(
1611 intent,
1612 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1613 updateFlagsForComponent(flags.getValue(), userId, intent),
1614 userId);
1615 if (parceledList == null) {
1616 return Collections.emptyList();
1617 }
1618 return parceledList.getList();
1619 } catch (RemoteException e) {
1620 throw e.rethrowFromSystemServer();
1621 }
1622 }
1623
1624 @Override
1625 public List<ResolveInfo> queryIntentContentProviders(Intent intent, int flags) {
1626 return queryIntentContentProviders(intent, ResolveInfoFlags.of(flags));
1627 }
1628
1629 @Override
1630 public List<ResolveInfo> queryIntentContentProviders(Intent intent, ResolveInfoFlags flags) {
1631 return queryIntentContentProvidersAsUser(intent, flags, getUserId());
1632 }
1633
1634 @Override
1635 public ProviderInfo resolveContentProvider(String name, int flags) {
1636 return resolveContentProvider(name, ComponentInfoFlags.of(flags));
1637 }
1638
1639 @Override
1640 public ProviderInfo resolveContentProvider(String name, ComponentInfoFlags flags) {
1641 return resolveContentProviderAsUser(name, flags, getUserId());
1642 }
1643
1644 /** @hide **/
1645 @Override
1646 public ProviderInfo resolveContentProviderAsUser(String name, int flags, int userId) {
1647 return resolveContentProviderAsUser(name, ComponentInfoFlags.of(flags), userId);
1648 }
1649
1650 /** @hide **/
1651 @Override
1652 public ProviderInfo resolveContentProviderAsUser(String name, ComponentInfoFlags flags,
1653 int userId) {
1654 try {
1655 return mPM.resolveContentProvider(name,
1656 updateFlagsForComponent(flags.getValue(), userId, null), userId);
1657 } catch (RemoteException e) {
1658 throw e.rethrowFromSystemServer();
1659 }
1660 }
1661
1662 @Override
1663 public List<ProviderInfo> queryContentProviders(String processName, int uid, int flags) {
1664 return queryContentProviders(processName, uid, ComponentInfoFlags.of(flags));
1665 }
1666
1667 @Override
1668 public List<ProviderInfo> queryContentProviders(String processName, int uid,
1669 ComponentInfoFlags flags) {
1670 return queryContentProviders(processName, uid, flags, null);
1671 }
1672
1673 @Override
1674 public List<ProviderInfo> queryContentProviders(String processName,
1675 int uid, int flags, String metaDataKey) {
1676 return queryContentProviders(processName, uid, ComponentInfoFlags.of(flags), metaDataKey);
1677 }
1678
1679 @Override
1680 @SuppressWarnings("unchecked")
1681 public List<ProviderInfo> queryContentProviders(String processName,
1682 int uid, ComponentInfoFlags flags, String metaDataKey) {
1683 try {
1684 ParceledListSlice<ProviderInfo> slice = mPM.queryContentProviders(processName, uid,
1685 updateFlagsForComponent(flags.getValue(), UserHandle.getUserId(uid),
1686 null), metaDataKey);
1687 return slice != null ? slice.getList() : Collections.emptyList();
1688 } catch (RemoteException e) {
1689 throw e.rethrowFromSystemServer();
1690 }
1691 }
1692
1693 @Override
1694 public InstrumentationInfo getInstrumentationInfo(
1695 ComponentName className, int flags)
1696 throws NameNotFoundException {
1697 try {
1698 InstrumentationInfo ii = mPM.getInstrumentationInfo(
1699 className, flags);
1700 if (ii != null) {
1701 return ii;
1702 }
1703 } catch (RemoteException e) {
1704 throw e.rethrowFromSystemServer();
1705 }
1706
1707 throw new NameNotFoundException(className.toString());
1708 }
1709
1710 @Override
1711 @SuppressWarnings("unchecked")
1712 public List<InstrumentationInfo> queryInstrumentation(
1713 String targetPackage, int flags) {
1714 try {
1715 ParceledListSlice<InstrumentationInfo> parceledList =
1716 mPM.queryInstrumentation(targetPackage, flags);
1717 if (parceledList == null) {
1718 return Collections.emptyList();
1719 }
1720 return parceledList.getList();
1721 } catch (RemoteException e) {
1722 throw e.rethrowFromSystemServer();
1723 }
1724 }
1725
1726 @Nullable
1727 @Override
1728 public Drawable getDrawable(String packageName, @DrawableRes int resId,
1729 @Nullable ApplicationInfo appInfo) {
1730 final ResourceName name = new ResourceName(packageName, resId);
1731 final Drawable cachedIcon = getCachedIcon(name);
1732 if (cachedIcon != null) {
1733 return cachedIcon;
1734 }
1735
1736 if (appInfo == null) {
1737 try {
1738 appInfo = getApplicationInfo(packageName, sDefaultFlags);
1739 } catch (NameNotFoundException e) {
1740 return null;
1741 }
1742 }
1743
1744 if (resId != 0) {
1745 try {
1746 final Resources r = getResourcesForApplication(appInfo);
1747 final Drawable dr = r.getDrawable(resId, null);
1748 if (dr != null) {
1749 putCachedIcon(name, dr);
1750 }
1751
1752 if (false) {
1753 RuntimeException e = new RuntimeException("here");
1754 e.fillInStackTrace();
1755 Log.w(TAG, "Getting drawable 0x" + Integer.toHexString(resId)
1756 + " from package " + packageName
1757 + ": app scale=" + r.getCompatibilityInfo().applicationScale
1758 + ", caller scale=" + mContext.getResources()
1759 .getCompatibilityInfo().applicationScale,
1760 e);
1761 }
1762 if (DEBUG_ICONS) {
1763 Log.v(TAG, "Getting drawable 0x"
1764 + Integer.toHexString(resId) + " from " + r
1765 + ": " + dr);
1766 }
1767 return dr;
1768 } catch (NameNotFoundException e) {
1769 Log.w("PackageManager", "Failure retrieving resources for "
1770 + appInfo.packageName);
1771 } catch (Resources.NotFoundException e) {
1772 Log.w("PackageManager", "Failure retrieving resources for "
1773 + appInfo.packageName + ": " + e.getMessage());
1774 } catch (Exception e) {
1775 // If an exception was thrown, fall through to return
1776 // default icon.
1777 Log.w("PackageManager", "Failure retrieving icon 0x"
1778 + Integer.toHexString(resId) + " in package "
1779 + packageName, e);
1780 }
1781 }
1782
1783 return null;
1784 }
1785
1786 @Override public Drawable getActivityIcon(ComponentName activityName)
1787 throws NameNotFoundException {
1788 return getActivityInfo(activityName, sDefaultFlags).loadIcon(this);
1789 }
1790
1791 @Override public Drawable getActivityIcon(Intent intent)
1792 throws NameNotFoundException {
1793 if (intent.getComponent() != null) {
1794 return getActivityIcon(intent.getComponent());
1795 }
1796
1797 ResolveInfo info = resolveActivity(intent, MATCH_DEFAULT_ONLY);
1798 if (info != null) {
1799 return info.activityInfo.loadIcon(this);
1800 }
1801
1802 throw new NameNotFoundException(intent.toUri(0));
1803 }
1804
1805 @Override public Drawable getDefaultActivityIcon() {
1806 return mContext.getDrawable(com.android.internal.R.drawable.sym_def_app_icon);
1807 }
1808
1809 @Override public Drawable getApplicationIcon(ApplicationInfo info) {
1810 return info.loadIcon(this);
1811 }
1812
1813 @Override public Drawable getApplicationIcon(String packageName)
1814 throws NameNotFoundException {
1815 return getApplicationIcon(getApplicationInfo(packageName, sDefaultFlags));
1816 }
1817
1818 @Override
1819 public Drawable getActivityBanner(ComponentName activityName)
1820 throws NameNotFoundException {
1821 return getActivityInfo(activityName, sDefaultFlags).loadBanner(this);
1822 }
1823
1824 @Override
1825 public Drawable getActivityBanner(Intent intent)
1826 throws NameNotFoundException {
1827 if (intent.getComponent() != null) {
1828 return getActivityBanner(intent.getComponent());
1829 }
1830
1831 ResolveInfo info = resolveActivity(
1832 intent, MATCH_DEFAULT_ONLY);
1833 if (info != null) {
1834 return info.activityInfo.loadBanner(this);
1835 }
1836
1837 throw new NameNotFoundException(intent.toUri(0));
1838 }
1839
1840 @Override
1841 public Drawable getApplicationBanner(ApplicationInfo info) {
1842 return info.loadBanner(this);
1843 }
1844
1845 @Override
1846 public Drawable getApplicationBanner(String packageName)
1847 throws NameNotFoundException {
1848 return getApplicationBanner(getApplicationInfo(packageName, sDefaultFlags));
1849 }
1850
1851 @Override
1852 public Drawable getActivityLogo(ComponentName activityName)
1853 throws NameNotFoundException {
1854 return getActivityInfo(activityName, sDefaultFlags).loadLogo(this);
1855 }
1856
1857 @Override
1858 public Drawable getActivityLogo(Intent intent)
1859 throws NameNotFoundException {
1860 if (intent.getComponent() != null) {
1861 return getActivityLogo(intent.getComponent());
1862 }
1863
1864 ResolveInfo info = resolveActivity(intent, MATCH_DEFAULT_ONLY);
1865 if (info != null) {
1866 return info.activityInfo.loadLogo(this);
1867 }
1868
1869 throw new NameNotFoundException(intent.toUri(0));
1870 }
1871
1872 @Override
1873 public Drawable getApplicationLogo(ApplicationInfo info) {
1874 return info.loadLogo(this);
1875 }
1876
1877 @Override
1878 public Drawable getApplicationLogo(String packageName)
1879 throws NameNotFoundException {
1880 return getApplicationLogo(getApplicationInfo(packageName, sDefaultFlags));
1881 }
1882
1883 @Override
1884 public Drawable getUserBadgedIcon(Drawable icon, UserHandle user) {
1885 if (!hasUserBadge(user.getIdentifier())) {
1886 return icon;
1887 }
1888
1889 final Drawable badgeForeground = getDevicePolicyManager().getResources().getDrawable(
1890 getUpdatableUserIconBadgeId(user),
1891 SOLID_COLORED,
1892 () -> getDefaultUserIconBadge(user));
1893
1894 Drawable badge = new LauncherIcons(mContext).getBadgeDrawable(
1895 badgeForeground,
1896 getUserBadgeColor(user, false));
1897 return getBadgedDrawable(icon, badge, null, true);
1898 }
1899
1900 private String getUpdatableUserIconBadgeId(UserHandle user) {
1901 return getUserManager().isManagedProfile(user.getIdentifier())
1902 ? WORK_PROFILE_ICON_BADGE : UNDEFINED;
1903 }
1904
1905 private Drawable getDefaultUserIconBadge(UserHandle user) {
1906 return mContext.getDrawable(getUserManager().getUserIconBadgeResId(user.getIdentifier()));
1907 }
1908
1909 @Override
1910 public Drawable getUserBadgedDrawableForDensity(Drawable drawable, UserHandle user,
1911 Rect badgeLocation, int badgeDensity) {
1912 Drawable badgeDrawable = getUserBadgeForDensity(user, badgeDensity);
1913 if (badgeDrawable == null) {
1914 return drawable;
1915 }
1916 return getBadgedDrawable(drawable, badgeDrawable, badgeLocation, true);
1917 }
1918
1919 /**
1920 * Returns the color of the user's actual badge (not the badge's shadow).
1921 * @param checkTheme whether to check the theme to determine the badge color. This should be
1922 * true if the background is determined by the theme. Otherwise, if
1923 * checkTheme is false, returns the color assuming a light background.
1924 */
1925 private int getUserBadgeColor(UserHandle user, boolean checkTheme) {
1926 if (checkTheme && mContext.getResources().getConfiguration().isNightModeActive()) {
1927 return getUserManager().getUserBadgeDarkColor(user.getIdentifier());
1928 }
1929 return getUserManager().getUserBadgeColor(user.getIdentifier());
1930 }
1931
1932 @Override
1933 public Drawable getUserBadgeForDensity(UserHandle user, int density) {
1934 // This is part of the shadow, not the main color, and is not actually corp-specific.
1935 Drawable badgeColor = getProfileIconForDensity(user,
1936 com.android.internal.R.drawable.ic_corp_badge_color, density);
1937 if (badgeColor == null) {
1938 return null;
1939 }
1940
1941 final Drawable badgeForeground = getDevicePolicyManager().getResources()
1942 .getDrawableForDensity(
1943 getUpdatableUserBadgeId(user),
1944 SOLID_COLORED,
1945 density,
1946 () -> getDefaultUserBadgeForDensity(user, density));
1947
1948 badgeForeground.setTint(getUserBadgeColor(user, false));
1949 Drawable badge = new LayerDrawable(new Drawable[] {badgeColor, badgeForeground });
1950 return badge;
1951 }
1952
1953 private String getUpdatableUserBadgeId(UserHandle user) {
1954 return getUserManager().isManagedProfile(user.getIdentifier())
1955 ? WORK_PROFILE_ICON : UNDEFINED;
1956 }
1957
1958 private Drawable getDefaultUserBadgeForDensity(UserHandle user, int density) {
1959 return getDrawableForDensity(
1960 getUserManager().getUserBadgeResId(user.getIdentifier()), density);
1961 }
1962
1963 /**
1964 * Returns the badge color based on whether device has dark theme enabled or not.
1965 */
1966 @Override
1967 public Drawable getUserBadgeForDensityNoBackground(UserHandle user, int density) {
1968 if (!hasUserBadge(user.getIdentifier())) {
1969 return null;
1970 }
1971
1972 final Drawable badge = getDevicePolicyManager().getResources().getDrawableForDensity(
1973 getUpdatableUserBadgeId(user),
1974 SOLID_NOT_COLORED,
1975 density,
1976 () -> getDefaultUserBadgeNoBackgroundForDensity(user, density));
1977
1978 if (badge != null) {
1979 badge.setTint(getUserBadgeColor(user, true));
1980 }
1981 return badge;
1982 }
1983
1984 private Drawable getDefaultUserBadgeNoBackgroundForDensity(UserHandle user, int density) {
1985 return getDrawableForDensity(
1986 getUserManager().getUserBadgeNoBackgroundResId(user.getIdentifier()), density);
1987 }
1988
1989 private Drawable getDrawableForDensity(int drawableId, int density) {
1990 if (density <= 0) {
1991 density = mContext.getResources().getDisplayMetrics().densityDpi;
1992 }
1993 return mContext.getResources().getDrawableForDensity(drawableId, density);
1994 }
1995
1996 private Drawable getProfileIconForDensity(UserHandle user, int drawableId, int density) {
1997 if (hasUserBadge(user.getIdentifier())) {
1998 return getDrawableForDensity(drawableId, density);
1999 }
2000 return null;
2001 }
2002
2003 @Override
2004 public CharSequence getUserBadgedLabel(CharSequence label, UserHandle user) {
2005 return getUserManager().getBadgedLabelForUser(label, user);
2006 }
2007
2008 @Override
2009 public Resources getResourcesForActivity(ComponentName activityName)
2010 throws NameNotFoundException {
2011 return getResourcesForApplication(
2012 getActivityInfo(activityName, sDefaultFlags).applicationInfo);
2013 }
2014
2015 @Override
2016 public Resources getResourcesForApplication(@NonNull ApplicationInfo app)
2017 throws NameNotFoundException {
2018 return getResourcesForApplication(app, null);
2019 }
2020
2021 @Override
2022 public Resources getResourcesForApplication(@NonNull ApplicationInfo app,
2023 @Nullable Configuration configuration) throws NameNotFoundException {
2024 if (app.packageName.equals("system")) {
2025 Context sysuiContext = mContext.mMainThread.getSystemUiContext();
2026 if (configuration != null) {
2027 sysuiContext = sysuiContext.createConfigurationContext(configuration);
2028 }
2029 return sysuiContext.getResources();
2030 }
2031 final boolean sameUid = (app.uid == Process.myUid());
2032 final Resources r = mContext.mMainThread.getTopLevelResources(
2033 sameUid ? app.sourceDir : app.publicSourceDir,
2034 sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
2035 app.resourceDirs, app.overlayPaths, app.sharedLibraryFiles,
2036 mContext.mPackageInfo, configuration);
2037 if (r != null) {
2038 return r;
2039 }
2040 throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
2041 }
2042
2043 @Override
2044 public Resources getResourcesForApplication(String appPackageName)
2045 throws NameNotFoundException {
2046 return getResourcesForApplication(
2047 getApplicationInfo(appPackageName, sDefaultFlags));
2048 }
2049
2050 /** @hide */
2051 @Override
2052 public Resources getResourcesForApplicationAsUser(String appPackageName, int userId)
2053 throws NameNotFoundException {
2054 if (userId < 0) {
2055 throw new IllegalArgumentException(
2056 "Call does not support special user #" + userId);
2057 }
2058 if ("system".equals(appPackageName)) {
2059 return mContext.mMainThread.getSystemUiContext().getResources();
2060 }
2061 try {
2062 ApplicationInfo ai = mPM.getApplicationInfo(appPackageName, sDefaultFlags, userId);
2063 if (ai != null) {
2064 return getResourcesForApplication(ai);
2065 }
2066 } catch (RemoteException e) {
2067 throw e.rethrowFromSystemServer();
2068 }
2069 throw new NameNotFoundException("Package " + appPackageName + " doesn't exist");
2070 }
2071
2072 volatile int mCachedSafeMode = -1;
2073
2074 @Override
2075 public boolean isSafeMode() {
2076 try {
2077 if (mCachedSafeMode < 0) {
2078 mCachedSafeMode = mPM.isSafeMode() ? 1 : 0;
2079 }
2080 return mCachedSafeMode != 0;
2081 } catch (RemoteException e) {
2082 throw e.rethrowFromSystemServer();
2083 }
2084 }
2085
2086 @Override
2087 public void addOnPermissionsChangeListener(OnPermissionsChangedListener listener) {
2088 getPermissionManager().addOnPermissionsChangeListener(listener);
2089 }
2090
2091 @Override
2092 public void removeOnPermissionsChangeListener(OnPermissionsChangedListener listener) {
2093 getPermissionManager().removeOnPermissionsChangeListener(listener);
2094 }
2095
2096 @UnsupportedAppUsage
2097 static void configurationChanged() {
2098 synchronized (sSync) {
2099 sIconCache.clear();
2100 sStringCache.clear();
2101 }
2102 }
2103
2104 @UnsupportedAppUsage
2105 protected ApplicationPackageManager(ContextImpl context, IPackageManager pm) {
2106 mContext = context;
2107 mPM = pm;
2108 }
2109
2110 /**
2111 * Update given flags when being used to request {@link PackageInfo}.
2112 */
2113 private long updateFlagsForPackage(long flags, int userId) {
2114 if ((flags & (GET_ACTIVITIES | GET_RECEIVERS | GET_SERVICES | GET_PROVIDERS)) != 0) {
2115 // Caller is asking for component details, so they'd better be
2116 // asking for specific Direct Boot matching behavior
2117 if ((flags & (MATCH_DIRECT_BOOT_UNAWARE
2118 | MATCH_DIRECT_BOOT_AWARE
2119 | MATCH_DIRECT_BOOT_AUTO)) == 0) {
2120 onImplicitDirectBoot(userId);
2121 }
2122 }
2123 return flags;
2124 }
2125
2126 /**
2127 * Update given flags when being used to request {@link ApplicationInfo}.
2128 */
2129 private long updateFlagsForApplication(long flags, int userId) {
2130 return updateFlagsForPackage(flags, userId);
2131 }
2132
2133 /**
2134 * Update given flags when being used to request {@link ComponentInfo}.
2135 */
2136 private long updateFlagsForComponent(@ComponentInfoFlagsBits long flags, int userId,
2137 Intent intent) {
2138 if (intent != null) {
2139 if ((intent.getFlags() & Intent.FLAG_DIRECT_BOOT_AUTO) != 0) {
2140 flags |= MATCH_DIRECT_BOOT_AUTO;
2141 }
2142 }
2143
2144 // Caller is asking for component details, so they'd better be
2145 // asking for specific Direct Boot matching behavior
2146 if ((flags & (MATCH_DIRECT_BOOT_UNAWARE
2147 | MATCH_DIRECT_BOOT_AWARE
2148 | MATCH_DIRECT_BOOT_AUTO)) == 0) {
2149 onImplicitDirectBoot(userId);
2150 }
2151 return flags;
2152 }
2153
2154 private void onImplicitDirectBoot(int userId) {
2155 // Only report if someone is relying on implicit behavior while the user
2156 // is locked; code running when unlocked is going to see both aware and
2157 // unaware components.
2158 if (StrictMode.vmImplicitDirectBootEnabled()) {
2159 // We can cache the unlocked state for the userId we're running as,
2160 // since any relocking of that user will always result in our
2161 // process being killed to release any CE FDs we're holding onto.
2162 if (userId == UserHandle.myUserId()) {
2163 if (mUserUnlocked) {
2164 return;
2165 } else if (mContext.getSystemService(UserManager.class)
2166 .isUserUnlockingOrUnlocked(userId)) {
2167 mUserUnlocked = true;
2168 } else {
2169 StrictMode.onImplicitDirectBoot();
2170 }
2171 } else if (!mContext.getSystemService(UserManager.class)
2172 .isUserUnlockingOrUnlocked(userId)) {
2173 StrictMode.onImplicitDirectBoot();
2174 }
2175 }
2176 }
2177
2178 @Nullable
2179 private Drawable getCachedIcon(@NonNull ResourceName name) {
2180 synchronized (sSync) {
2181 final WeakReference<Drawable.ConstantState> wr = sIconCache.get(name);
2182 if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for "
2183 + name + ": " + wr);
2184 if (wr != null) { // we have the activity
2185 final Drawable.ConstantState state = wr.get();
2186 if (state != null) {
2187 if (DEBUG_ICONS) {
2188 Log.v(TAG, "Get cached drawable state for " + name + ": " + state);
2189 }
2190 // Note: It's okay here to not use the newDrawable(Resources) variant
2191 // of the API. The ConstantState comes from a drawable that was
2192 // originally created by passing the proper app Resources instance
2193 // which means the state should already contain the proper
2194 // resources specific information (like density.) See
2195 // BitmapDrawable.BitmapState for instance.
2196 return state.newDrawable();
2197 }
2198 // our entry has been purged
2199 sIconCache.remove(name);
2200 }
2201 }
2202 return null;
2203 }
2204
2205 private void putCachedIcon(@NonNull ResourceName name, @NonNull Drawable dr) {
2206 synchronized (sSync) {
2207 sIconCache.put(name, new WeakReference<>(dr.getConstantState()));
2208 if (DEBUG_ICONS) Log.v(TAG, "Added cached drawable state for " + name + ": " + dr);
2209 }
2210 }
2211
2212 static void handlePackageBroadcast(int cmd, String[] pkgList, boolean hasPkgInfo) {
2213 boolean immediateGc = false;
2214 if (cmd == ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE) {
2215 immediateGc = true;
2216 }
2217 if (pkgList != null && (pkgList.length > 0)) {
2218 boolean needCleanup = false;
2219 for (String ssp : pkgList) {
2220 synchronized (sSync) {
2221 for (int i=sIconCache.size()-1; i>=0; i--) {
2222 ResourceName nm = sIconCache.keyAt(i);
2223 if (nm.packageName.equals(ssp)) {
2224 //Log.i(TAG, "Removing cached drawable for " + nm);
2225 sIconCache.removeAt(i);
2226 needCleanup = true;
2227 }
2228 }
2229 for (int i=sStringCache.size()-1; i>=0; i--) {
2230 ResourceName nm = sStringCache.keyAt(i);
2231 if (nm.packageName.equals(ssp)) {
2232 //Log.i(TAG, "Removing cached string for " + nm);
2233 sStringCache.removeAt(i);
2234 needCleanup = true;
2235 }
2236 }
2237 }
2238 }
2239 if (needCleanup || hasPkgInfo) {
2240 if (immediateGc) {
2241 // Schedule an immediate gc.
2242 Runtime.getRuntime().gc();
2243 } else {
2244 ActivityThread.currentActivityThread().scheduleGcIdler();
2245 }
2246 }
2247 }
2248 }
2249
2250 private static final class ResourceName {
2251 final String packageName;
2252 final int iconId;
2253
2254 ResourceName(String _packageName, int _iconId) {
2255 packageName = _packageName;
2256 iconId = _iconId;
2257 }
2258
2259 ResourceName(ApplicationInfo aInfo, int _iconId) {
2260 this(aInfo.packageName, _iconId);
2261 }
2262
2263 ResourceName(ComponentInfo cInfo, int _iconId) {
2264 this(cInfo.applicationInfo.packageName, _iconId);
2265 }
2266
2267 ResourceName(ResolveInfo rInfo, int _iconId) {
2268 this(rInfo.activityInfo.applicationInfo.packageName, _iconId);
2269 }
2270
2271 @Override
2272 public boolean equals(@Nullable Object o) {
2273 if (this == o) return true;
2274 if (o == null || getClass() != o.getClass()) return false;
2275
2276 ResourceName that = (ResourceName) o;
2277
2278 if (iconId != that.iconId) return false;
2279 return !(packageName != null ?
2280 !packageName.equals(that.packageName) : that.packageName != null);
2281
2282 }
2283
2284 @Override
2285 public int hashCode() {
2286 int result;
2287 result = packageName.hashCode();
2288 result = 31 * result + iconId;
2289 return result;
2290 }
2291
2292 @Override
2293 public String toString() {
2294 return "{ResourceName " + packageName + " / " + iconId + "}";
2295 }
2296 }
2297
2298 private CharSequence getCachedString(ResourceName name) {
2299 synchronized (sSync) {
2300 WeakReference<CharSequence> wr = sStringCache.get(name);
2301 if (wr != null) { // we have the activity
2302 CharSequence cs = wr.get();
2303 if (cs != null) {
2304 return cs;
2305 }
2306 // our entry has been purged
2307 sStringCache.remove(name);
2308 }
2309 }
2310 return null;
2311 }
2312
2313 private void putCachedString(ResourceName name, CharSequence cs) {
2314 synchronized (sSync) {
2315 sStringCache.put(name, new WeakReference<CharSequence>(cs));
2316 }
2317 }
2318
2319 @Override
2320 public CharSequence getText(String packageName, @StringRes int resid,
2321 ApplicationInfo appInfo) {
2322 ResourceName name = new ResourceName(packageName, resid);
2323 CharSequence text = getCachedString(name);
2324 if (text != null) {
2325 return text;
2326 }
2327 if (appInfo == null) {
2328 try {
2329 appInfo = getApplicationInfo(packageName, sDefaultFlags);
2330 } catch (NameNotFoundException e) {
2331 return null;
2332 }
2333 }
2334 try {
2335 Resources r = getResourcesForApplication(appInfo);
2336 text = r.getText(resid);
2337 putCachedString(name, text);
2338 return text;
2339 } catch (NameNotFoundException e) {
2340 Log.w("PackageManager", "Failure retrieving resources for "
2341 + appInfo.packageName);
2342 } catch (RuntimeException e) {
2343 // If an exception was thrown, fall through to return
2344 // default icon.
2345 Log.w("PackageManager", "Failure retrieving text 0x"
2346 + Integer.toHexString(resid) + " in package "
2347 + packageName, e);
2348 }
2349 return null;
2350 }
2351
2352 @Override
2353 public XmlResourceParser getXml(String packageName, @XmlRes int resid,
2354 ApplicationInfo appInfo) {
2355 if (appInfo == null) {
2356 try {
2357 appInfo = getApplicationInfo(packageName, sDefaultFlags);
2358 } catch (NameNotFoundException e) {
2359 return null;
2360 }
2361 }
2362 try {
2363 Resources r = getResourcesForApplication(appInfo);
2364 return r.getXml(resid);
2365 } catch (RuntimeException e) {
2366 // If an exception was thrown, fall through to return
2367 // default icon.
2368 Log.w("PackageManager", "Failure retrieving xml 0x"
2369 + Integer.toHexString(resid) + " in package "
2370 + packageName, e);
2371 } catch (NameNotFoundException e) {
2372 Log.w("PackageManager", "Failure retrieving resources for "
2373 + appInfo.packageName);
2374 }
2375 return null;
2376 }
2377
2378 @Override
2379 public CharSequence getApplicationLabel(ApplicationInfo info) {
2380 return info.loadLabel(this);
2381 }
2382
2383 @Override
2384 public int installExistingPackage(String packageName) throws NameNotFoundException {
2385 return installExistingPackage(packageName, INSTALL_REASON_UNKNOWN);
2386 }
2387
2388 @Override
2389 public int installExistingPackage(String packageName, int installReason)
2390 throws NameNotFoundException {
2391 return installExistingPackageAsUser(packageName, installReason, getUserId());
2392 }
2393
2394 @Override
2395 public int installExistingPackageAsUser(String packageName, int userId)
2396 throws NameNotFoundException {
2397 return installExistingPackageAsUser(packageName, INSTALL_REASON_UNKNOWN,
2398 userId);
2399 }
2400
2401 private int installExistingPackageAsUser(String packageName, int installReason, int userId)
2402 throws NameNotFoundException {
2403 try {
2404 int res = mPM.installExistingPackageAsUser(packageName, userId,
2405 INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, installReason, null);
2406 if (res == INSTALL_FAILED_INVALID_URI) {
2407 throw new NameNotFoundException("Package " + packageName + " doesn't exist");
2408 }
2409 return res;
2410 } catch (RemoteException e) {
2411 throw e.rethrowFromSystemServer();
2412 }
2413 }
2414
2415 @Override
2416 public void verifyPendingInstall(int id, int response) {
2417 try {
2418 mPM.verifyPendingInstall(id, response);
2419 } catch (RemoteException e) {
2420 throw e.rethrowFromSystemServer();
2421 }
2422 }
2423
2424 @Override
2425 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
2426 long millisecondsToDelay) {
2427 try {
2428 mPM.extendVerificationTimeout(id, verificationCodeAtTimeout, millisecondsToDelay);
2429 } catch (RemoteException e) {
2430 throw e.rethrowFromSystemServer();
2431 }
2432 }
2433
2434 @Override
2435 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) {
2436 try {
2437 mPM.verifyIntentFilter(id, verificationCode, failedDomains);
2438 } catch (RemoteException e) {
2439 throw e.rethrowFromSystemServer();
2440 }
2441 }
2442
2443 @Override
2444 public int getIntentVerificationStatusAsUser(String packageName, int userId) {
2445 try {
2446 return mPM.getIntentVerificationStatus(packageName, userId);
2447 } catch (RemoteException e) {
2448 throw e.rethrowFromSystemServer();
2449 }
2450 }
2451
2452 @Override
2453 public boolean updateIntentVerificationStatusAsUser(String packageName, int status, int userId) {
2454 try {
2455 return mPM.updateIntentVerificationStatus(packageName, status, userId);
2456 } catch (RemoteException e) {
2457 throw e.rethrowFromSystemServer();
2458 }
2459 }
2460
2461 @Override
2462 @SuppressWarnings("unchecked")
2463 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
2464 try {
2465 ParceledListSlice<IntentFilterVerificationInfo> parceledList =
2466 mPM.getIntentFilterVerifications(packageName);
2467 if (parceledList == null) {
2468 return Collections.emptyList();
2469 }
2470 return parceledList.getList();
2471 } catch (RemoteException e) {
2472 throw e.rethrowFromSystemServer();
2473 }
2474 }
2475
2476 @Override
2477 @SuppressWarnings("unchecked")
2478 public List<IntentFilter> getAllIntentFilters(String packageName) {
2479 try {
2480 ParceledListSlice<IntentFilter> parceledList =
2481 mPM.getAllIntentFilters(packageName);
2482 if (parceledList == null) {
2483 return Collections.emptyList();
2484 }
2485 return parceledList.getList();
2486 } catch (RemoteException e) {
2487 throw e.rethrowFromSystemServer();
2488 }
2489 }
2490
2491 @Override
2492 public String getDefaultBrowserPackageNameAsUser(int userId) {
2493 RoleManager roleManager = mContext.getSystemService(RoleManager.class);
2494 return roleManager.getBrowserRoleHolder(userId);
2495 }
2496
2497 @Override
2498 public boolean setDefaultBrowserPackageNameAsUser(String packageName, int userId) {
2499 RoleManager roleManager = mContext.getSystemService(RoleManager.class);
2500 return roleManager.setBrowserRoleHolder(packageName, userId);
2501 }
2502
2503 @Override
2504 public void setInstallerPackageName(String targetPackage,
2505 String installerPackageName) {
2506 try {
2507 mPM.setInstallerPackageName(targetPackage, installerPackageName);
2508 } catch (RemoteException e) {
2509 throw e.rethrowFromSystemServer();
2510 }
2511 }
2512
2513 @Override
2514 public void setUpdateAvailable(String packageName, boolean updateAvailable) {
2515 try {
2516 mPM.setUpdateAvailable(packageName, updateAvailable);
2517 } catch (RemoteException e) {
2518 throw e.rethrowFromSystemServer();
2519 }
2520 }
2521
2522 @Override
2523 public String getInstallerPackageName(String packageName) {
2524 try {
2525 return mPM.getInstallerPackageName(packageName);
2526 } catch (RemoteException e) {
2527 throw e.rethrowFromSystemServer();
2528 }
2529 }
2530
2531 @Override
2532 @NonNull
2533 public InstallSourceInfo getInstallSourceInfo(String packageName) throws NameNotFoundException {
2534 final InstallSourceInfo installSourceInfo;
2535 try {
2536 installSourceInfo = mPM.getInstallSourceInfo(packageName);
2537 } catch (RemoteException e) {
2538 throw e.rethrowFromSystemServer();
2539 }
2540 if (installSourceInfo == null) {
2541 throw new NameNotFoundException(packageName);
2542 }
2543 return installSourceInfo;
2544 }
2545
2546 @Override
2547 public int getMoveStatus(int moveId) {
2548 try {
2549 return mPM.getMoveStatus(moveId);
2550 } catch (RemoteException e) {
2551 throw e.rethrowFromSystemServer();
2552 }
2553 }
2554
2555 @Override
2556 public void registerMoveCallback(MoveCallback callback, Handler handler) {
2557 synchronized (mDelegates) {
2558 final MoveCallbackDelegate delegate = new MoveCallbackDelegate(callback,
2559 handler.getLooper());
2560 try {
2561 mPM.registerMoveCallback(delegate);
2562 } catch (RemoteException e) {
2563 throw e.rethrowFromSystemServer();
2564 }
2565 mDelegates.add(delegate);
2566 }
2567 }
2568
2569 @Override
2570 public void unregisterMoveCallback(MoveCallback callback) {
2571 synchronized (mDelegates) {
2572 for (Iterator<MoveCallbackDelegate> i = mDelegates.iterator(); i.hasNext();) {
2573 final MoveCallbackDelegate delegate = i.next();
2574 if (delegate.mCallback == callback) {
2575 try {
2576 mPM.unregisterMoveCallback(delegate);
2577 } catch (RemoteException e) {
2578 throw e.rethrowFromSystemServer();
2579 }
2580 i.remove();
2581 }
2582 }
2583 }
2584 }
2585
2586 @Override
2587 public int movePackage(String packageName, VolumeInfo vol) {
2588 try {
2589 final String volumeUuid;
2590 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
2591 volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
2592 } else if (vol.isPrimaryPhysical()) {
2593 volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
2594 } else {
2595 volumeUuid = Objects.requireNonNull(vol.fsUuid);
2596 }
2597
2598 return mPM.movePackage(packageName, volumeUuid);
2599 } catch (RemoteException e) {
2600 throw e.rethrowFromSystemServer();
2601 }
2602 }
2603
2604 @Override
2605 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2606 public @Nullable VolumeInfo getPackageCurrentVolume(ApplicationInfo app) {
2607 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2608 return getPackageCurrentVolume(app, storage);
2609 }
2610
2611 @VisibleForTesting
2612 protected @Nullable VolumeInfo getPackageCurrentVolume(ApplicationInfo app,
2613 StorageManager storage) {
2614 if (app.isInternal()) {
2615 return storage.findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL);
2616 } else {
2617 return storage.findVolumeByUuid(app.volumeUuid);
2618 }
2619 }
2620
2621 @Override
2622 public @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app) {
2623 final StorageManager storageManager = mContext.getSystemService(StorageManager.class);
2624 return getPackageCandidateVolumes(app, storageManager, mPM);
2625 }
2626
2627 @VisibleForTesting
2628 protected @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app,
2629 StorageManager storageManager, IPackageManager pm) {
2630 final VolumeInfo currentVol = getPackageCurrentVolume(app, storageManager);
2631 final List<VolumeInfo> vols = storageManager.getVolumes();
2632 final List<VolumeInfo> candidates = new ArrayList<>();
2633 for (VolumeInfo vol : vols) {
2634 if (Objects.equals(vol, currentVol)
2635 || isPackageCandidateVolume(mContext, app, vol, pm)) {
2636 candidates.add(vol);
2637 }
2638 }
2639 return candidates;
2640 }
2641
2642 @VisibleForTesting
2643 protected boolean isForceAllowOnExternal(Context context) {
2644 return Settings.Global.getInt(
2645 context.getContentResolver(), Settings.Global.FORCE_ALLOW_ON_EXTERNAL, 0) != 0;
2646 }
2647
2648 @VisibleForTesting
2649 protected boolean isAllow3rdPartyOnInternal(Context context) {
2650 return context.getResources().getBoolean(
2651 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
2652 }
2653
2654 private boolean isPackageCandidateVolume(
2655 ContextImpl context, ApplicationInfo app, VolumeInfo vol, IPackageManager pm) {
2656 final boolean forceAllowOnExternal = isForceAllowOnExternal(context);
2657
2658 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.getId())) {
2659 return app.isSystemApp() || isAllow3rdPartyOnInternal(context);
2660 }
2661
2662 // System apps and apps demanding internal storage can't be moved
2663 // anywhere else
2664 if (app.isSystemApp()) {
2665 return false;
2666 }
2667 if (!forceAllowOnExternal
2668 && (app.installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY
2669 || app.installLocation == PackageInfo.INSTALL_LOCATION_UNSPECIFIED)) {
2670 return false;
2671 }
2672
2673 // Gotta be able to write there
2674 if (!vol.isMountedWritable()) {
2675 return false;
2676 }
2677
2678 // Moving into an ASEC on public primary is only option internal
2679 if (vol.isPrimaryPhysical()) {
2680 return app.isInternal();
2681 }
2682
2683 // Some apps can't be moved. (e.g. device admins)
2684 try {
2685 if (pm.isPackageDeviceAdminOnAnyUser(app.packageName)) {
2686 return false;
2687 }
2688 } catch (RemoteException e) {
2689 throw e.rethrowFromSystemServer();
2690 }
2691
2692 // Otherwise we can move to any private volume
2693 return (vol.getType() == VolumeInfo.TYPE_PRIVATE);
2694 }
2695
2696 @Override
2697 public int movePrimaryStorage(VolumeInfo vol) {
2698 try {
2699 final String volumeUuid;
2700 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
2701 volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
2702 } else if (vol.isPrimaryPhysical()) {
2703 volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
2704 } else {
2705 volumeUuid = Objects.requireNonNull(vol.fsUuid);
2706 }
2707
2708 return mPM.movePrimaryStorage(volumeUuid);
2709 } catch (RemoteException e) {
2710 throw e.rethrowFromSystemServer();
2711 }
2712 }
2713
2714 @Override
2715 public @Nullable VolumeInfo getPrimaryStorageCurrentVolume() {
2716 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2717 final String volumeUuid = storage.getPrimaryStorageUuid();
2718 return storage.findVolumeByQualifiedUuid(volumeUuid);
2719 }
2720
2721 @Override
2722 public @NonNull List<VolumeInfo> getPrimaryStorageCandidateVolumes() {
2723 final StorageManager storage = mContext.getSystemService(StorageManager.class);
2724 final VolumeInfo currentVol = getPrimaryStorageCurrentVolume();
2725 final List<VolumeInfo> vols = storage.getVolumes();
2726 final List<VolumeInfo> candidates = new ArrayList<>();
2727 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL,
2728 storage.getPrimaryStorageUuid()) && currentVol != null) {
2729 // TODO: support moving primary physical to emulated volume
2730 candidates.add(currentVol);
2731 } else {
2732 for (VolumeInfo vol : vols) {
2733 if (Objects.equals(vol, currentVol) || isPrimaryStorageCandidateVolume(vol)) {
2734 candidates.add(vol);
2735 }
2736 }
2737 }
2738 return candidates;
2739 }
2740
2741 private static boolean isPrimaryStorageCandidateVolume(VolumeInfo vol) {
2742 // Private internal is always an option
2743 if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.getId())) {
2744 return true;
2745 }
2746
2747 // Gotta be able to write there
2748 if (!vol.isMountedWritable()) {
2749 return false;
2750 }
2751
2752 // We can move to any private volume
2753 return (vol.getType() == VolumeInfo.TYPE_PRIVATE);
2754 }
2755
2756 @Override
2757 @UnsupportedAppUsage
2758 public void deletePackage(String packageName, IPackageDeleteObserver observer, int flags) {
2759 deletePackageAsUser(packageName, observer, flags, getUserId());
2760 }
2761
2762 @Override
2763 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer,
2764 int flags, int userId) {
2765 try {
2766 mPM.deletePackageAsUser(packageName, VERSION_CODE_HIGHEST,
2767 observer, userId, flags);
2768 } catch (RemoteException e) {
2769 throw e.rethrowFromSystemServer();
2770 }
2771 }
2772
2773 @Override
2774 public void clearApplicationUserData(String packageName,
2775 IPackageDataObserver observer) {
2776 try {
2777 mPM.clearApplicationUserData(packageName, observer, getUserId());
2778 } catch (RemoteException e) {
2779 throw e.rethrowFromSystemServer();
2780 }
2781 }
2782 @Override
2783 public void deleteApplicationCacheFiles(String packageName,
2784 IPackageDataObserver observer) {
2785 try {
2786 mPM.deleteApplicationCacheFiles(packageName, observer);
2787 } catch (RemoteException e) {
2788 throw e.rethrowFromSystemServer();
2789 }
2790 }
2791
2792 @Override
2793 public void deleteApplicationCacheFilesAsUser(String packageName, int userId,
2794 IPackageDataObserver observer) {
2795 try {
2796 mPM.deleteApplicationCacheFilesAsUser(packageName, userId, observer);
2797 } catch (RemoteException e) {
2798 throw e.rethrowFromSystemServer();
2799 }
2800 }
2801
2802 @Override
2803 public void freeStorageAndNotify(String volumeUuid, long idealStorageSize,
2804 IPackageDataObserver observer) {
2805 try {
2806 mPM.freeStorageAndNotify(volumeUuid, idealStorageSize, 0, observer);
2807 } catch (RemoteException e) {
2808 throw e.rethrowFromSystemServer();
2809 }
2810 }
2811
2812 @Override
2813 public void freeStorage(String volumeUuid, long freeStorageSize, IntentSender pi) {
2814 try {
2815 mPM.freeStorage(volumeUuid, freeStorageSize, 0, pi);
2816 } catch (RemoteException e) {
2817 throw e.rethrowFromSystemServer();
2818 }
2819 }
2820
2821 @Override
2822 public String[] setDistractingPackageRestrictions(String[] packages, int distractionFlags) {
2823 try {
2824 return mPM.setDistractingPackageRestrictionsAsUser(packages, distractionFlags,
2825 mContext.getUserId());
2826 } catch (RemoteException e) {
2827 throw e.rethrowFromSystemServer();
2828 }
2829 }
2830
2831 @Override
2832 public String[] setPackagesSuspended(String[] packageNames, boolean suspended,
2833 PersistableBundle appExtras, PersistableBundle launcherExtras,
2834 String dialogMessage) {
2835 final SuspendDialogInfo dialogInfo = !TextUtils.isEmpty(dialogMessage)
2836 ? new SuspendDialogInfo.Builder().setMessage(dialogMessage).build()
2837 : null;
2838 return setPackagesSuspended(packageNames, suspended, appExtras, launcherExtras, dialogInfo);
2839 }
2840
2841 @Override
2842 public String[] setPackagesSuspended(String[] packageNames, boolean suspended,
2843 PersistableBundle appExtras, PersistableBundle launcherExtras,
2844 SuspendDialogInfo dialogInfo) {
2845 try {
2846 return mPM.setPackagesSuspendedAsUser(packageNames, suspended, appExtras,
2847 launcherExtras, dialogInfo, mContext.getOpPackageName(),
2848 getUserId());
2849 } catch (RemoteException e) {
2850 throw e.rethrowFromSystemServer();
2851 }
2852 }
2853
2854 @Override
2855 public String[] getUnsuspendablePackages(String[] packageNames) {
2856 try {
2857 return mPM.getUnsuspendablePackagesForUser(packageNames, mContext.getUserId());
2858 } catch (RemoteException e) {
2859 throw e.rethrowFromSystemServer();
2860 }
2861 }
2862
2863 @Override
2864 public Bundle getSuspendedPackageAppExtras() {
2865 try {
2866 return mPM.getSuspendedPackageAppExtras(mContext.getOpPackageName(), getUserId());
2867 } catch (RemoteException e) {
2868 throw e.rethrowFromSystemServer();
2869 }
2870 }
2871
2872 @Override
2873 public boolean isPackageSuspendedForUser(String packageName, int userId) {
2874 try {
2875 return mPM.isPackageSuspendedForUser(packageName, userId);
2876 } catch (RemoteException e) {
2877 throw e.rethrowFromSystemServer();
2878 }
2879 }
2880
2881 /** @hide */
2882 @Override
2883 public boolean isPackageSuspended(String packageName) throws NameNotFoundException {
2884 try {
2885 return isPackageSuspendedForUser(packageName, getUserId());
2886 } catch (IllegalArgumentException ie) {
2887 throw new NameNotFoundException(packageName);
2888 }
2889 }
2890
2891 @Override
2892 public boolean isPackageSuspended() {
2893 return isPackageSuspendedForUser(mContext.getOpPackageName(), getUserId());
2894 }
2895
2896 /** @hide */
2897 @Override
2898 public void setApplicationCategoryHint(String packageName, int categoryHint) {
2899 try {
2900 mPM.setApplicationCategoryHint(packageName, categoryHint,
2901 mContext.getOpPackageName());
2902 } catch (RemoteException e) {
2903 throw e.rethrowFromSystemServer();
2904 }
2905 }
2906
2907 @Override
2908 @UnsupportedAppUsage
2909 public void getPackageSizeInfoAsUser(String packageName, int userHandle,
2910 IPackageStatsObserver observer) {
2911 final String msg = "Shame on you for calling the hidden API "
2912 + "getPackageSizeInfoAsUser(). Shame!";
2913 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) {
2914 throw new UnsupportedOperationException(msg);
2915 } else if (observer != null) {
2916 Log.d(TAG, msg);
2917 try {
2918 observer.onGetStatsCompleted(null, false);
2919 } catch (RemoteException ignored) {
2920 }
2921 }
2922 }
2923
2924 @Override
2925 public void addPackageToPreferred(String packageName) {
2926 Log.w(TAG, "addPackageToPreferred() is a no-op");
2927 }
2928
2929 @Override
2930 public void removePackageFromPreferred(String packageName) {
2931 Log.w(TAG, "removePackageFromPreferred() is a no-op");
2932 }
2933
2934 @Override
2935 public List<PackageInfo> getPreferredPackages(int flags) {
2936 Log.w(TAG, "getPreferredPackages() is a no-op");
2937 return Collections.emptyList();
2938 }
2939
2940 @Override
2941 public void addPreferredActivity(IntentFilter filter,
2942 int match, ComponentName[] set, ComponentName activity) {
2943 try {
2944 mPM.addPreferredActivity(filter, match, set, activity, getUserId(), false);
2945 } catch (RemoteException e) {
2946 throw e.rethrowFromSystemServer();
2947 }
2948 }
2949
2950 @Override
2951 public void addPreferredActivityAsUser(IntentFilter filter, int match,
2952 ComponentName[] set, ComponentName activity, int userId) {
2953 try {
2954 mPM.addPreferredActivity(filter, match, set, activity, userId, false);
2955 } catch (RemoteException e) {
2956 throw e.rethrowFromSystemServer();
2957 }
2958 }
2959
2960 @Override
2961 public void replacePreferredActivity(IntentFilter filter,
2962 int match, ComponentName[] set, ComponentName activity) {
2963 try {
2964 mPM.replacePreferredActivity(filter, match, set, activity, getUserId());
2965 } catch (RemoteException e) {
2966 throw e.rethrowFromSystemServer();
2967 }
2968 }
2969
2970 @Override
2971 public void replacePreferredActivityAsUser(IntentFilter filter,
2972 int match, ComponentName[] set, ComponentName activity,
2973 int userId) {
2974 try {
2975 mPM.replacePreferredActivity(filter, match, set, activity, userId);
2976 } catch (RemoteException e) {
2977 throw e.rethrowFromSystemServer();
2978 }
2979 }
2980
2981 @Override
2982 public void clearPackagePreferredActivities(String packageName) {
2983 try {
2984 mPM.clearPackagePreferredActivities(packageName);
2985 } catch (RemoteException e) {
2986 throw e.rethrowFromSystemServer();
2987 }
2988 }
2989
2990 @Override
2991 public void addUniquePreferredActivity(@NonNull IntentFilter filter, int match,
2992 @Nullable ComponentName[] set, @NonNull ComponentName activity) {
2993 try {
2994 mPM.addPreferredActivity(filter, match, set, activity, getUserId(), true);
2995 } catch (RemoteException e) {
2996 throw e.rethrowFromSystemServer();
2997 }
2998 }
2999
3000 @Override
3001 public int getPreferredActivities(List<IntentFilter> outFilters,
3002 List<ComponentName> outActivities, String packageName) {
3003 try {
3004 return mPM.getPreferredActivities(outFilters, outActivities, packageName);
3005 } catch (RemoteException e) {
3006 throw e.rethrowFromSystemServer();
3007 }
3008 }
3009
3010 @Override
3011 public ComponentName getHomeActivities(List<ResolveInfo> outActivities) {
3012 try {
3013 return mPM.getHomeActivities(outActivities);
3014 } catch (RemoteException e) {
3015 throw e.rethrowFromSystemServer();
3016 }
3017 }
3018
3019 @Override
3020 public void setSyntheticAppDetailsActivityEnabled(String packageName, boolean enabled) {
3021 try {
3022 ComponentName componentName = new ComponentName(packageName,
3023 APP_DETAILS_ACTIVITY_CLASS_NAME);
3024 mPM.setComponentEnabledSetting(componentName, enabled
3025 ? COMPONENT_ENABLED_STATE_DEFAULT
3026 : COMPONENT_ENABLED_STATE_DISABLED,
3027 DONT_KILL_APP, getUserId());
3028 } catch (RemoteException e) {
3029 throw e.rethrowFromSystemServer();
3030 }
3031 }
3032
3033 @Override
3034 public boolean getSyntheticAppDetailsActivityEnabled(String packageName) {
3035 try {
3036 ComponentName componentName = new ComponentName(packageName,
3037 APP_DETAILS_ACTIVITY_CLASS_NAME);
3038 int state = mPM.getComponentEnabledSetting(componentName, getUserId());
3039 return state == COMPONENT_ENABLED_STATE_ENABLED
3040 || state == COMPONENT_ENABLED_STATE_DEFAULT;
3041 } catch (RemoteException e) {
3042 throw e.rethrowFromSystemServer();
3043 }
3044 }
3045
3046 @Override
3047 public void setComponentEnabledSetting(ComponentName componentName,
3048 int newState, int flags) {
3049 try {
3050 mPM.setComponentEnabledSetting(componentName, newState, flags, getUserId());
3051 } catch (RemoteException e) {
3052 throw e.rethrowFromSystemServer();
3053 }
3054 }
3055
3056 @Override
3057 public void setComponentEnabledSettings(List<ComponentEnabledSetting> settings) {
3058 try {
3059 mPM.setComponentEnabledSettings(settings, getUserId());
3060 } catch (RemoteException e) {
3061 throw e.rethrowFromSystemServer();
3062 }
3063 }
3064
3065 @Override
3066 public int getComponentEnabledSetting(ComponentName componentName) {
3067 try {
3068 return mPM.getComponentEnabledSetting(componentName, getUserId());
3069 } catch (RemoteException e) {
3070 throw e.rethrowFromSystemServer();
3071 }
3072 }
3073
3074 @Override
3075 public void setApplicationEnabledSetting(String packageName,
3076 int newState, int flags) {
3077 try {
3078 mPM.setApplicationEnabledSetting(packageName, newState, flags,
3079 getUserId(), mContext.getOpPackageName());
3080 } catch (RemoteException e) {
3081 throw e.rethrowFromSystemServer();
3082 }
3083 }
3084
3085 @Override
3086 public int getApplicationEnabledSetting(String packageName) {
3087 try {
3088 return mPM.getApplicationEnabledSetting(packageName, getUserId());
3089 } catch (RemoteException e) {
3090 throw e.rethrowFromSystemServer();
3091 }
3092 }
3093
3094 @Override
3095 public void flushPackageRestrictionsAsUser(int userId) {
3096 try {
3097 mPM.flushPackageRestrictionsAsUser(userId);
3098 } catch (RemoteException e) {
3099 throw e.rethrowFromSystemServer();
3100 }
3101 }
3102
3103 @Override
3104 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
3105 UserHandle user) {
3106 try {
3107 return mPM.setApplicationHiddenSettingAsUser(packageName, hidden,
3108 user.getIdentifier());
3109 } catch (RemoteException e) {
3110 throw e.rethrowFromSystemServer();
3111 }
3112 }
3113
3114 @Override
3115 public boolean getApplicationHiddenSettingAsUser(String packageName, UserHandle user) {
3116 try {
3117 return mPM.getApplicationHiddenSettingAsUser(packageName, user.getIdentifier());
3118 } catch (RemoteException e) {
3119 throw e.rethrowFromSystemServer();
3120 }
3121 }
3122
3123 /** @hide */
3124 @Override
3125 public void setSystemAppState(String packageName, @SystemAppState int state) {
3126 try {
3127 switch (state) {
3128 case SYSTEM_APP_STATE_HIDDEN_UNTIL_INSTALLED_HIDDEN:
3129 mPM.setSystemAppHiddenUntilInstalled(packageName, true);
3130 break;
3131 case SYSTEM_APP_STATE_HIDDEN_UNTIL_INSTALLED_VISIBLE:
3132 mPM.setSystemAppHiddenUntilInstalled(packageName, false);
3133 break;
3134 case SYSTEM_APP_STATE_INSTALLED:
3135 mPM.setSystemAppInstallState(packageName, true, getUserId());
3136 break;
3137 case SYSTEM_APP_STATE_UNINSTALLED:
3138 mPM.setSystemAppInstallState(packageName, false, getUserId());
3139 break;
3140 default:
3141 }
3142 } catch (RemoteException e) {
3143 throw e.rethrowFromSystemServer();
3144 }
3145 }
3146
3147 /** @hide */
3148 @Override
3149 public KeySet getKeySetByAlias(String packageName, String alias) {
3150 Objects.requireNonNull(packageName);
3151 Objects.requireNonNull(alias);
3152 try {
3153 return mPM.getKeySetByAlias(packageName, alias);
3154 } catch (RemoteException e) {
3155 throw e.rethrowFromSystemServer();
3156 }
3157 }
3158
3159 /** @hide */
3160 @Override
3161 public KeySet getSigningKeySet(String packageName) {
3162 Objects.requireNonNull(packageName);
3163 try {
3164 return mPM.getSigningKeySet(packageName);
3165 } catch (RemoteException e) {
3166 throw e.rethrowFromSystemServer();
3167 }
3168 }
3169
3170 /** @hide */
3171 @Override
3172 public boolean isSignedBy(String packageName, KeySet ks) {
3173 Objects.requireNonNull(packageName);
3174 Objects.requireNonNull(ks);
3175 try {
3176 return mPM.isPackageSignedByKeySet(packageName, ks);
3177 } catch (RemoteException e) {
3178 throw e.rethrowFromSystemServer();
3179 }
3180 }
3181
3182 /** @hide */
3183 @Override
3184 public boolean isSignedByExactly(String packageName, KeySet ks) {
3185 Objects.requireNonNull(packageName);
3186 Objects.requireNonNull(ks);
3187 try {
3188 return mPM.isPackageSignedByKeySetExactly(packageName, ks);
3189 } catch (RemoteException e) {
3190 throw e.rethrowFromSystemServer();
3191 }
3192 }
3193
3194 /**
3195 * @hide
3196 */
3197 @Override
3198 public VerifierDeviceIdentity getVerifierDeviceIdentity() {
3199 try {
3200 return mPM.getVerifierDeviceIdentity();
3201 } catch (RemoteException e) {
3202 throw e.rethrowFromSystemServer();
3203 }
3204 }
3205
3206 @Override
3207 public boolean isUpgrade() {
3208 return isDeviceUpgrading();
3209 }
3210
3211 @Override
3212 public boolean isDeviceUpgrading() {
3213 try {
3214 return mPM.isDeviceUpgrading();
3215 } catch (RemoteException e) {
3216 throw e.rethrowFromSystemServer();
3217 }
3218 }
3219
3220 @Override
3221 public PackageInstaller getPackageInstaller() {
3222 if (mInstaller == null) {
3223 try {
3224 mInstaller = new PackageInstaller(mPM.getPackageInstaller(),
3225 mContext.getPackageName(), mContext.getAttributionTag(), getUserId());
3226 } catch (RemoteException e) {
3227 throw e.rethrowFromSystemServer();
3228 }
3229 }
3230 return mInstaller;
3231 }
3232
3233 @Override
3234 public boolean isPackageAvailable(String packageName) {
3235 try {
3236 return mPM.isPackageAvailable(packageName, getUserId());
3237 } catch (RemoteException e) {
3238 throw e.rethrowFromSystemServer();
3239 }
3240 }
3241
3242 /**
3243 * @hide
3244 */
3245 @Override
3246 public void addCrossProfileIntentFilter(IntentFilter filter, int sourceUserId, int targetUserId,
3247 int flags) {
3248 try {
3249 mPM.addCrossProfileIntentFilter(filter, mContext.getOpPackageName(),
3250 sourceUserId, targetUserId, flags);
3251 } catch (RemoteException e) {
3252 throw e.rethrowFromSystemServer();
3253 }
3254 }
3255
3256 /**
3257 * @hide
3258 */
3259 @Override
3260 public void clearCrossProfileIntentFilters(int sourceUserId) {
3261 try {
3262 mPM.clearCrossProfileIntentFilters(sourceUserId, mContext.getOpPackageName());
3263 } catch (RemoteException e) {
3264 throw e.rethrowFromSystemServer();
3265 }
3266 }
3267
3268 /**
3269 * @hide
3270 */
3271 public Drawable loadItemIcon(PackageItemInfo itemInfo, ApplicationInfo appInfo) {
3272 Drawable dr = loadUnbadgedItemIcon(itemInfo, appInfo);
3273 if (itemInfo.showUserIcon != UserHandle.USER_NULL) {
3274 return dr;
3275 }
3276 return getUserBadgedIcon(dr, new UserHandle(getUserId()));
3277 }
3278
3279 /**
3280 * @hide
3281 */
3282 public Drawable loadUnbadgedItemIcon(@NonNull PackageItemInfo itemInfo,
3283 @Nullable ApplicationInfo appInfo) {
3284 if (itemInfo.showUserIcon != UserHandle.USER_NULL) {
3285 // Indicates itemInfo is for a different user (e.g. a profile's parent), so use a
3286 // generic user icon (users generally lack permission to view each other's actual icons)
3287 int targetUserId = itemInfo.showUserIcon;
3288 return UserIcons.getDefaultUserIcon(
3289 mContext.getResources(), targetUserId, /* light= */ false);
3290 }
3291 Drawable dr = null;
3292 if (itemInfo.packageName != null) {
3293 dr = getDrawable(itemInfo.packageName, itemInfo.icon, appInfo);
3294 }
3295 if (dr == null && itemInfo != appInfo && appInfo != null) {
3296 dr = loadUnbadgedItemIcon(appInfo, appInfo);
3297 }
3298 if (dr == null) {
3299 dr = itemInfo.loadDefaultIcon(this);
3300 }
3301 return dr;
3302 }
3303
3304 private Drawable getBadgedDrawable(Drawable drawable, Drawable badgeDrawable,
3305 Rect badgeLocation, boolean tryBadgeInPlace) {
3306 final int badgedWidth = drawable.getIntrinsicWidth();
3307 final int badgedHeight = drawable.getIntrinsicHeight();
3308 final boolean canBadgeInPlace = tryBadgeInPlace
3309 && (drawable instanceof BitmapDrawable)
3310 && ((BitmapDrawable) drawable).getBitmap().isMutable();
3311
3312 final Bitmap bitmap;
3313 if (canBadgeInPlace) {
3314 bitmap = ((BitmapDrawable) drawable).getBitmap();
3315 } else {
3316 bitmap = Bitmap.createBitmap(badgedWidth, badgedHeight, Bitmap.Config.ARGB_8888);
3317 }
3318 Canvas canvas = new Canvas(bitmap);
3319
3320 if (!canBadgeInPlace) {
3321 drawable.setBounds(0, 0, badgedWidth, badgedHeight);
3322 drawable.draw(canvas);
3323 }
3324
3325 if (badgeLocation != null) {
3326 if (badgeLocation.left < 0 || badgeLocation.top < 0
3327 || badgeLocation.width() > badgedWidth || badgeLocation.height() > badgedHeight) {
3328 throw new IllegalArgumentException("Badge location " + badgeLocation
3329 + " not in badged drawable bounds "
3330 + new Rect(0, 0, badgedWidth, badgedHeight));
3331 }
3332 badgeDrawable.setBounds(0, 0, badgeLocation.width(), badgeLocation.height());
3333
3334 canvas.save();
3335 canvas.translate(badgeLocation.left, badgeLocation.top);
3336 badgeDrawable.draw(canvas);
3337 canvas.restore();
3338 } else {
3339 badgeDrawable.setBounds(0, 0, badgedWidth, badgedHeight);
3340 badgeDrawable.draw(canvas);
3341 }
3342
3343 if (!canBadgeInPlace) {
3344 BitmapDrawable mergedDrawable = new BitmapDrawable(mContext.getResources(), bitmap);
3345
3346 if (drawable instanceof BitmapDrawable) {
3347 BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
3348 mergedDrawable.setTargetDensity(bitmapDrawable.getBitmap().getDensity());
3349 }
3350
3351 return mergedDrawable;
3352 }
3353
3354 return drawable;
3355 }
3356
3357 private boolean hasUserBadge(int userId) {
3358 return getUserManager().hasBadge(userId);
3359 }
3360
3361 /**
3362 * @hide
3363 */
3364 @Override
3365 public int getInstallReason(String packageName, UserHandle user) {
3366 try {
3367 return mPM.getInstallReason(packageName, user.getIdentifier());
3368 } catch (RemoteException e) {
3369 throw e.rethrowFromSystemServer();
3370 }
3371 }
3372
3373 /** {@hide} */
3374 private static class MoveCallbackDelegate extends IPackageMoveObserver.Stub implements
3375 Handler.Callback {
3376 private static final int MSG_CREATED = 1;
3377 private static final int MSG_STATUS_CHANGED = 2;
3378
3379 final MoveCallback mCallback;
3380 final Handler mHandler;
3381
3382 public MoveCallbackDelegate(MoveCallback callback, Looper looper) {
3383 mCallback = callback;
3384 mHandler = new Handler(looper, this);
3385 }
3386
3387 @Override
3388 public boolean handleMessage(Message msg) {
3389 switch (msg.what) {
3390 case MSG_CREATED: {
3391 final SomeArgs args = (SomeArgs) msg.obj;
3392 mCallback.onCreated(args.argi1, (Bundle) args.arg2);
3393 args.recycle();
3394 return true;
3395 }
3396 case MSG_STATUS_CHANGED: {
3397 final SomeArgs args = (SomeArgs) msg.obj;
3398 mCallback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
3399 args.recycle();
3400 return true;
3401 }
3402 }
3403 return false;
3404 }
3405
3406 @Override
3407 public void onCreated(int moveId, Bundle extras) {
3408 final SomeArgs args = SomeArgs.obtain();
3409 args.argi1 = moveId;
3410 args.arg2 = extras;
3411 mHandler.obtainMessage(MSG_CREATED, args).sendToTarget();
3412 }
3413
3414 @Override
3415 public void onStatusChanged(int moveId, int status, long estMillis) {
3416 final SomeArgs args = SomeArgs.obtain();
3417 args.argi1 = moveId;
3418 args.argi2 = status;
3419 args.arg3 = estMillis;
3420 mHandler.obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
3421 }
3422 }
3423
3424 private final ContextImpl mContext;
3425 @UnsupportedAppUsage
3426 private final IPackageManager mPM;
3427
3428 /** Assume locked until we hear otherwise */
3429 private volatile boolean mUserUnlocked = false;
3430
3431 private static final Object sSync = new Object();
3432 private static ArrayMap<ResourceName, WeakReference<Drawable.ConstantState>> sIconCache
3433 = new ArrayMap<ResourceName, WeakReference<Drawable.ConstantState>>();
3434 private static ArrayMap<ResourceName, WeakReference<CharSequence>> sStringCache
3435 = new ArrayMap<ResourceName, WeakReference<CharSequence>>();
3436
3437 @Override
3438 public boolean canRequestPackageInstalls() {
3439 try {
3440 return mPM.canRequestPackageInstalls(mContext.getPackageName(), getUserId());
3441 } catch (RemoteException e) {
3442 throw e.rethrowAsRuntimeException();
3443 }
3444 }
3445
3446 @Override
3447 public ComponentName getInstantAppResolverSettingsComponent() {
3448 try {
3449 return mPM.getInstantAppResolverSettingsComponent();
3450 } catch (RemoteException e) {
3451 throw e.rethrowAsRuntimeException();
3452 }
3453 }
3454
3455 @Override
3456 public ComponentName getInstantAppInstallerComponent() {
3457 try {
3458 return mPM.getInstantAppInstallerComponent();
3459 } catch (RemoteException e) {
3460 throw e.rethrowAsRuntimeException();
3461 }
3462 }
3463
3464 @Override
3465 public String getInstantAppAndroidId(String packageName, UserHandle user) {
3466 try {
3467 return mPM.getInstantAppAndroidId(packageName, user.getIdentifier());
3468 } catch (RemoteException e) {
3469 throw e.rethrowAsRuntimeException();
3470 }
3471 }
3472
3473 private static class DexModuleRegisterResult {
3474 final String dexModulePath;
3475 final boolean success;
3476 final String message;
3477
3478 private DexModuleRegisterResult(String dexModulePath, boolean success, String message) {
3479 this.dexModulePath = dexModulePath;
3480 this.success = success;
3481 this.message = message;
3482 }
3483 }
3484
3485 private static class DexModuleRegisterCallbackDelegate
3486 extends android.content.pm.IDexModuleRegisterCallback.Stub
3487 implements Handler.Callback {
3488 private static final int MSG_DEX_MODULE_REGISTERED = 1;
3489 private final DexModuleRegisterCallback callback;
3490 private final Handler mHandler;
3491
3492 DexModuleRegisterCallbackDelegate(@NonNull DexModuleRegisterCallback callback) {
3493 this.callback = callback;
3494 mHandler = new Handler(Looper.getMainLooper(), this);
3495 }
3496
3497 @Override
3498 public void onDexModuleRegistered(@NonNull String dexModulePath, boolean success,
3499 @Nullable String message)throws RemoteException {
3500 mHandler.obtainMessage(MSG_DEX_MODULE_REGISTERED,
3501 new DexModuleRegisterResult(dexModulePath, success, message)).sendToTarget();
3502 }
3503
3504 @Override
3505 public boolean handleMessage(Message msg) {
3506 if (msg.what != MSG_DEX_MODULE_REGISTERED) {
3507 return false;
3508 }
3509 DexModuleRegisterResult result = (DexModuleRegisterResult)msg.obj;
3510 callback.onDexModuleRegistered(result.dexModulePath, result.success, result.message);
3511 return true;
3512 }
3513 }
3514
3515 @Override
3516 public void registerDexModule(@NonNull String dexModule,
3517 @Nullable DexModuleRegisterCallback callback) {
3518 // Create the callback delegate to be passed to package manager service.
3519 DexModuleRegisterCallbackDelegate callbackDelegate = null;
3520 if (callback != null) {
3521 callbackDelegate = new DexModuleRegisterCallbackDelegate(callback);
3522 }
3523
3524 // Check if this is a shared module by looking if the others can read it.
3525 boolean isSharedModule = false;
3526 try {
3527 StructStat stat = Os.stat(dexModule);
3528 if ((OsConstants.S_IROTH & stat.st_mode) != 0) {
3529 isSharedModule = true;
3530 }
3531 } catch (ErrnoException e) {
3532 if (callbackDelegate != null) {
3533 callback.onDexModuleRegistered(dexModule, false,
3534 "Could not get stat the module file: " + e.getMessage());
3535 }
3536 return;
3537 }
3538
3539 // Invoke the package manager service.
3540 try {
3541 mPM.registerDexModule(mContext.getPackageName(), dexModule,
3542 isSharedModule, callbackDelegate);
3543 } catch (RemoteException e) {
3544 throw e.rethrowAsRuntimeException();
3545 }
3546 }
3547
3548 @Override
3549 public CharSequence getHarmfulAppWarning(String packageName) {
3550 try {
3551 return mPM.getHarmfulAppWarning(packageName, getUserId());
3552 } catch (RemoteException e) {
3553 throw e.rethrowAsRuntimeException();
3554 }
3555 }
3556
3557 @Override
3558 public void setHarmfulAppWarning(String packageName, CharSequence warning) {
3559 try {
3560 mPM.setHarmfulAppWarning(packageName, warning, getUserId());
3561 } catch (RemoteException e) {
3562 throw e.rethrowAsRuntimeException();
3563 }
3564 }
3565
3566 @Override
3567 public ArtManager getArtManager() {
3568 if (mArtManager == null) {
3569 try {
3570 mArtManager = new ArtManager(mContext, mPM.getArtManager());
3571 } catch (RemoteException e) {
3572 throw e.rethrowFromSystemServer();
3573 }
3574 }
3575 return mArtManager;
3576 }
3577
3578 @Override
3579 public String getDefaultTextClassifierPackageName() {
3580 try {
3581 return mPM.getDefaultTextClassifierPackageName();
3582 } catch (RemoteException e) {
3583 throw e.rethrowAsRuntimeException();
3584 }
3585 }
3586
3587 @Override
3588 public String getSystemTextClassifierPackageName() {
3589 try {
3590 return mPM.getSystemTextClassifierPackageName();
3591 } catch (RemoteException e) {
3592 throw e.rethrowAsRuntimeException();
3593 }
3594 }
3595
3596 @Override
3597 public String getAttentionServicePackageName() {
3598 try {
3599 return mPM.getAttentionServicePackageName();
3600 } catch (RemoteException e) {
3601 throw e.rethrowAsRuntimeException();
3602 }
3603 }
3604
3605 @Override
3606 public String getRotationResolverPackageName() {
3607 try {
3608 return mPM.getRotationResolverPackageName();
3609 } catch (RemoteException e) {
3610 throw e.rethrowAsRuntimeException();
3611 }
3612 }
3613
3614 @Override
3615 public String getWellbeingPackageName() {
3616 try {
3617 return mPM.getWellbeingPackageName();
3618 } catch (RemoteException e) {
3619 throw e.rethrowAsRuntimeException();
3620 }
3621 }
3622
3623 @Override
3624 public String getAppPredictionServicePackageName() {
3625 try {
3626 return mPM.getAppPredictionServicePackageName();
3627 } catch (RemoteException e) {
3628 throw e.rethrowAsRuntimeException();
3629 }
3630 }
3631
3632 @Override
3633 public String getSystemCaptionsServicePackageName() {
3634 try {
3635 return mPM.getSystemCaptionsServicePackageName();
3636 } catch (RemoteException e) {
3637 throw e.rethrowAsRuntimeException();
3638 }
3639 }
3640
3641 @Override
3642 public String getSetupWizardPackageName() {
3643 try {
3644 return mPM.getSetupWizardPackageName();
3645 } catch (RemoteException e) {
3646 throw e.rethrowAsRuntimeException();
3647 }
3648 }
3649
3650 @Override
3651 public String getIncidentReportApproverPackageName() {
3652 try {
3653 return mPM.getIncidentReportApproverPackageName();
3654 } catch (RemoteException e) {
3655 throw e.rethrowAsRuntimeException();
3656 }
3657 }
3658
3659 @Override
3660 public String getContentCaptureServicePackageName() {
3661 try {
3662 return mPM.getContentCaptureServicePackageName();
3663 } catch (RemoteException e) {
3664 throw e.rethrowAsRuntimeException();
3665 }
3666 }
3667
3668 @Override
3669 public boolean isPackageStateProtected(String packageName, int userId) {
3670 try {
3671 return mPM.isPackageStateProtected(packageName, userId);
3672 } catch (RemoteException e) {
3673 throw e.rethrowAsRuntimeException();
3674 }
3675 }
3676
3677 public void sendDeviceCustomizationReadyBroadcast() {
3678 try {
3679 mPM.sendDeviceCustomizationReadyBroadcast();
3680 } catch (RemoteException e) {
3681 throw e.rethrowAsRuntimeException();
3682 }
3683 }
3684
3685 @Override
3686 public boolean isAutoRevokeWhitelisted() {
3687 try {
3688 return mPM.isAutoRevokeWhitelisted(mContext.getPackageName());
3689 } catch (RemoteException e) {
3690 throw e.rethrowAsRuntimeException();
3691 }
3692 }
3693
3694 @Override
3695 public void setMimeGroup(String mimeGroup, Set<String> mimeTypes) {
3696 try {
3697 mPM.setMimeGroup(mContext.getPackageName(), mimeGroup, new ArrayList<>(mimeTypes));
3698 } catch (RemoteException e) {
3699 throw e.rethrowAsRuntimeException();
3700 }
3701 }
3702
3703 @NonNull
3704 @Override
3705 public Set<String> getMimeGroup(String group) {
3706 try {
3707 List<String> mimeGroup = mPM.getMimeGroup(mContext.getPackageName(), group);
3708 return new ArraySet<>(mimeGroup);
3709 } catch (RemoteException e) {
3710 throw e.rethrowAsRuntimeException();
3711 }
3712 }
3713
3714 @Override
3715 public Property getProperty(String propertyName, String packageName)
3716 throws NameNotFoundException {
3717 Objects.requireNonNull(packageName);
3718 Objects.requireNonNull(propertyName);
3719 try {
3720 final Property property = mPM.getProperty(propertyName, packageName, null);
3721 if (property == null) {
3722 throw new NameNotFoundException();
3723 }
3724 return property;
3725 } catch (RemoteException e) {
3726 throw e.rethrowAsRuntimeException();
3727 }
3728 }
3729
3730 @Override
3731 public Property getProperty(String propertyName, ComponentName component)
3732 throws NameNotFoundException {
3733 Objects.requireNonNull(component);
3734 Objects.requireNonNull(propertyName);
3735 try {
3736 final Property property = mPM.getProperty(
3737 propertyName, component.getPackageName(), component.getClassName());
3738 if (property == null) {
3739 throw new NameNotFoundException();
3740 }
3741 return property;
3742 } catch (RemoteException e) {
3743 throw e.rethrowAsRuntimeException();
3744 }
3745 }
3746
3747 @Override
3748 public List<Property> queryApplicationProperty(String propertyName) {
3749 Objects.requireNonNull(propertyName);
3750 try {
3751 final ParceledListSlice<Property> parceledList =
3752 mPM.queryProperty(propertyName, TYPE_APPLICATION);
3753 if (parceledList == null) {
3754 return Collections.emptyList();
3755 }
3756 return parceledList.getList();
3757 } catch (RemoteException e) {
3758 throw e.rethrowAsRuntimeException();
3759 }
3760 }
3761
3762 @Override
3763 public List<Property> queryActivityProperty(String propertyName) {
3764 Objects.requireNonNull(propertyName);
3765 try {
3766 final ParceledListSlice<Property> parceledList =
3767 mPM.queryProperty(propertyName, TYPE_ACTIVITY);
3768 if (parceledList == null) {
3769 return Collections.emptyList();
3770 }
3771 return parceledList.getList();
3772 } catch (RemoteException e) {
3773 throw e.rethrowAsRuntimeException();
3774 }
3775 }
3776
3777 @Override
3778 public List<Property> queryProviderProperty(String propertyName) {
3779 Objects.requireNonNull(propertyName);
3780 try {
3781 final ParceledListSlice<Property> parceledList =
3782 mPM.queryProperty(propertyName, TYPE_PROVIDER);
3783 if (parceledList == null) {
3784 return Collections.emptyList();
3785 }
3786 return parceledList.getList();
3787 } catch (RemoteException e) {
3788 throw e.rethrowAsRuntimeException();
3789 }
3790 }
3791
3792 @Override
3793 public List<Property> queryReceiverProperty(String propertyName) {
3794 Objects.requireNonNull(propertyName);
3795 try {
3796 final ParceledListSlice<Property> parceledList =
3797 mPM.queryProperty(propertyName, TYPE_RECEIVER);
3798 if (parceledList == null) {
3799 return Collections.emptyList();
3800 }
3801 return parceledList.getList();
3802 } catch (RemoteException e) {
3803 throw e.rethrowAsRuntimeException();
3804 }
3805 }
3806
3807 @Override
3808 public List<Property> queryServiceProperty(String propertyName) {
3809 Objects.requireNonNull(propertyName);
3810 try {
3811 final ParceledListSlice<Property> parceledList =
3812 mPM.queryProperty(propertyName, TYPE_SERVICE);
3813 if (parceledList == null) {
3814 return Collections.emptyList();
3815 }
3816 return parceledList.getList();
3817 } catch (RemoteException e) {
3818 throw e.rethrowAsRuntimeException();
3819 }
3820 }
3821
3822 @Override
3823 public boolean canPackageQuery(@NonNull String sourcePackageName,
3824 @NonNull String targetPackageName) throws NameNotFoundException {
3825 Objects.requireNonNull(sourcePackageName);
3826 Objects.requireNonNull(targetPackageName);
3827 try {
3828 return mPM.canPackageQuery(sourcePackageName, targetPackageName, getUserId());
3829 } catch (ParcelableException e) {
3830 e.maybeRethrow(PackageManager.NameNotFoundException.class);
3831 throw new RuntimeException(e);
3832 } catch (RemoteException re) {
3833 throw re.rethrowAsRuntimeException();
3834 }
3835 }
3836
3837 @Override
3838 public void makeUidVisible(int recipientUid, int visibleUid) {
3839 try {
3840 mPM.makeUidVisible(recipientUid, visibleUid);
3841 } catch (RemoteException e) {
3842 throw e.rethrowAsRuntimeException();
3843 }
3844 }
3845 }