• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.content.pm;
18 
19 import android.annotation.AppIdInt;
20 import android.annotation.IntDef;
21 import android.annotation.LongDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.SystemApi;
25 import android.annotation.UserIdInt;
26 import android.annotation.WorkerThread;
27 import android.content.ComponentName;
28 import android.content.ContentResolver;
29 import android.content.Intent;
30 import android.content.IntentSender;
31 import android.content.pm.PackageManager.SignatureResult;
32 import android.content.pm.SigningDetails.CertCapabilities;
33 import android.content.pm.overlay.OverlayPaths;
34 import android.os.Bundle;
35 import android.os.Handler;
36 import android.os.HandlerExecutor;
37 import android.os.IBinder;
38 import android.os.Looper;
39 import android.os.PersistableBundle;
40 import android.os.Process;
41 import android.os.storage.StorageManager;
42 import android.util.ArrayMap;
43 import android.util.ArraySet;
44 import android.util.SparseArray;
45 
46 import com.android.internal.pm.pkg.component.ParsedMainComponent;
47 import com.android.internal.util.function.pooled.PooledLambda;
48 import com.android.server.pm.KnownPackages;
49 import com.android.server.pm.PackageArchiver;
50 import com.android.server.pm.PackageList;
51 import com.android.server.pm.PackageSetting;
52 import com.android.server.pm.dex.DynamicCodeLogger;
53 import com.android.server.pm.permission.LegacyPermissionSettings;
54 import com.android.server.pm.pkg.AndroidPackage;
55 import com.android.server.pm.pkg.PackageStateInternal;
56 import com.android.server.pm.pkg.SharedUserApi;
57 import com.android.server.pm.pkg.mutate.PackageStateMutator;
58 import com.android.server.pm.snapshot.PackageDataSnapshot;
59 
60 import java.io.IOException;
61 import java.lang.annotation.Retention;
62 import java.lang.annotation.RetentionPolicy;
63 import java.util.List;
64 import java.util.Set;
65 import java.util.concurrent.Executor;
66 import java.util.function.Consumer;
67 
68 /**
69  * Package manager local system service interface.
70  *
71  * @hide Only for use within the system server.
72  */
73 public abstract class PackageManagerInternal {
74     @LongDef(flag = true, prefix = "RESOLVE_", value = {
75             RESOLVE_NON_BROWSER_ONLY,
76             RESOLVE_NON_RESOLVER_ONLY
77     })
78     @Retention(RetentionPolicy.SOURCE)
79     public @interface PrivateResolveFlags {}
80 
81     /**
82      * Internal {@link #resolveIntent(Intent, String, int, int, int, boolean, int)} flag:
83      * only match components that contain a generic web intent filter.
84      */
85     public static final int RESOLVE_NON_BROWSER_ONLY = 0x00000001;
86 
87     /**
88      * Internal {@link #resolveIntent(Intent, String, int, int, int, boolean, int)} flag: do not
89      * match to the resolver.
90      */
91     public static final int RESOLVE_NON_RESOLVER_ONLY = 0x00000002;
92 
93     @Deprecated
94     @IntDef(value = {
95             INTEGRITY_VERIFICATION_ALLOW,
96             INTEGRITY_VERIFICATION_REJECT,
97     })
98     @Retention(RetentionPolicy.SOURCE)
99     public @interface IntegrityVerificationResult {}
100 
101     @Deprecated
102     public static final int INTEGRITY_VERIFICATION_ALLOW = 1;
103 
104     @Deprecated
105     public static final int INTEGRITY_VERIFICATION_REJECT = 0;
106 
107     /**
108      * Observer called whenever the list of packages changes.
109      *
110      * @deprecated please use {@link com.android.internal.content.PackageMonitor} instead.
111      * PackageMonitor covers more installation and uninstallation corner cases than
112      * PackageListObserver.
113      */
114     @Deprecated
115     public interface PackageListObserver {
116         /** A package was added to the system. */
onPackageAdded(@onNull String packageName, int uid)117         default void onPackageAdded(@NonNull String packageName, int uid) {}
118         /** A package was changed - either installed for a specific user or updated. */
onPackageChanged(@onNull String packageName, int uid)119         default void onPackageChanged(@NonNull String packageName, int uid) {}
120         /** A package was removed from the system. */
onPackageRemoved(@onNull String packageName, int uid)121         default void onPackageRemoved(@NonNull String packageName, int uid) {}
122     }
123 
124     /**
125      * Called when the package for the default SMS handler changed
126      *
127      * @param packageName the new sms package
128      * @param userId user for which the change was made
129      */
onDefaultSmsAppChanged(String packageName, int userId)130     public void onDefaultSmsAppChanged(String packageName, int userId) {}
131 
132     /**
133      * Called when the package for the default sim call manager changed
134      *
135      * @param packageName the new sms package
136      * @param userId user for which the change was made
137      */
onDefaultSimCallManagerAppChanged(String packageName, int userId)138     public void onDefaultSimCallManagerAppChanged(String packageName, int userId) {}
139 
140     /**
141      * Sets a list of apps to keep in PM's internal data structures and as APKs even if no user has
142      * currently installed it. The apps are not preloaded.
143      * @param packageList List of package names to keep cached.
144      */
setKeepUninstalledPackages(List<String> packageList)145     public abstract void setKeepUninstalledPackages(List<String> packageList);
146 
147     /**
148      * Gets whether some of the permissions used by this package require a user
149      * review before any of the app components can run.
150      * @param packageName The package name for which to check.
151      * @param userId The user under which to check.
152      * @return True a permissions review is required.
153      */
isPermissionsReviewRequired(String packageName, int userId)154     public abstract boolean isPermissionsReviewRequired(String packageName, int userId);
155 
156 
157     /**
158      * Variant of {@link #isSameApp(String, long, int, int)} with no flags.
159      * @see #isSameApp(String, long, int, int)
160      */
isSameApp(String packageName, int callingUid, int userId)161     public abstract boolean isSameApp(String packageName, int callingUid, int userId);
162 
163     /**
164      * Gets whether a given package name belongs to the calling uid. If the calling uid is an
165      * {@link Process#isSdkSandboxUid(int) sdk sandbox uid}, checks whether the package name is
166      * equal to {@link PackageManager#getSdkSandboxPackageName()}.
167      *
168      * @param packageName The package name to check.
169      * @param flags The PackageInfoFlagsBits flags to use during uid lookup.
170      * @param callingUid The calling uid.
171      * @param userId The user under which to check.
172      * @return True if the package name belongs to the calling uid.
173      */
isSameApp(String packageName, @PackageManager.PackageInfoFlagsBits long flags, int callingUid, int userId)174     public abstract boolean isSameApp(String packageName,
175             @PackageManager.PackageInfoFlagsBits long flags, int callingUid, int userId);
176 
177     /**
178      * Retrieve all of the information we know about a particular package/application.
179      * @param filterCallingUid The results will be filtered in the context of this UID instead
180      * of the calling UID.
181      * @see PackageManager#getPackageInfo(String, int)
182      */
getPackageInfo(String packageName, @PackageManager.PackageInfoFlagsBits long flags, int filterCallingUid, int userId)183     public abstract PackageInfo getPackageInfo(String packageName,
184             @PackageManager.PackageInfoFlagsBits long flags, int filterCallingUid, int userId);
185 
186     /**
187      * Retrieve CE data directory inode number of an application.
188      * Return 0 if there's error.
189      */
getCeDataInode(String packageName, int userId)190     public abstract long getCeDataInode(String packageName, int userId);
191 
192     /**
193      * Return a List of all application packages that are installed on the
194      * device, for a specific user. If flag GET_UNINSTALLED_PACKAGES has been
195      * set, a list of all applications including those deleted with
196      * {@code DELETE_KEEP_DATA} (partially installed apps with data directory)
197      * will be returned.
198      *
199      * @param flags Additional option flags to modify the data returned.
200      * @param userId The user for whom the installed applications are to be
201      *            listed
202      * @param callingUid The uid of the original caller app
203      * @return A List of ApplicationInfo objects, one for each installed
204      *         application. In the unlikely case there are no installed
205      *         packages, an empty list is returned. If flag
206      *         {@code MATCH_UNINSTALLED_PACKAGES} is set, the application
207      *         information is retrieved from the list of uninstalled
208      *         applications (which includes installed applications as well as
209      *         applications with data directory i.e. applications which had been
210      *         deleted with {@code DELETE_KEEP_DATA} flag set).
211      */
getInstalledApplications( @ackageManager.ApplicationInfoFlagsBits long flags, @UserIdInt int userId, int callingUid)212     public abstract List<ApplicationInfo> getInstalledApplications(
213             @PackageManager.ApplicationInfoFlagsBits long flags, @UserIdInt int userId,
214             int callingUid);
215 
216     /**
217      * Like {@link #getInstalledApplications}, but allows the fetching of apps
218      * cross user.
219      */
getInstalledApplicationsCrossUser( @ackageManager.ApplicationInfoFlagsBits long flags, @UserIdInt int userId, int callingUid)220     public abstract List<ApplicationInfo> getInstalledApplicationsCrossUser(
221             @PackageManager.ApplicationInfoFlagsBits long flags, @UserIdInt int userId,
222             int callingUid);
223 
224     /**
225      * Retrieve launcher extras for a suspended package provided to the system in
226      * {@link PackageManager#setPackagesSuspended(String[], boolean, PersistableBundle,
227      * PersistableBundle, String)}.
228      *
229      * @param packageName The package for which to return launcher extras.
230      * @param userId The user for which to check.
231      * @return The launcher extras.
232      *
233      * @see PackageManager#setPackagesSuspended(String[], boolean, PersistableBundle,
234      * PersistableBundle, String)
235      * @see PackageManager#isPackageSuspended()
236      */
getSuspendedPackageLauncherExtras(String packageName, int userId)237     public abstract Bundle getSuspendedPackageLauncherExtras(String packageName,
238             int userId);
239 
240     /**
241      * Internal api to query the suspended state of a package.
242      * @param packageName The package to check.
243      * @param userId The user id to check for.
244      * @return {@code true} if the package is suspended, {@code false} otherwise.
245      * @see PackageManager#isPackageSuspended(String)
246      */
isPackageSuspended(String packageName, int userId)247     public abstract boolean isPackageSuspended(String packageName, int userId);
248 
249     /**
250      * Removes all package suspensions imposed by any non-system packages.
251      */
removeAllNonSystemPackageSuspensions(int userId)252     public abstract void removeAllNonSystemPackageSuspensions(int userId);
253 
254     /**
255      * Removes all suspensions imposed on the given package by non-system packages.
256      */
removeNonSystemPackageSuspensions(String packageName, int userId)257     public abstract void removeNonSystemPackageSuspensions(String packageName, int userId);
258 
259     /**
260      * Removes all {@link PackageManager.DistractionRestriction restrictions} set on the given
261      * package
262      */
removeDistractingPackageRestrictions(String packageName, int userId)263     public abstract void removeDistractingPackageRestrictions(String packageName, int userId);
264 
265     /**
266      * Removes all {@link PackageManager.DistractionRestriction restrictions} set on all the
267      * packages.
268      */
removeAllDistractingPackageRestrictions(int userId)269     public abstract void removeAllDistractingPackageRestrictions(int userId);
270 
271     /**
272      * Flushes package restrictions for the given user immediately to disk.
273      */
274     @WorkerThread
flushPackageRestrictions(int userId)275     public abstract void flushPackageRestrictions(int userId);
276 
277     /**
278      * Get the name of the package that suspended the given package. Packages can be suspended by
279      * device administrators or apps holding {@link android.Manifest.permission#MANAGE_USERS} or
280      * {@link android.Manifest.permission#SUSPEND_APPS}.
281      *
282      * @param suspendedPackage The package that has been suspended.
283      * @param userId The user for which to check.
284      * @return User id and package name of the package that suspended the given package. Returns
285      * {@code null} if the given package is not currently suspended and the platform package name
286      * - i.e. {@code "android"} - if the package was suspended by a device admin.
287      */
getSuspendingPackage(String suspendedPackage, int userId)288     public abstract UserPackage getSuspendingPackage(String suspendedPackage, int userId);
289 
290     /**
291      * Suspend or unsuspend packages upon admin request.
292      *
293      * @param userId The target user.
294      * @param packageNames The names of the packages to set the suspended status.
295      * @param suspended Whether the packages should be suspended or unsuspended.
296      * @return an array of package names for which the suspended status could not be set as
297      *   requested in this method.
298      */
setPackagesSuspendedByAdmin( @serIdInt int userId, @NonNull String[] packageNames, boolean suspended)299     public abstract String[] setPackagesSuspendedByAdmin(
300             @UserIdInt int userId, @NonNull String[] packageNames, boolean suspended);
301 
302     /**
303      * Get the information describing the dialog to be shown to the user when they try to launch a
304      * suspended application.
305      *
306      * @param suspendedPackage The package that has been suspended.
307      * @param suspendingPackage The package responsible for suspension.
308      * @param userId The user for which to check.
309      * @return A {@link SuspendDialogInfo} object describing the dialog to be shown.
310      */
311     @Nullable
getSuspendedDialogInfo(String suspendedPackage, UserPackage suspendingPackage, int userId)312     public abstract SuspendDialogInfo getSuspendedDialogInfo(String suspendedPackage,
313             UserPackage suspendingPackage, int userId);
314 
315     /**
316      * Gets any distraction flags set via
317      * {@link PackageManager#setDistractingPackageRestrictions(String[], int)}
318      *
319      * @param packageName
320      * @param userId
321      * @return A bitwise OR of any of the {@link PackageManager.DistractionRestriction}
322      */
getDistractingPackageRestrictions( String packageName, int userId)323     public abstract @PackageManager.DistractionRestriction int getDistractingPackageRestrictions(
324             String packageName, int userId);
325 
326     /**
327      * Do a straight uid lookup for the given package/application in the given user.
328      * @see PackageManager#getPackageUidAsUser(String, int, int)
329      * @return The app's uid, or < 0 if the package was not found in that user
330      */
getPackageUid(String packageName, @PackageManager.PackageInfoFlagsBits long flags, int userId)331     public abstract int getPackageUid(String packageName,
332             @PackageManager.PackageInfoFlagsBits long flags, int userId);
333 
334     /**
335      * Retrieve all of the information we know about a particular package/application.
336      * @param filterCallingUid The results will be filtered in the context of this UID instead
337      * of the calling UID.
338      * @see PackageManager#getApplicationInfo(String, int)
339      */
getApplicationInfo(String packageName, @PackageManager.ApplicationInfoFlagsBits long flags, int filterCallingUid, int userId)340     public abstract ApplicationInfo getApplicationInfo(String packageName,
341             @PackageManager.ApplicationInfoFlagsBits long flags, int filterCallingUid, int userId);
342 
343     /**
344      * Retrieve all of the information we know about a particular activity class.
345      * @param filterCallingUid The results will be filtered in the context of this UID instead
346      * of the calling UID.
347      * @see PackageManager#getActivityInfo(ComponentName, int)
348      */
getActivityInfo(ComponentName component, @PackageManager.ComponentInfoFlagsBits long flags, int filterCallingUid, int userId)349     public abstract ActivityInfo getActivityInfo(ComponentName component,
350             @PackageManager.ComponentInfoFlagsBits long flags, int filterCallingUid, int userId);
351 
352     /**
353      * Retrieve all activities that can be performed for the given intent.
354      * @param resolvedType the resolved type of the intent, which should be resolved via
355      * {@link Intent#resolveTypeIfNeeded(ContentResolver)} before passing to {@link PackageManager}
356      * @param filterCallingUid The results will be filtered in the context of this UID instead
357      * of the calling UID.
358      * @see PackageManager#queryIntentActivities(Intent, int)
359      */
queryIntentActivities( Intent intent, @Nullable String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId)360     public abstract List<ResolveInfo> queryIntentActivities(
361             Intent intent, @Nullable String resolvedType,
362             @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId);
363 
364     /**
365      * Retrieve all receivers that can handle a broadcast of the given intent.
366      *
367      * @param filterCallingUid The results will be filtered in the context of this UID instead
368      *                         of the calling UID.
369      * @param forSend          true if the invocation is intended for sending broadcasts. The value
370      *                         of this parameter affects how packages are filtered.
371      */
queryIntentReceivers( Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int callingPid, int userId, boolean forSend)372     public abstract List<ResolveInfo> queryIntentReceivers(
373             Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags,
374             int filterCallingUid, int callingPid, int userId, boolean forSend);
375 
376     /**
377      * Retrieve all services that can be performed for the given intent.
378      * @see PackageManager#queryIntentServices(Intent, int)
379      */
queryIntentServices( Intent intent, @PackageManager.ResolveInfoFlagsBits long flags, int callingUid, int userId)380     public abstract List<ResolveInfo> queryIntentServices(
381             Intent intent, @PackageManager.ResolveInfoFlagsBits long flags, int callingUid,
382             int userId);
383 
384     /**
385      * Interface to {@link com.android.server.pm.PackageManagerService#getHomeActivitiesAsUser}.
386      */
getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, int userId)387     public abstract ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
388             int userId);
389 
390     /**
391      * @return The default home activity component name.
392      */
getDefaultHomeActivity(int userId)393     public abstract ComponentName getDefaultHomeActivity(int userId);
394 
395     /**
396      * @return The SystemUI service component name.
397      */
getSystemUiServiceComponent()398     public abstract ComponentName getSystemUiServiceComponent();
399 
400     /**
401      * Called by DeviceOwnerManagerService to set the package names of device owner and profile
402      * owners.
403      */
setDeviceAndProfileOwnerPackages( int deviceOwnerUserId, String deviceOwner, SparseArray<String> profileOwners)404     public abstract void setDeviceAndProfileOwnerPackages(
405             int deviceOwnerUserId, String deviceOwner, SparseArray<String> profileOwners);
406 
407     /**
408      * Marks packages as protected for a given user or all users in case of USER_ALL. Setting
409      * {@code packageNames} to {@code null} means unset all existing protected packages for the
410      * given user.
411      *
412      * <p> Note that setting it if set for a specific user, it takes precedence over the packages
413      * set globally using USER_ALL.
414      */
setOwnerProtectedPackages( @serIdInt int userId, @Nullable List<String> packageNames)415     public abstract void setOwnerProtectedPackages(
416             @UserIdInt int userId, @Nullable List<String> packageNames);
417 
418     /**
419      * Returns {@code true} if a given package can't be wiped. Otherwise, returns {@code false}.
420      */
isPackageDataProtected(int userId, String packageName)421     public abstract boolean isPackageDataProtected(int userId, String packageName);
422 
423     /**
424      * Returns {@code true} if a given package's state is protected, e.g. it cannot be force
425      * stopped, suspended, disabled or hidden. Otherwise, returns {@code false}.
426      */
isPackageStateProtected(String packageName, int userId)427     public abstract boolean isPackageStateProtected(String packageName, int userId);
428 
429     /**
430      * Returns {@code true} if a given package is installed as ephemeral. Otherwise, returns
431      * {@code false}.
432      */
isPackageEphemeral(int userId, String packageName)433     public abstract boolean isPackageEphemeral(int userId, String packageName);
434 
435     /**
436      * Gets whether the package was ever launched.
437      * @param packageName The package name.
438      * @param userId The user for which to check.
439      * @return Whether was launched.
440      * @throws IllegalArgumentException if the package is not found
441      */
wasPackageEverLaunched(String packageName, int userId)442     public abstract boolean wasPackageEverLaunched(String packageName, int userId);
443 
444     /**
445      * Retrieve the official name associated with a uid. This name is
446      * guaranteed to never change, though it is possible for the underlying
447      * uid to be changed. That is, if you are storing information about
448      * uids in persistent storage, you should use the string returned
449      * by this function instead of the raw uid.
450      *
451      * @param uid The uid for which you would like to retrieve a name.
452      * @return Returns a unique name for the given uid, or null if the
453      * uid is not currently assigned.
454      */
getNameForUid(int uid)455     public abstract String getNameForUid(int uid);
456 
457     /**
458      * Request to perform the second phase of ephemeral resolution.
459      * @param responseObj The response of the first phase of ephemeral resolution
460      * @param origIntent The original intent that triggered ephemeral resolution
461      * @param resolvedType The resolved type of the intent
462      * @param callingPkg The app requesting the ephemeral application
463      * @param callingFeatureId The feature in the package
464      * @param isRequesterInstantApp Whether or not the app requesting the ephemeral application
465      *                              is an instant app
466      * @param verificationBundle Optional bundle to pass to the installer for additional
467      * verification
468      * @param userId The ID of the user that triggered ephemeral resolution
469      */
requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, Intent origIntent, String resolvedType, String callingPkg, @Nullable String callingFeatureId, boolean isRequesterInstantApp, Bundle verificationBundle, int userId)470     public abstract void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
471             Intent origIntent, String resolvedType, String callingPkg,
472             @Nullable String callingFeatureId, boolean isRequesterInstantApp,
473             Bundle verificationBundle, int userId);
474 
475     /**
476      * Grants implicit access based on an interaction between two apps. This grants access to the
477      * from one application to the other's package metadata.
478      * <p>
479      * When an application explicitly tries to interact with another application [via an
480      * activity, service or provider that is either declared in the caller's
481      * manifest via the {@code <queries>} tag or has been exposed via the target apps manifest using
482      * the {@code visibleToInstantApp} attribute], the target application must be able to see
483      * metadata about the calling app. If the calling application uses an implicit intent [ie
484      * action VIEW, category BROWSABLE], it remains hidden from the launched app.
485      * <p>
486      * If an interaction is not explicit, the {@code direct} argument should be set to false as
487      * visibility should not be granted in some cases. This method handles that logic.
488      * <p>
489      * @param userId the user
490      * @param intent the intent that triggered the grant
491      * @param recipientAppId The app ID of the application that is being given access to {@code
492      *                       visibleUid}
493      * @param visibleUid The uid of the application that is becoming accessible to {@code
494      *                   recipientAppId}
495      * @param direct true if the access is being made due to direct interaction between visibleUid
496      *               and recipientAppId.
497      */
grantImplicitAccess( @serIdInt int userId, Intent intent, @AppIdInt int recipientAppId, int visibleUid, boolean direct)498     public abstract void grantImplicitAccess(
499             @UserIdInt int userId, Intent intent,
500             @AppIdInt int recipientAppId, int visibleUid,
501             boolean direct);
502 
503     /**
504      * Grants implicit access based on an interaction between two apps. This grants access to the
505      * from one application to the other's package metadata.
506      * <p>
507      * When an application explicitly tries to interact with another application [via an
508      * activity, service or provider that is either declared in the caller's
509      * manifest via the {@code <queries>} tag or has been exposed via the target apps manifest using
510      * the {@code visibleToInstantApp} attribute], the target application must be able to see
511      * metadata about the calling app. If the calling application uses an implicit intent [ie
512      * action VIEW, category BROWSABLE], it remains hidden from the launched app.
513      * <p>
514      * If an interaction is not explicit, the {@code direct} argument should be set to false as
515      * visibility should not be granted in some cases. This method handles that logic.
516      * <p>
517      * @param userId the user
518      * @param intent the intent that triggered the grant
519      * @param recipientAppId The app ID of the application that is being given access to {@code
520      *                       visibleUid}
521      * @param visibleUid The uid of the application that is becoming accessible to {@code
522      *                   recipientAppId}
523      * @param direct true if the access is being made due to direct interaction between visibleUid
524      *               and recipientAppId.
525      * @param retainOnUpdate true if the implicit access is retained across package update.
526      */
grantImplicitAccess( @serIdInt int userId, Intent intent, @AppIdInt int recipientAppId, int visibleUid, boolean direct, boolean retainOnUpdate)527     public abstract void grantImplicitAccess(
528             @UserIdInt int userId, Intent intent,
529             @AppIdInt int recipientAppId, int visibleUid,
530             boolean direct, boolean retainOnUpdate);
531 
isInstantAppInstallerComponent(ComponentName component)532     public abstract boolean isInstantAppInstallerComponent(ComponentName component);
533     /**
534      * Prunes instant apps and state associated with uninstalled
535      * instant apps according to the current platform policy.
536      */
pruneInstantApps()537     public abstract void pruneInstantApps();
538 
539     /**
540      * @return The SetupWizard package name.
541      */
getSetupWizardPackageName()542     public abstract String getSetupWizardPackageName();
543 
544     public interface ExternalSourcesPolicy {
545 
546         int USER_TRUSTED = 0;   // User has trusted the package to install apps
547         int USER_BLOCKED = 1;   // User has blocked the package to install apps
548         int USER_DEFAULT = 2;   // Default code to use when user response is unavailable
549 
550         /**
551          * Checks the user preference for whether a package is trusted to request installs through
552          * package installer
553          *
554          * @param packageName The package to check for
555          * @param uid the uid in which the package is running
556          * @return {@link #USER_TRUSTED} if the user has trusted the package, {@link #USER_BLOCKED}
557          * if user has blocked requests from the package, {@link #USER_DEFAULT} if the user response
558          * is not yet available
559          */
getPackageTrustedToInstallApps(String packageName, int uid)560         int getPackageTrustedToInstallApps(String packageName, int uid);
561     }
562 
setExternalSourcesPolicy(ExternalSourcesPolicy policy)563     public abstract void setExternalSourcesPolicy(ExternalSourcesPolicy policy);
564 
565     /**
566      * Return true if the given package is a persistent app process.
567      */
isPackagePersistent(String packageName)568     public abstract boolean isPackagePersistent(String packageName);
569 
570     /**
571      * Get all overlay packages for a user.
572      * @param userId The user for which to get the overlays.
573      * @return A list of overlay packages. An empty list is returned if the
574      *         user has no installed overlay packages.
575      */
getOverlayPackages(int userId)576     public abstract List<PackageInfo> getOverlayPackages(int userId);
577 
578     /**
579      * Get the names of all target packages for a user.
580      * @param userId The user for which to get the package names.
581      * @return A list of target package names. This list includes the "android" package.
582      */
getTargetPackageNames(int userId)583     public abstract List<String> getTargetPackageNames(int userId);
584 
585     /**
586      * Set which overlay to use for a package.
587      * @param userId The user for which to update the overlays.
588      * @param pendingChanges is a map to describe all overlay targets and their related overlay
589      *                      paths. Its key is the overlay target package and its value is the
590      *                      complete list of overlay paths that should be enabled for
591      *                      the target. Previously enabled overlays not specified in the list
592      *                      will be disabled. Pass in null or empty paths to disable all overlays.
593      *                      The order of the items is significant if several overlays modify the
594      *                      same resource. To pass the concrete ArrayMap type is to reduce the
595      *                      overheads of system server.
596      * @param outUpdatedPackageNames An output list that contains the package names of packages
597      *                               affected by the update of enabled overlays.
598      * @param outInvalidPackageNames An output list that contains the package names of packages
599      *                               are not valid.
600      */
setEnabledOverlayPackages(int userId, @NonNull ArrayMap<String, OverlayPaths> pendingChanges, @NonNull Set<String> outUpdatedPackageNames, @NonNull Set<String> outInvalidPackageNames)601     public abstract void setEnabledOverlayPackages(int userId,
602             @NonNull ArrayMap<String, OverlayPaths> pendingChanges,
603             @NonNull Set<String> outUpdatedPackageNames,
604             @NonNull Set<String> outInvalidPackageNames);
605 
606     /**
607      * Resolves an exported activity intent, allowing instant apps to be resolved.
608      */
resolveIntent(Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, @PrivateResolveFlags long privateResolveFlags, int userId, boolean resolveForStart, int filterCallingUid, int callingPid)609     public abstract ResolveInfo resolveIntent(Intent intent, String resolvedType,
610             @PackageManager.ResolveInfoFlagsBits long flags,
611             @PrivateResolveFlags long privateResolveFlags, int userId, boolean resolveForStart,
612             int filterCallingUid, int callingPid);
613 
614     /**
615     * Resolves a service intent, allowing instant apps to be resolved.
616     */
resolveService(Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId, int callingUid)617     public abstract ResolveInfo resolveService(Intent intent, String resolvedType,
618             @PackageManager.ResolveInfoFlagsBits long flags, int userId, int callingUid);
619 
620 
621     /**
622      * Resolves a service intent for start.
623      */
resolveService( Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId, int callingUid, int callingPid)624     public abstract ResolveInfo resolveService(
625             Intent intent, String resolvedType,
626             @PackageManager.ResolveInfoFlagsBits long flags, int userId,
627             int callingUid, int callingPid);
628 
629     /**
630     * Resolves a content provider intent.
631     */
resolveContentProvider(String name, @PackageManager.ComponentInfoFlagsBits long flags, int userId, int callingUid)632     public abstract ProviderInfo resolveContentProvider(String name,
633             @PackageManager.ComponentInfoFlagsBits long flags, int userId, int callingUid);
634 
635     /**
636      * Track the creator of a new isolated uid.
637      * @param isolatedUid The newly created isolated uid.
638      * @param ownerUid The uid of the app that created the isolated process.
639      */
addIsolatedUid(int isolatedUid, int ownerUid)640     public abstract void addIsolatedUid(int isolatedUid, int ownerUid);
641 
642     /**
643      * Track removal of an isolated uid.
644      * @param isolatedUid isolated uid that is no longer being used.
645      */
removeIsolatedUid(int isolatedUid)646     public abstract void removeIsolatedUid(int isolatedUid);
647 
648     /**
649      * Return the taget SDK version for the app with the given UID.
650      */
getUidTargetSdkVersion(int uid)651     public abstract int getUidTargetSdkVersion(int uid);
652 
653     /**
654      * Return the taget SDK version for the app with the given package name.
655      */
getPackageTargetSdkVersion(String packageName)656     public abstract int getPackageTargetSdkVersion(String packageName);
657 
658     /** Whether the binder caller can access instant apps. */
canAccessInstantApps(int callingUid, int userId)659     public abstract boolean canAccessInstantApps(int callingUid, int userId);
660 
661     /** Whether the binder caller can access the given component. */
canAccessComponent(int callingUid, ComponentName component, int userId)662     public abstract boolean canAccessComponent(int callingUid, ComponentName component, int userId);
663 
664     /**
665      * Returns {@code true} if a given package has instant application meta-data.
666      * Otherwise, returns {@code false}. Meta-data is state (eg. cookie, app icon, etc)
667      * associated with an instant app. It may be kept after the instant app has been uninstalled.
668      */
hasInstantApplicationMetadata(String packageName, int userId)669     public abstract boolean hasInstantApplicationMetadata(String packageName, int userId);
670 
671     /**
672      * Updates a package last used time.
673      */
notifyPackageUse(String packageName, int reason)674     public abstract void notifyPackageUse(String packageName, int reason);
675 
676     /**
677      * Notify the package is force stopped.
678      */
onPackageProcessKilledForUninstall(String packageName)679     public abstract void onPackageProcessKilledForUninstall(String packageName);
680 
681     /**
682      * Returns a package object for the given package name.
683      */
getPackage(@onNull String packageName)684     public abstract @Nullable AndroidPackage getPackage(@NonNull String packageName);
685 
686     /**
687      * Returns the {@link SystemApi} variant of a package for use with mainline.
688      */
689     @Nullable
getAndroidPackage(@onNull String packageName)690     public abstract AndroidPackage getAndroidPackage(@NonNull String packageName);
691 
692     @Nullable
getPackageStateInternal(@onNull String packageName)693     public abstract PackageStateInternal getPackageStateInternal(@NonNull String packageName);
694 
695     @NonNull
getPackageStates()696     public abstract ArrayMap<String, ? extends PackageStateInternal> getPackageStates();
697 
698     /**
699      * Returns a package for the given UID. If the UID is part of a shared user ID, one
700      * of the packages will be chosen to be returned.
701      */
getPackage(int uid)702     public abstract @Nullable AndroidPackage getPackage(int uid);
703 
704 
705     /**
706      * Returns all packages for the given app ID.
707      */
getPackagesForAppId(int appId)708     public abstract @NonNull List<AndroidPackage> getPackagesForAppId(int appId);
709 
710     /**
711      * Returns a list without a change observer.
712      *
713      * @see #getPackageList(PackageListObserver)
714      */
getPackageList()715     public @NonNull PackageList getPackageList() {
716         return getPackageList(null);
717     }
718 
719     /**
720      * Returns the list of packages installed at the time of the method call.
721      * <p>The given observer is notified when the list of installed packages
722      * changes [eg. a package was installed or uninstalled]. It will not be
723      * notified if a package is updated.
724      * <p>The package list will not be updated automatically as packages are
725      * installed / uninstalled. Any changes must be handled within the observer.
726      *
727      * @deprecated please use {@link com.android.internal.content.PackageMonitor} instead.
728      * PackageMonitor covers more installation and uninstallation corner cases than
729      * PackageListObserver.
730      */
731     @Deprecated
getPackageList(@ullable PackageListObserver observer)732     public abstract @NonNull PackageList getPackageList(@Nullable PackageListObserver observer);
733 
734     /**
735      * Removes the observer.
736      * <p>Generally not needed. {@link #getPackageList(PackageListObserver)} will automatically
737      * remove the observer.
738      * <p>Does nothing if the observer isn't currently registered.
739      * <p>Observers are notified asynchronously and it's possible for an observer to be
740      * invoked after its been removed.
741      *
742      * @deprecated please use {@link com.android.internal.content.PackageMonitor} instead.
743      * PackageMonitor covers more installation and uninstallation corner cases than
744      * PackageListObserver.
745      */
746     @Deprecated
removePackageListObserver(@onNull PackageListObserver observer)747     public abstract void removePackageListObserver(@NonNull PackageListObserver observer);
748 
749     /**
750      * Returns a package object for the disabled system package name.
751      */
getDisabledSystemPackage( @onNull String packageName)752     public abstract @Nullable PackageStateInternal getDisabledSystemPackage(
753             @NonNull String packageName);
754 
755     /**
756      * Returns the package name for the disabled system package.
757      *
758      * This is equivalent to
759      * {@link #getDisabledSystemPackage(String)}
760      *     .{@link PackageSetting#pkg}
761      *     .{@link AndroidPackage#getPackageName()}
762      */
getDisabledSystemPackageName(@onNull String packageName)763     public abstract @Nullable String getDisabledSystemPackageName(@NonNull String packageName);
764 
765     /**
766      * Returns whether or not the component is the resolver activity.
767      */
isResolveActivityComponent(@onNull ComponentInfo component)768     public abstract boolean isResolveActivityComponent(@NonNull ComponentInfo component);
769 
770     /**
771      * Returns a list of package names for a known package
772      */
getKnownPackageNames( @nownPackages.KnownPackage int knownPackage, int userId)773     public abstract @NonNull String[] getKnownPackageNames(
774             @KnownPackages.KnownPackage int knownPackage, int userId);
775 
776     /**
777      * Returns whether the package is an instant app.
778      */
isInstantApp(String packageName, int userId)779     public abstract boolean isInstantApp(String packageName, int userId);
780 
781     /**
782      * Returns whether the package is an instant app.
783      */
getInstantAppPackageName(int uid)784     public abstract @Nullable String getInstantAppPackageName(int uid);
785 
786     /**
787      * Returns whether or not access to the application should be filtered. The access is not
788      * allowed if the application is not installed under the given user.
789      * <p>
790      * Access may be limited based upon whether the calling or target applications
791      * are instant applications.
792      *
793      * @see #canAccessInstantApps
794      *
795      * @param pkg The package to be accessed.
796      * @param callingUid The uid that attempts to access the package.
797      * @param userId The user id where the package resides.
798      */
filterAppAccess( @onNull AndroidPackage pkg, int callingUid, int userId)799     public abstract boolean filterAppAccess(
800             @NonNull AndroidPackage pkg, int callingUid, int userId);
801 
802     /**
803      * Returns whether or not access to the application should be filtered. The access is not
804      * allowed if the application is not installed under the given user.
805      *
806      * @see #filterAppAccess(AndroidPackage, int, int)
807      */
filterAppAccess(@onNull String packageName, int callingUid, int userId)808     public boolean filterAppAccess(@NonNull String packageName, int callingUid, int userId) {
809         return filterAppAccess(packageName, callingUid, userId, true /* filterUninstalled */);
810     }
811 
812     /**
813      * Returns whether or not access to the application should be filtered.
814      *
815      * @param packageName The package to be accessed.
816      * @param callingUid The uid that attempts to access the package.
817      * @param userId The user id where the package resides.
818      * @param filterUninstalled Set to true to filter the access if the package is not installed
819      *                        under the given user.
820      * @see #filterAppAccess(AndroidPackage, int, int)
821      */
filterAppAccess( @onNull String packageName, int callingUid, int userId, boolean filterUninstalled)822     public abstract boolean filterAppAccess(
823             @NonNull String packageName, int callingUid, int userId, boolean filterUninstalled);
824 
825     /**
826      * Returns whether or not access to the application which belongs to the given UID should be
827      * filtered. If the UID is part of a shared user ID, return {@code true} if all applications
828      * belong to the shared user ID should be filtered. The access is not allowed if the uid does
829      * not exist in the device.
830      *
831      * @see #filterAppAccess(AndroidPackage, int, int)
832      */
filterAppAccess(int uid, int callingUid)833     public abstract boolean filterAppAccess(int uid, int callingUid);
834 
835     /**
836      * Fetches all app Ids that a given application is currently visible to the provided user.
837      *
838      * <p>
839      * <strong>Note: </strong>This only includes UIDs >= {@link Process#FIRST_APPLICATION_UID}
840      * as all other UIDs can already see all applications.
841      * </p>
842      *
843      * If the app is visible to all UIDs, null is returned. If the app is not visible to any
844      * applications, the int array will be empty.
845      */
846     @Nullable
getVisibilityAllowList(@onNull String packageName, int userId)847     public abstract int[] getVisibilityAllowList(@NonNull String packageName, int userId);
848 
849     /**
850      * Returns whether the given UID either declares &lt;queries&gt; element with the given package
851      * name in its app's manifest, has {@link android.Manifest.permission.QUERY_ALL_PACKAGES}, or
852      * package visibility filtering is enabled on it. If the UID is part of a shared user ID,
853      * return {@code true} if any one application belongs to the shared user ID meets the criteria.
854      */
canQueryPackage(int callingUid, @Nullable String packageName)855     public abstract boolean canQueryPackage(int callingUid, @Nullable String packageName);
856 
857     /** Returns whether the given package was signed by the platform */
isPlatformSigned(String pkg)858     public abstract boolean isPlatformSigned(String pkg);
859 
860     /**
861      * Returns true if it's still safe to restore data backed up from this app's version
862      * that was signed with restoringFromSigHash.
863      */
isDataRestoreSafe(@onNull byte[] restoringFromSigHash, @NonNull String packageName)864     public abstract boolean isDataRestoreSafe(@NonNull byte[] restoringFromSigHash,
865             @NonNull String packageName);
866 
867     /**
868      * Returns true if it's still safe to restore data backed up from this app's version
869      * that was signed with restoringFromSig.
870      */
isDataRestoreSafe(@onNull Signature restoringFromSig, @NonNull String packageName)871     public abstract boolean isDataRestoreSafe(@NonNull Signature restoringFromSig,
872             @NonNull String packageName);
873 
874     /**
875      * Returns {@code true} if the signing information for {@code clientUid} is sufficient
876      * to gain access gated by {@code capability}.  This can happen if the two UIDs have the
877      * same signing information, if the signing information {@code clientUid} indicates that
878      * it has the signing certificate for {@code serverUid} in its signing history (if it was
879      * previously signed by it), or if the signing certificate for {@code clientUid} is in the
880      * signing history for {@code serverUid} and with the {@code capability} specified.
881      */
hasSignatureCapability(int serverUid, int clientUid, @CertCapabilities int capability)882     public abstract boolean hasSignatureCapability(int serverUid, int clientUid,
883             @CertCapabilities int capability);
884 
885     /**
886      * Get appIds of all available apps which specified android:sharedUserId in the manifest.
887      *
888      * @return a SparseArray mapping from appId to it's sharedUserId.
889      */
getAppsWithSharedUserIds()890     public abstract SparseArray<String> getAppsWithSharedUserIds();
891 
892     /**
893      * Get all packages which share the same userId as the specified package, or an empty array
894      * if the package does not have a shared userId.
895      */
896     @NonNull
getSharedUserPackagesForPackage(@onNull String packageName, int userId)897     public abstract String[] getSharedUserPackagesForPackage(@NonNull String packageName,
898             int userId);
899 
900     /**
901      * Return the processes that have been declared for a uid.
902      *
903      * @param uid The uid to query.
904      *
905      * @return Returns null if there are no declared processes for the uid; otherwise,
906      * returns the set of processes it declared.
907      */
getProcessesForUid(int uid)908     public abstract ArrayMap<String, ProcessInfo> getProcessesForUid(int uid);
909 
910     /**
911      * Return the gids associated with a particular permission.
912      *
913      * @param permissionName The name of the permission to query.
914      * @param userId The user id the gids will be associated with.
915      *
916      * @return Returns null if there are no gids associated with the permission, otherwise an
917      * array if the gid ints.
918      */
getPermissionGids(String permissionName, int userId)919     public abstract int[] getPermissionGids(String permissionName, int userId);
920 
921     /**
922      * Make a best-effort attempt to provide the requested free disk space by
923      * deleting cached files.
924      *
925      * @throws IOException if the request was unable to be fulfilled.
926      */
freeStorage(String volumeUuid, long bytes, @StorageManager.AllocateFlags int flags)927     public abstract void freeStorage(String volumeUuid, long bytes,
928             @StorageManager.AllocateFlags int flags) throws IOException;
929 
930     /**
931      * Blocking call to clear all cached app data above quota.
932      */
freeAllAppCacheAboveQuota(@onNull String volumeUuid)933     public abstract void freeAllAppCacheAboveQuota(@NonNull String volumeUuid) throws IOException;
934 
935     /** Returns {@code true} if the specified component is enabled and matches the given flags. */
isEnabledAndMatches(@onNull ParsedMainComponent component, @PackageManager.ComponentInfoFlagsBits long flags, int userId)936     public abstract boolean isEnabledAndMatches(@NonNull ParsedMainComponent component,
937             @PackageManager.ComponentInfoFlagsBits long flags, int userId);
938 
939     /** Returns {@code true} if the given user requires extra badging for icons. */
userNeedsBadging(int userId)940     public abstract boolean userNeedsBadging(int userId);
941 
942     /**
943      * Perform the given action for each {@link PackageSetting}.
944      * Note that packages lock will be held while performing the actions.
945      *
946      * If the caller does not need all packages, prefer the potentially non-locking
947      * {@link #withPackageSettingsSnapshot(Consumer)}.
948      *
949      * @param actionLocked action to be performed
950      */
forEachPackageSetting(Consumer<PackageSetting> actionLocked)951     public abstract void forEachPackageSetting(Consumer<PackageSetting> actionLocked);
952 
953     /**
954      * Perform the given action for each package.
955      * @param action action to be performed
956      */
forEachPackageState(Consumer<PackageStateInternal> action)957     public abstract void forEachPackageState(Consumer<PackageStateInternal> action);
958 
959     /**
960      * {@link #forEachPackageState(Consumer)} but filtered to only states with packages
961      * on device where {@link PackageStateInternal#getPkg()} is not null.
962      */
forEachPackage(Consumer<AndroidPackage> action)963     public abstract void forEachPackage(Consumer<AndroidPackage> action);
964 
965     /**
966      * Perform the given action for each installed package for a user.
967      */
forEachInstalledPackage( @onNull Consumer<AndroidPackage> action, @UserIdInt int userId)968     public abstract void forEachInstalledPackage(
969             @NonNull Consumer<AndroidPackage> action, @UserIdInt int userId);
970 
971     /** Returns the list of enabled components */
getEnabledComponents(String packageName, int userId)972     public abstract ArraySet<String> getEnabledComponents(String packageName, int userId);
973 
974     /** Returns the list of disabled components */
getDisabledComponents(String packageName, int userId)975     public abstract ArraySet<String> getDisabledComponents(String packageName, int userId);
976 
977     /** Returns whether the given package is enabled for the given user */
getApplicationEnabledState( String packageName, int userId)978     public abstract @PackageManager.EnabledState int getApplicationEnabledState(
979             String packageName, int userId);
980 
981     /**
982      * Return the enabled setting for a package component (activity, receiver, service, provider).
983      */
getComponentEnabledSetting( @onNull ComponentName componentName, int callingUid, int userId)984     public abstract @PackageManager.EnabledState int getComponentEnabledSetting(
985             @NonNull ComponentName componentName, int callingUid, int userId);
986 
987     /**
988      * Extra field name for the token of a request to enable rollback for a
989      * package.
990      */
991     public static final String EXTRA_ENABLE_ROLLBACK_TOKEN =
992             "android.content.pm.extra.ENABLE_ROLLBACK_TOKEN";
993 
994     /**
995      * Extra field name for the session id of a request to enable rollback
996      * for a package.
997      */
998     public static final String EXTRA_ENABLE_ROLLBACK_SESSION_ID =
999             "android.content.pm.extra.ENABLE_ROLLBACK_SESSION_ID";
1000 
1001     /**
1002      * Used as the {@code enableRollbackCode} argument for
1003      * {@link PackageManagerInternal#setEnableRollbackCode} to indicate that
1004      * enabling rollback succeeded.
1005      */
1006     public static final int ENABLE_ROLLBACK_SUCCEEDED = 1;
1007 
1008     /**
1009      * Used as the {@code enableRollbackCode} argument for
1010      * {@link PackageManagerInternal#setEnableRollbackCode} to indicate that
1011      * enabling rollback failed.
1012      */
1013     public static final int ENABLE_ROLLBACK_FAILED = -1;
1014 
1015     /**
1016      * Allows the rollback manager listening to the
1017      * {@link Intent#ACTION_PACKAGE_ENABLE_ROLLBACK enable rollback broadcast}
1018      * to respond to the package manager. The response must include the
1019      * {@code enableRollbackCode} which is one of
1020      * {@link PackageManager#ENABLE_ROLLBACK_SUCCEEDED} or
1021      * {@link PackageManager#ENABLE_ROLLBACK_FAILED}.
1022      *
1023      * @param token pending package identifier as passed via the
1024      *            {@link PackageManager#EXTRA_ENABLE_ROLLBACK_TOKEN} Intent extra.
1025      * @param enableRollbackCode the status code result of enabling rollback
1026      * @throws SecurityException if the caller does not have the
1027      *            PACKAGE_ROLLBACK_AGENT permission.
1028      */
setEnableRollbackCode(int token, int enableRollbackCode)1029     public abstract void setEnableRollbackCode(int token, int enableRollbackCode);
1030 
1031     /*
1032      * Inform the package manager that the pending package install identified by
1033      * {@code token} can be completed.
1034      */
finishPackageInstall(int token, boolean didLaunch)1035     public abstract void finishPackageInstall(int token, boolean didLaunch);
1036 
1037     /**
1038      * Remove the default browser stored in the legacy package settings.
1039      *
1040      * @param userId the user id
1041      *
1042      * @return the package name of the default browser, or {@code null} if none
1043      */
1044     @Nullable
removeLegacyDefaultBrowserPackageName(int userId)1045     public abstract String removeLegacyDefaultBrowserPackageName(int userId);
1046 
1047     /**
1048      * Returns {@code true} if given {@code packageName} is an apex package.
1049      */
isApexPackage(String packageName)1050     public abstract boolean isApexPackage(String packageName);
1051 
1052     /**
1053      * Returns list of {@code packageName} of apks inside the given apex.
1054      * @param apexPackageName Package name of the apk container of apex
1055      */
getApksInApex(String apexPackageName)1056     public abstract List<String> getApksInApex(String apexPackageName);
1057 
1058     /**
1059      * Uninstalls given {@code packageName}.
1060      *
1061      * @param packageName apex package to uninstall.
1062      * @param versionCode version of a package to uninstall.
1063      * @param userId user to uninstall apex package for. Must be
1064      *               {@link android.os.UserHandle#USER_ALL}, otherwise failure will be reported.
1065      * @param intentSender a {@link IntentSender} to send result of an uninstall to.
1066      * @param flags flags about the uninstall.
1067      */
uninstallApex(String packageName, long versionCode, int userId, IntentSender intentSender, @PackageManager.InstallFlags int installFlags)1068     public abstract void uninstallApex(String packageName, long versionCode, int userId,
1069             IntentSender intentSender, @PackageManager.InstallFlags int installFlags);
1070 
1071     /**
1072      * Update fingerprint of build that updated the runtime permissions for a user.
1073      *
1074      * @param userId The user to update
1075      */
updateRuntimePermissionsFingerprint(@serIdInt int userId)1076     public abstract void updateRuntimePermissionsFingerprint(@UserIdInt int userId);
1077 
1078     /**
1079      * Migrates legacy obb data to its new location.
1080      */
migrateLegacyObbData()1081     public abstract void migrateLegacyObbData();
1082 
1083     /**
1084      * Writes all package manager settings to disk. If {@code async} is {@code true}, the
1085      * settings are written at some point in the future. Otherwise, the call blocks until
1086      * the settings have been written.
1087      */
writeSettings(boolean async)1088     public abstract void writeSettings(boolean async);
1089 
1090     /**
1091      * Writes all permission settings for the given set of users to disk. If {@code async}
1092      * is {@code true}, the settings are written at some point in the future. Otherwise,
1093      * the call blocks until the settings have been written.
1094      */
writePermissionSettings(@onNull @serIdInt int[] userIds, boolean async)1095     public abstract void writePermissionSettings(@NonNull @UserIdInt int[] userIds, boolean async);
1096 
1097     /**
1098      * Read legacy permission definitions for permissions migration to new permission subsystem.
1099      * Note that this api is supposed to be used for permissions migration only.
1100      */
getLegacyPermissions()1101     public abstract LegacyPermissionSettings getLegacyPermissions();
1102 
1103     /**
1104      * Read legacy permission states for permissions migration to new permission subsystem.
1105      * Note that this api is supposed to be used for permissions state migration only.
1106      */
1107     // TODO: restore to com.android.permission.persistence.RuntimePermissionsState
1108     // once Ravenwood includes Mainline stubs
getLegacyPermissionsState(@serIdInt int userId)1109     public abstract Object getLegacyPermissionsState(@UserIdInt int userId);
1110 
1111     /**
1112      * @return permissions file version for the given user.
1113      */
getLegacyPermissionsVersion(@serIdInt int userId)1114     public abstract int getLegacyPermissionsVersion(@UserIdInt int userId);
1115 
1116     /**
1117      * Returns {@code true} if the caller is the installer of record for the given package.
1118      * Otherwise, {@code false}.
1119      */
isCallerInstallerOfRecord( @onNull AndroidPackage pkg, int callingUid)1120     public abstract boolean isCallerInstallerOfRecord(
1121             @NonNull AndroidPackage pkg, int callingUid);
1122 
1123     /** Returns whether or not permissions need to be upgraded for the given user */
isPermissionUpgradeNeeded(@serIdInt int userId)1124     public abstract boolean isPermissionUpgradeNeeded(@UserIdInt int userId);
1125 
1126     /**
1127      * Used to allow the integrity component to respond to the
1128      * ACTION_PACKAGE_NEEDS_INTEGRITY_VERIFICATION package verification
1129      * broadcast to respond to the package manager.
1130      *
1131      * Deprecated.
1132      */
1133     @Deprecated
setIntegrityVerificationResult(int verificationId, @IntegrityVerificationResult int verificationResult)1134     public abstract void setIntegrityVerificationResult(int verificationId,
1135             @IntegrityVerificationResult int verificationResult);
1136 
1137     /**
1138      * Returns MIME types contained in {@code mimeGroup} from {@code packageName} package
1139      */
getMimeGroup(String packageName, String mimeGroup)1140     public abstract List<String> getMimeGroup(String packageName, String mimeGroup);
1141 
1142     /**
1143      * Toggles visibility logging to help in debugging the app enumeration feature.
1144      * @param packageName the package name that should begin logging
1145      * @param enabled true if visibility blocks should be logged
1146      */
setVisibilityLogging(String packageName, boolean enabled)1147     public abstract void setVisibilityLogging(String packageName, boolean enabled);
1148 
1149     /**
1150      * Returns if a package name is a valid system package.
1151      */
isSystemPackage(@onNull String packageName)1152     public abstract boolean isSystemPackage(@NonNull String packageName);
1153 
1154     /**
1155      * Unblocks uninstall for all packages for the user.
1156      */
clearBlockUninstallForUser(@serIdInt int userId)1157     public abstract void clearBlockUninstallForUser(@UserIdInt int userId);
1158 
1159     /**
1160      * Unsuspends all packages suspended by an admin for the user.
1161      */
unsuspendAdminSuspendedPackages(int userId)1162     public abstract void unsuspendAdminSuspendedPackages(int userId);
1163 
1164     /**
1165      * Returns {@code true} if an admin is suspending any packages for the user.
1166      */
isAdminSuspendingAnyPackages(int userId)1167     public abstract boolean isAdminSuspendingAnyPackages(int userId);
1168 
1169     /**
1170      * Register to listen for loading progress of an installed package.
1171      * The listener is automatically unregistered when the app is fully loaded.
1172      * @param packageName The name of the installed package
1173      * @param callback To loading reporting progress
1174      * @param userId The user under which to check.
1175      * @return Whether the registration was successful. It can fail if the package has not been
1176      *          installed yet.
1177      */
registerInstalledLoadingProgressCallback(@onNull String packageName, @NonNull InstalledLoadingProgressCallback callback, int userId)1178     public abstract boolean registerInstalledLoadingProgressCallback(@NonNull String packageName,
1179             @NonNull InstalledLoadingProgressCallback callback, int userId);
1180 
1181     /**
1182      * Callback to listen for loading progress of a package installed on Incremental File System.
1183      */
1184     public abstract static class InstalledLoadingProgressCallback {
1185         final LoadingProgressCallbackBinder mBinder = new LoadingProgressCallbackBinder();
1186         final Executor mExecutor;
1187         /**
1188          * Default constructor that should always be called on subclass instantiation
1189          * @param handler To dispatch callback events through. If null, the main thread
1190          *                handler will be used.
1191          */
InstalledLoadingProgressCallback(@ullable Handler handler)1192         public InstalledLoadingProgressCallback(@Nullable Handler handler) {
1193             if (handler == null) {
1194                 handler = new Handler(Looper.getMainLooper());
1195             }
1196             mExecutor = new HandlerExecutor(handler);
1197         }
1198 
1199         /**
1200          * Binder used by Package Manager Service to register as a callback
1201          * @return the binder object of IPackageLoadingProgressCallback
1202          */
getBinder()1203         public final @NonNull IBinder getBinder() {
1204             return mBinder;
1205         }
1206 
1207         /**
1208          * Report loading progress of an installed package.
1209          *
1210          * @param progress    Loading progress between [0, 1] for the registered package.
1211          */
onLoadingProgressChanged(float progress)1212         public abstract void onLoadingProgressChanged(float progress);
1213 
1214         private class LoadingProgressCallbackBinder extends
1215                 android.content.pm.IPackageLoadingProgressCallback.Stub {
1216             @Override
onPackageLoadingProgressChanged(float progress)1217             public void onPackageLoadingProgressChanged(float progress) {
1218                 mExecutor.execute(PooledLambda.obtainRunnable(
1219                         InstalledLoadingProgressCallback::onLoadingProgressChanged,
1220                         InstalledLoadingProgressCallback.this,
1221                         progress).recycleOnUse());
1222             }
1223         }
1224     }
1225 
1226     /**
1227      * Retrieve all of the information we know about a particular activity class including its
1228      * package states.
1229      *
1230      * @param packageName a specific package
1231      * @param filterCallingUid The results will be filtered in the context of this UID instead
1232      *                         of the calling UID.
1233      * @param userId The user for whom the package is installed
1234      * @return IncrementalStatesInfo that contains information about package states.
1235      */
getIncrementalStatesInfo(String packageName, int filterCallingUid, int userId)1236     public abstract IncrementalStatesInfo getIncrementalStatesInfo(String packageName,
1237             int filterCallingUid, int userId);
1238 
1239     /**
1240      * Requesting the checksums for APKs within a package.
1241      * See {@link PackageManager#requestChecksums} for details.
1242      *
1243      * @param executor to use for digest calculations.
1244      * @param handler to use for postponed calculations.
1245      */
requestChecksums(@onNull String packageName, boolean includeSplits, @Checksum.TypeMask int optional, @Checksum.TypeMask int required, @Nullable List trustedInstallers, @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId, @NonNull Executor executor, @NonNull Handler handler)1246     public abstract void requestChecksums(@NonNull String packageName, boolean includeSplits,
1247             @Checksum.TypeMask int optional, @Checksum.TypeMask int required,
1248             @Nullable List trustedInstallers,
1249             @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId,
1250             @NonNull Executor executor, @NonNull Handler handler);
1251 
1252     /**
1253      * Returns true if the given {@code packageName} and {@code userId} is frozen.
1254      *
1255      * @param packageName a specific package
1256      * @param callingUid The uid of the caller
1257      * @param userId The user for whom the package is installed
1258      * @return {@code true} If the package is current frozen (due to install/update etc.)
1259      */
isPackageFrozen( @onNull String packageName, int callingUid, int userId)1260     public abstract boolean isPackageFrozen(
1261             @NonNull String packageName, int callingUid, int userId);
1262 
1263     /**
1264      * Deletes the OAT artifacts of a package.
1265      * @param packageName a specific package
1266      * @return the number of freed bytes or -1 if there was an error in the process.
1267      */
deleteOatArtifactsOfPackage(String packageName)1268     public abstract long deleteOatArtifactsOfPackage(String packageName);
1269 
1270     /**
1271      * Reconcile all app data for the given user.
1272      */
reconcileAppsData(int userId, @StorageManager.StorageFlags int flags, boolean migrateAppsData)1273     public abstract void reconcileAppsData(int userId, @StorageManager.StorageFlags int flags,
1274             boolean migrateAppsData);
1275 
1276     /**
1277      * Returns an array of PackageStateInternal that are all part of a shared user setting which is
1278      * denoted by the app ID. Returns an empty set if the shared user setting doesn't exist or does
1279      * not contain any package.
1280      */
1281     @NonNull
getSharedUserPackages(int sharedUserAppId)1282     public abstract ArraySet<PackageStateInternal> getSharedUserPackages(int sharedUserAppId);
1283 
1284     /**
1285      * Returns the SharedUserApi denoted by the app ID of the shared user setting. Returns null if
1286      * the corresponding shared user setting doesn't exist.
1287      */
1288     @Nullable
getSharedUserApi(int sharedUserAppId)1289     public abstract SharedUserApi getSharedUserApi(int sharedUserAppId);
1290 
1291     /**
1292      * Returns if the given uid is privileged or not.
1293      */
isUidPrivileged(int uid)1294     public abstract boolean isUidPrivileged(int uid);
1295 
1296     /**
1297      * Initiates a package state mutation request, returning the current state as known by
1298      * PackageManager. This allows the later commit request to compare the initial values and
1299      * determine if any state was changed or any packages were updated since the whole request
1300      * was initiated.
1301      *
1302      * As a concrete example, consider the following steps:
1303      * <ol>
1304      *     <li>Read a package state without taking a lock</li>
1305      *     <li>Check some values in that state, determine that a mutation needs to occur</li>
1306      *     <li>Call to commit the change with the new value, takes lock</li>
1307      * </ol>
1308      *
1309      * Between steps 1 and 3, because the lock was not taken for the entire flow, it's possible
1310      * a package state was changed by another consumer or a package was updated/installed.
1311      *
1312      * If anything has changed,
1313      * {@link #commitPackageStateMutation(PackageStateMutator.InitialState, Consumer)} will return
1314      * a {@link PackageStateMutator.Result} indicating so. If the caller has not indicated it can
1315      * ignore changes, it can opt to re-run the commit logic from the top with a true write lock
1316      * around all of its read-logic-commit loop.
1317      *
1318      * Note that if the caller does not care about potential race conditions or package/state
1319      * changes between steps 1 and 3, it can simply opt to not call this method and pass in null
1320      * for the initial state. This is useful to avoid long running data structure locks when the
1321      * caller is changing a value as part of a one-off request. Perhaps from an app side API which
1322      * mutates only a single package, where it doesn't care what the state of that package is or
1323      * any other packages on the devices.
1324      *
1325      * Important to note is that if no locking is enforced, callers themselves will not be
1326      * synchronized with themselves. The caller may be relying on the PackageManager lock to
1327      * enforce ordering within their own code path, and that has to be adjusted if migrated off
1328      * the lock.
1329      */
1330     @NonNull
recordInitialState()1331     public abstract PackageStateMutator.InitialState recordInitialState();
1332 
1333     /**
1334      * Some questions to ask when designing a mutation:
1335      * <ol>
1336      *     <li>What external system state is required and is it synchronized properly?</li>
1337      *     <li>Are there any package/state changes that could happen to the target (or another)
1338      *     package that could result in the commit being invalid?</li>
1339      *     <li>Is the caller synchronized with itself and can handle multiple mutations being
1340      *     requested from different threads?</li>
1341      *     <li>What should be done in case of a conflict and the commit can't be finished?</li>
1342      * </ol>
1343      *
1344      * @param state See {@link #recordInitialState()}. If null, no result is returned.
1345      * @param consumer Lean wrapper around just the logic that changes state values
1346      * @return result if anything changed since initial state, or null if nothing changed and
1347      * commit was successful
1348      */
1349     @Nullable
commitPackageStateMutation( @ullable PackageStateMutator.InitialState state, @NonNull Consumer<PackageStateMutator> consumer)1350     public abstract PackageStateMutator.Result commitPackageStateMutation(
1351             @Nullable PackageStateMutator.InitialState state,
1352             @NonNull Consumer<PackageStateMutator> consumer);
1353 
1354     /**
1355      * @return package data snapshot for use with other PackageManager infrastructure. This should
1356      * only be used as a parameter passed to another PM related class. Do not call methods on this
1357      * directly.
1358      */
1359     @NonNull
snapshot()1360     public abstract PackageDataSnapshot snapshot();
1361 
shutdown()1362     public abstract void shutdown();
1363 
getDynamicCodeLogger()1364     public abstract DynamicCodeLogger getDynamicCodeLogger();
1365 
1366     /**
1367      * Compare the signatures of two packages that are installed in different users.
1368      *
1369      * @param uid1 First UID whose signature will be compared.
1370      * @param uid2 Second UID whose signature will be compared.
1371      * @return {@link PackageManager#SIGNATURE_MATCH} if signatures are matched.
1372      * @throws SecurityException if the caller does not hold the
1373      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS}.
1374      */
checkUidSignaturesForAllUsers(int uid1, int uid2)1375     public abstract @SignatureResult int checkUidSignaturesForAllUsers(int uid1, int uid2);
1376 
setPackageStoppedState(@onNull String packageName, boolean stopped, @UserIdInt int userId)1377     public abstract void setPackageStoppedState(@NonNull String packageName, boolean stopped,
1378             @UserIdInt int userId);
1379 
1380     /**
1381      * Tells PackageManager when a component of the package is used
1382      * and the package should get out of stopped state and be enabled.
1383      */
notifyComponentUsed(@onNull String packageName, @UserIdInt int userId, @Nullable String recentCallingPackage, @NonNull String debugInfo)1384     public abstract void notifyComponentUsed(@NonNull String packageName,
1385             @UserIdInt int userId, @Nullable String recentCallingPackage,
1386             @NonNull String debugInfo);
1387 
1388     /**
1389      * Gets {@link PackageManager.DistractionRestriction restrictions} of the given
1390      * packages of the given user.
1391      *
1392      * The corresponding element of the resulting array will be -1 if a given package doesn't exist.
1393      *
1394      * @param packageNames The packages under which to check.
1395      * @param userId The user under which to check.
1396      * @return an array of distracting restriction state in order of the given packages
1397      */
getDistractingPackageRestrictionsAsUser( @onNull String[] packageNames, int userId)1398     public abstract int[] getDistractingPackageRestrictionsAsUser(
1399             @NonNull String[] packageNames, int userId);
1400 
1401     /**
1402      * Checks if package is quarantined for a specific user.
1403      *
1404      * @throws PackageManager.NameNotFoundException if the package is not found
1405      */
isPackageQuarantined(@onNull String packageName, @UserIdInt int userId)1406     public abstract boolean isPackageQuarantined(@NonNull String packageName, @UserIdInt int userId)
1407             throws PackageManager.NameNotFoundException;
1408 
1409     /**
1410      * Checks if package is stopped for a specific user.
1411      *
1412      * @throws PackageManager.NameNotFoundException if the package is not found
1413      */
isPackageStopped(@onNull String packageName, @UserIdInt int userId)1414     public abstract boolean isPackageStopped(@NonNull String packageName, @UserIdInt int userId)
1415             throws PackageManager.NameNotFoundException;
1416 
1417     /**
1418      * Sends the PACKAGE_RESTARTED broadcast.
1419      */
sendPackageRestartedBroadcast(@onNull String packageName, int uid, @Intent.Flags int flags)1420     public abstract void sendPackageRestartedBroadcast(@NonNull String packageName,
1421             int uid, @Intent.Flags int flags);
1422 
1423     /**
1424      * Return a list of all historical install sessions for the given user.
1425      */
getHistoricalSessions( int userId)1426     public abstract ParceledListSlice<PackageInstaller.SessionInfo> getHistoricalSessions(
1427             int userId);
1428 
1429     /**
1430      * Sends the ACTION_PACKAGE_DATA_CLEARED broadcast.
1431      */
sendPackageDataClearedBroadcast(@onNull String packageName, int uid, int userId, boolean isRestore, boolean isInstantApp)1432     public abstract void sendPackageDataClearedBroadcast(@NonNull String packageName,
1433             int uid, int userId, boolean isRestore, boolean isInstantApp);
1434 
1435     /**
1436      * Returns an instance of {@link PackageArchiver} to be used for archiving related operations.
1437      */
1438     @NonNull
getPackageArchiver()1439     public abstract PackageArchiver getPackageArchiver();
1440 
1441     /**
1442      * Returns true if the device is upgrading from an SDK version lower than the one specified.
1443      */
isUpgradingFromLowerThan(int sdkVersion)1444     public abstract boolean isUpgradingFromLowerThan(int sdkVersion);
1445 }
1446