• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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.CallbackExecutor;
20 import android.annotation.IntDef;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.SdkConstant;
24 import android.annotation.SdkConstant.SdkConstantType;
25 import android.annotation.SystemApi;
26 import android.annotation.SystemService;
27 import android.annotation.TestApi;
28 import android.annotation.UnsupportedAppUsage;
29 import android.app.PendingIntent;
30 import android.appwidget.AppWidgetManager;
31 import android.appwidget.AppWidgetProviderInfo;
32 import android.content.ActivityNotFoundException;
33 import android.content.ComponentName;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentSender;
37 import android.content.pm.PackageInstaller.SessionCallback;
38 import android.content.pm.PackageInstaller.SessionCallbackDelegate;
39 import android.content.pm.PackageInstaller.SessionInfo;
40 import android.content.pm.PackageManager.ApplicationInfoFlags;
41 import android.content.pm.PackageManager.NameNotFoundException;
42 import android.content.res.Resources;
43 import android.graphics.Bitmap;
44 import android.graphics.BitmapFactory;
45 import android.graphics.Rect;
46 import android.graphics.drawable.AdaptiveIconDrawable;
47 import android.graphics.drawable.BitmapDrawable;
48 import android.graphics.drawable.Drawable;
49 import android.graphics.drawable.Icon;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.Handler;
53 import android.os.Looper;
54 import android.os.Message;
55 import android.os.Parcel;
56 import android.os.ParcelFileDescriptor;
57 import android.os.Parcelable;
58 import android.os.RemoteException;
59 import android.os.ServiceManager;
60 import android.os.UserHandle;
61 import android.os.UserManager;
62 import android.util.DisplayMetrics;
63 import android.util.Log;
64 
65 import com.android.internal.util.Preconditions;
66 
67 import java.io.IOException;
68 import java.lang.annotation.Retention;
69 import java.lang.annotation.RetentionPolicy;
70 import java.util.ArrayList;
71 import java.util.Arrays;
72 import java.util.Collections;
73 import java.util.Iterator;
74 import java.util.List;
75 import java.util.concurrent.Executor;
76 
77 /**
78  * Class for retrieving a list of launchable activities for the current user and any associated
79  * managed profiles that are visible to the current user, which can be retrieved with
80  * {@link #getProfiles}. This is mainly for use by launchers.
81  *
82  * Apps can be queried for each user profile.
83  * Since the PackageManager will not deliver package broadcasts for other profiles, you can register
84  * for package changes here.
85  * <p>
86  * To watch for managed profiles being added or removed, register for the following broadcasts:
87  * {@link Intent#ACTION_MANAGED_PROFILE_ADDED} and {@link Intent#ACTION_MANAGED_PROFILE_REMOVED}.
88  * <p>
89  * Note as of Android O, apps on a managed profile are no longer allowed to access apps on the
90  * main profile.  Apps can only access profiles returned by {@link #getProfiles()}.
91  */
92 @SystemService(Context.LAUNCHER_APPS_SERVICE)
93 public class LauncherApps {
94 
95     static final String TAG = "LauncherApps";
96     static final boolean DEBUG = false;
97 
98     /**
99      * Activity Action: For the default launcher to show the confirmation dialog to create
100      * a pinned shortcut.
101      *
102      * <p>See the {@link ShortcutManager} javadoc for details.
103      *
104      * <p>
105      * Use {@link #getPinItemRequest(Intent)} to get a {@link PinItemRequest} object,
106      * and call {@link PinItemRequest#accept(Bundle)}
107      * if the user accepts.  If the user doesn't accept, no further action is required.
108      *
109      * @see #EXTRA_PIN_ITEM_REQUEST
110      */
111     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
112     public static final String ACTION_CONFIRM_PIN_SHORTCUT =
113             "android.content.pm.action.CONFIRM_PIN_SHORTCUT";
114 
115     /**
116      * Activity Action: For the default launcher to show the confirmation dialog to create
117      * a pinned app widget.
118      *
119      * <p>See the {@link android.appwidget.AppWidgetManager#requestPinAppWidget} javadoc for
120      * details.
121      *
122      * <p>
123      * Use {@link #getPinItemRequest(Intent)} to get a {@link PinItemRequest} object,
124      * and call {@link PinItemRequest#accept(Bundle)}
125      * if the user accepts.  If the user doesn't accept, no further action is required.
126      *
127      * @see #EXTRA_PIN_ITEM_REQUEST
128      */
129     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
130     public static final String ACTION_CONFIRM_PIN_APPWIDGET =
131             "android.content.pm.action.CONFIRM_PIN_APPWIDGET";
132 
133     /**
134      * An extra for {@link #ACTION_CONFIRM_PIN_SHORTCUT} &amp; {@link #ACTION_CONFIRM_PIN_APPWIDGET}
135      * containing a {@link PinItemRequest} of appropriate type asked to pin.
136      *
137      * <p>A helper function {@link #getPinItemRequest(Intent)} can be used
138      * instead of using this constant directly.
139      *
140      * @see #ACTION_CONFIRM_PIN_SHORTCUT
141      * @see #ACTION_CONFIRM_PIN_APPWIDGET
142      */
143     public static final String EXTRA_PIN_ITEM_REQUEST =
144             "android.content.pm.extra.PIN_ITEM_REQUEST";
145 
146     private final Context mContext;
147     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
148     private final ILauncherApps mService;
149     @UnsupportedAppUsage
150     private final PackageManager mPm;
151     private final UserManager mUserManager;
152 
153     private final List<CallbackMessageHandler> mCallbacks = new ArrayList<>();
154     private final List<SessionCallbackDelegate> mDelegates = new ArrayList<>();
155 
156     /**
157      * Callbacks for package changes to this and related managed profiles.
158      */
159     public static abstract class Callback {
160         /**
161          * Indicates that a package was removed from the specified profile.
162          *
163          * If a package is removed while being updated onPackageChanged will be
164          * called instead.
165          *
166          * @param packageName The name of the package that was removed.
167          * @param user The UserHandle of the profile that generated the change.
168          */
onPackageRemoved(String packageName, UserHandle user)169         abstract public void onPackageRemoved(String packageName, UserHandle user);
170 
171         /**
172          * Indicates that a package was added to the specified profile.
173          *
174          * If a package is added while being updated then onPackageChanged will be
175          * called instead.
176          *
177          * @param packageName The name of the package that was added.
178          * @param user The UserHandle of the profile that generated the change.
179          */
onPackageAdded(String packageName, UserHandle user)180         abstract public void onPackageAdded(String packageName, UserHandle user);
181 
182         /**
183          * Indicates that a package was modified in the specified profile.
184          * This can happen, for example, when the package is updated or when
185          * one or more components are enabled or disabled.
186          *
187          * @param packageName The name of the package that has changed.
188          * @param user The UserHandle of the profile that generated the change.
189          */
onPackageChanged(String packageName, UserHandle user)190         abstract public void onPackageChanged(String packageName, UserHandle user);
191 
192         /**
193          * Indicates that one or more packages have become available. For
194          * example, this can happen when a removable storage card has
195          * reappeared.
196          *
197          * @param packageNames The names of the packages that have become
198          *            available.
199          * @param user The UserHandle of the profile that generated the change.
200          * @param replacing Indicates whether these packages are replacing
201          *            existing ones.
202          */
onPackagesAvailable(String[] packageNames, UserHandle user, boolean replacing)203         abstract public void onPackagesAvailable(String[] packageNames, UserHandle user,
204                 boolean replacing);
205 
206         /**
207          * Indicates that one or more packages have become unavailable. For
208          * example, this can happen when a removable storage card has been
209          * removed.
210          *
211          * @param packageNames The names of the packages that have become
212          *            unavailable.
213          * @param user The UserHandle of the profile that generated the change.
214          * @param replacing Indicates whether the packages are about to be
215          *            replaced with new versions.
216          */
onPackagesUnavailable(String[] packageNames, UserHandle user, boolean replacing)217         abstract public void onPackagesUnavailable(String[] packageNames, UserHandle user,
218                 boolean replacing);
219 
220         /**
221          * Indicates that one or more packages have been suspended. For
222          * example, this can happen when a Device Administrator suspends
223          * an applicaton.
224          *
225          * <p>Note: On devices running {@link android.os.Build.VERSION_CODES#P Android P} or higher,
226          * any apps that override {@link #onPackagesSuspended(String[], UserHandle, Bundle)} will
227          * not receive this callback.
228          *
229          * @param packageNames The names of the packages that have just been
230          *            suspended.
231          * @param user The UserHandle of the profile that generated the change.
232          */
onPackagesSuspended(String[] packageNames, UserHandle user)233         public void onPackagesSuspended(String[] packageNames, UserHandle user) {
234         }
235 
236         /**
237          * Indicates that one or more packages have been suspended. A device administrator or an app
238          * with {@code android.permission.SUSPEND_APPS} can do this.
239          *
240          * <p>A suspending app with the permission {@code android.permission.SUSPEND_APPS} can
241          * optionally provide a {@link Bundle} of extra information that it deems helpful for the
242          * launcher to handle the suspended state of these packages. The contents of this
243          * {@link Bundle} are supposed to be a contract between the suspending app and the launcher.
244          *
245          * @param packageNames The names of the packages that have just been suspended.
246          * @param user the user for which the given packages were suspended.
247          * @param launcherExtras A {@link Bundle} of extras for the launcher, if provided to the
248          *                      system, {@code null} otherwise.
249          * @see PackageManager#isPackageSuspended()
250          * @see #getSuspendedPackageLauncherExtras(String, UserHandle)
251          */
onPackagesSuspended(String[] packageNames, UserHandle user, @Nullable Bundle launcherExtras)252         public void onPackagesSuspended(String[] packageNames, UserHandle user,
253                 @Nullable Bundle launcherExtras) {
254             onPackagesSuspended(packageNames, user);
255         }
256 
257         /**
258          * Indicates that one or more packages have been unsuspended. For
259          * example, this can happen when a Device Administrator unsuspends
260          * an applicaton.
261          *
262          * @param packageNames The names of the packages that have just been
263          *            unsuspended.
264          * @param user The UserHandle of the profile that generated the change.
265          */
onPackagesUnsuspended(String[] packageNames, UserHandle user)266         public void onPackagesUnsuspended(String[] packageNames, UserHandle user) {
267         }
268 
269         /**
270          * Indicates that one or more shortcuts of any kind (dynamic, pinned, or manifest)
271          * have been added, updated or removed.
272          *
273          * <p>Only the applications that are allowed to access the shortcut information,
274          * as defined in {@link #hasShortcutHostPermission()}, will receive it.
275          *
276          * @param packageName The name of the package that has the shortcuts.
277          * @param shortcuts All shortcuts from the package (dynamic, manifest and/or pinned).
278          *    Only "key" information will be provided, as defined in
279          *    {@link ShortcutInfo#hasKeyFieldsOnly()}.
280          * @param user The UserHandle of the profile that generated the change.
281          *
282          * @see ShortcutManager
283          */
onShortcutsChanged(@onNull String packageName, @NonNull List<ShortcutInfo> shortcuts, @NonNull UserHandle user)284         public void onShortcutsChanged(@NonNull String packageName,
285                 @NonNull List<ShortcutInfo> shortcuts, @NonNull UserHandle user) {
286         }
287     }
288 
289     /**
290      * Represents a query passed to {@link #getShortcuts(ShortcutQuery, UserHandle)}.
291      */
292     public static class ShortcutQuery {
293         /**
294          * Include dynamic shortcuts in the result.
295          */
296         public static final int FLAG_MATCH_DYNAMIC = 1 << 0;
297 
298         /** @hide kept for unit tests */
299         @Deprecated
300         public static final int FLAG_GET_DYNAMIC = FLAG_MATCH_DYNAMIC;
301 
302         /**
303          * Include pinned shortcuts in the result.
304          *
305          * <p>If you are the selected assistant app, and wishes to fetch all shortcuts that the
306          * user owns on the launcher (or by other launchers, in case the user has multiple), use
307          * {@link #FLAG_MATCH_PINNED_BY_ANY_LAUNCHER} instead.
308          *
309          * <p>If you're a regular launcher app, there's no way to get shortcuts pinned by other
310          * launchers, and {@link #FLAG_MATCH_PINNED_BY_ANY_LAUNCHER} will be ignored. So use this
311          * flag to get own pinned shortcuts.
312          */
313         public static final int FLAG_MATCH_PINNED = 1 << 1;
314 
315         /** @hide kept for unit tests */
316         @Deprecated
317         public static final int FLAG_GET_PINNED = FLAG_MATCH_PINNED;
318 
319         /**
320          * Include manifest shortcuts in the result.
321          */
322         public static final int FLAG_MATCH_MANIFEST = 1 << 3;
323 
324         /** @hide kept for unit tests */
325         @Deprecated
326         public static final int FLAG_GET_MANIFEST = FLAG_MATCH_MANIFEST;
327 
328         /**
329          * Include all pinned shortcuts by any launchers, not just by the caller,
330          * in the result.
331          *
332          * <p>The caller must be the selected assistant app to use this flag, or have the system
333          * {@code ACCESS_SHORTCUTS} permission.
334          *
335          * <p>If you are the selected assistant app, and wishes to fetch all shortcuts that the
336          * user owns on the launcher (or by other launchers, in case the user has multiple), use
337          * {@link #FLAG_MATCH_PINNED_BY_ANY_LAUNCHER} instead.
338          *
339          * <p>If you're a regular launcher app (or any app that's not the selected assistant app)
340          * then this flag will be ignored.
341          */
342         public static final int FLAG_MATCH_PINNED_BY_ANY_LAUNCHER = 1 << 10;
343 
344         /**
345          * FLAG_MATCH_DYNAMIC | FLAG_MATCH_PINNED | FLAG_MATCH_MANIFEST
346          * @hide
347          */
348         public static final int FLAG_MATCH_ALL_KINDS =
349                 FLAG_MATCH_DYNAMIC | FLAG_MATCH_PINNED | FLAG_MATCH_MANIFEST;
350 
351         /**
352          * FLAG_MATCH_DYNAMIC | FLAG_MATCH_PINNED | FLAG_MATCH_MANIFEST | FLAG_MATCH_ALL_PINNED
353          * @hide
354          */
355         public static final int FLAG_MATCH_ALL_KINDS_WITH_ALL_PINNED =
356                 FLAG_MATCH_ALL_KINDS | FLAG_MATCH_PINNED_BY_ANY_LAUNCHER;
357 
358         /** @hide kept for unit tests */
359         @Deprecated
360         public static final int FLAG_GET_ALL_KINDS = FLAG_MATCH_ALL_KINDS;
361 
362         /**
363          * Requests "key" fields only.  See {@link ShortcutInfo#hasKeyFieldsOnly()}'s javadoc to
364          * see which fields fields "key".
365          * This allows quicker access to shortcut information in order to
366          * determine whether the caller's in-memory cache needs to be updated.
367          *
368          * <p>Typically, launcher applications cache all or most shortcut information
369          * in memory in order to show shortcuts without a delay.
370          *
371          * When a given launcher application wants to update its cache, such as when its process
372          * restarts, it can fetch shortcut information with this flag.
373          * The application can then check {@link ShortcutInfo#getLastChangedTimestamp()} for each
374          * shortcut, fetching a shortcut's non-key information only if that shortcut has been
375          * updated.
376          *
377          * @see ShortcutManager
378          */
379         public static final int FLAG_GET_KEY_FIELDS_ONLY = 1 << 2;
380 
381         /** @hide */
382         @IntDef(flag = true, prefix = { "FLAG_" }, value = {
383                 FLAG_MATCH_DYNAMIC,
384                 FLAG_MATCH_PINNED,
385                 FLAG_MATCH_MANIFEST,
386                 FLAG_GET_KEY_FIELDS_ONLY,
387                 FLAG_MATCH_MANIFEST,
388         })
389         @Retention(RetentionPolicy.SOURCE)
390         public @interface QueryFlags {}
391 
392         long mChangedSince;
393 
394         @Nullable
395         String mPackage;
396 
397         @Nullable
398         List<String> mShortcutIds;
399 
400         @Nullable
401         ComponentName mActivity;
402 
403         @QueryFlags
404         int mQueryFlags;
405 
ShortcutQuery()406         public ShortcutQuery() {
407         }
408 
409         /**
410          * If non-zero, returns only shortcuts that have been added or updated
411          * since the given timestamp, expressed in milliseconds since the Epoch&mdash;see
412          * {@link System#currentTimeMillis()}.
413          */
setChangedSince(long changedSince)414         public ShortcutQuery setChangedSince(long changedSince) {
415             mChangedSince = changedSince;
416             return this;
417         }
418 
419         /**
420          * If non-null, returns only shortcuts from the package.
421          */
setPackage(@ullable String packageName)422         public ShortcutQuery setPackage(@Nullable String packageName) {
423             mPackage = packageName;
424             return this;
425         }
426 
427         /**
428          * If non-null, return only the specified shortcuts by ID.  When setting this field,
429          * a package name must also be set with {@link #setPackage}.
430          */
setShortcutIds(@ullable List<String> shortcutIds)431         public ShortcutQuery setShortcutIds(@Nullable List<String> shortcutIds) {
432             mShortcutIds = shortcutIds;
433             return this;
434         }
435 
436         /**
437          * If non-null, returns only shortcuts associated with the activity; i.e.
438          * {@link ShortcutInfo}s whose {@link ShortcutInfo#getActivity()} are equal
439          * to {@code activity}.
440          */
setActivity(@ullable ComponentName activity)441         public ShortcutQuery setActivity(@Nullable ComponentName activity) {
442             mActivity = activity;
443             return this;
444         }
445 
446         /**
447          * Set query options.  At least one of the {@code MATCH} flags should be set.  Otherwise,
448          * no shortcuts will be returned.
449          *
450          * <ul>
451          *     <li>{@link #FLAG_MATCH_DYNAMIC}
452          *     <li>{@link #FLAG_MATCH_PINNED}
453          *     <li>{@link #FLAG_MATCH_MANIFEST}
454          *     <li>{@link #FLAG_GET_KEY_FIELDS_ONLY}
455          * </ul>
456          */
setQueryFlags(@ueryFlags int queryFlags)457         public ShortcutQuery setQueryFlags(@QueryFlags int queryFlags) {
458             mQueryFlags = queryFlags;
459             return this;
460         }
461     }
462 
463     /** @hide */
LauncherApps(Context context, ILauncherApps service)464     public LauncherApps(Context context, ILauncherApps service) {
465         mContext = context;
466         mService = service;
467         mPm = context.getPackageManager();
468         mUserManager = context.getSystemService(UserManager.class);
469     }
470 
471     /** @hide */
472     @TestApi
LauncherApps(Context context)473     public LauncherApps(Context context) {
474         this(context, ILauncherApps.Stub.asInterface(
475                 ServiceManager.getService(Context.LAUNCHER_APPS_SERVICE)));
476     }
477 
478     /**
479      * Show an error log on logcat, when the calling user is a managed profile, and the target
480      * user is different from the calling user, in order to help developers to detect it.
481      */
logErrorForInvalidProfileAccess(@onNull UserHandle target)482     private void logErrorForInvalidProfileAccess(@NonNull UserHandle target) {
483         if (UserHandle.myUserId() != target.getIdentifier() && mUserManager.isManagedProfile()) {
484             Log.w(TAG, "Accessing other profiles/users from managed profile is no longer allowed.");
485         }
486     }
487 
488     /**
489      * Return a list of profiles that the caller can access via the {@link LauncherApps} APIs.
490      *
491      * <p>If the caller is running on a managed profile, it'll return only the current profile.
492      * Otherwise it'll return the same list as {@link UserManager#getUserProfiles()} would.
493      */
getProfiles()494     public List<UserHandle> getProfiles() {
495         if (mUserManager.isManagedProfile()) {
496             // If it's a managed profile, only return the current profile.
497             final List result =  new ArrayList(1);
498             result.add(android.os.Process.myUserHandle());
499             return result;
500         } else {
501             return mUserManager.getUserProfiles();
502         }
503     }
504 
505     /**
506      * Retrieves a list of launchable activities that match {@link Intent#ACTION_MAIN} and
507      * {@link Intent#CATEGORY_LAUNCHER}, for a specified user. Result may include
508      * synthesized activities like app details Activity injected by system.
509      *
510      * @param packageName The specific package to query. If null, it checks all installed packages
511      *            in the profile.
512      * @param user The UserHandle of the profile.
513      * @return List of launchable activities. Can be an empty list but will not be null.
514      */
getActivityList(String packageName, UserHandle user)515     public List<LauncherActivityInfo> getActivityList(String packageName, UserHandle user) {
516         logErrorForInvalidProfileAccess(user);
517         try {
518             return convertToActivityList(mService.getLauncherActivities(mContext.getPackageName(),
519                     packageName, user), user);
520         } catch (RemoteException re) {
521             throw re.rethrowFromSystemServer();
522         }
523     }
524 
525     /**
526      * Returns the activity info for a given intent and user handle, if it resolves. Otherwise it
527      * returns null.
528      *
529      * @param intent The intent to find a match for.
530      * @param user The profile to look in for a match.
531      * @return An activity info object if there is a match.
532      */
resolveActivity(Intent intent, UserHandle user)533     public LauncherActivityInfo resolveActivity(Intent intent, UserHandle user) {
534         logErrorForInvalidProfileAccess(user);
535         try {
536             ActivityInfo ai = mService.resolveActivity(mContext.getPackageName(),
537                     intent.getComponent(), user);
538             if (ai != null) {
539                 LauncherActivityInfo info = new LauncherActivityInfo(mContext, ai, user);
540                 return info;
541             }
542         } catch (RemoteException re) {
543             throw re.rethrowFromSystemServer();
544         }
545         return null;
546     }
547 
548     /**
549      * Starts a Main activity in the specified profile.
550      *
551      * @param component The ComponentName of the activity to launch
552      * @param user The UserHandle of the profile
553      * @param sourceBounds The Rect containing the source bounds of the clicked icon
554      * @param opts Options to pass to startActivity
555      */
startMainActivity(ComponentName component, UserHandle user, Rect sourceBounds, Bundle opts)556     public void startMainActivity(ComponentName component, UserHandle user, Rect sourceBounds,
557             Bundle opts) {
558         logErrorForInvalidProfileAccess(user);
559         if (DEBUG) {
560             Log.i(TAG, "StartMainActivity " + component + " " + user.getIdentifier());
561         }
562         try {
563             mService.startActivityAsUser(mContext.getIApplicationThread(),
564                     mContext.getPackageName(),
565                     component, sourceBounds, opts, user);
566         } catch (RemoteException re) {
567             throw re.rethrowFromSystemServer();
568         }
569     }
570 
571     /**
572      * Starts an activity to show the details of the specified session.
573      *
574      * @param sessionInfo The SessionInfo of the session
575      * @param sourceBounds The Rect containing the source bounds of the clicked icon
576      * @param opts Options to pass to startActivity
577      */
startPackageInstallerSessionDetailsActivity(@onNull SessionInfo sessionInfo, @Nullable Rect sourceBounds, @Nullable Bundle opts)578     public void startPackageInstallerSessionDetailsActivity(@NonNull SessionInfo sessionInfo,
579             @Nullable Rect sourceBounds, @Nullable Bundle opts) {
580         try {
581             mService.startSessionDetailsActivityAsUser(mContext.getIApplicationThread(),
582                     mContext.getPackageName(), sessionInfo, sourceBounds, opts,
583                     sessionInfo.getUser());
584         } catch (RemoteException re) {
585             throw re.rethrowFromSystemServer();
586         }
587     }
588 
589     /**
590      * Starts the settings activity to show the application details for a
591      * package in the specified profile.
592      *
593      * @param component The ComponentName of the package to launch settings for.
594      * @param user The UserHandle of the profile
595      * @param sourceBounds The Rect containing the source bounds of the clicked icon
596      * @param opts Options to pass to startActivity
597      */
startAppDetailsActivity(ComponentName component, UserHandle user, Rect sourceBounds, Bundle opts)598     public void startAppDetailsActivity(ComponentName component, UserHandle user,
599             Rect sourceBounds, Bundle opts) {
600         logErrorForInvalidProfileAccess(user);
601         try {
602             mService.showAppDetailsAsUser(mContext.getIApplicationThread(),
603                     mContext.getPackageName(),
604                     component, sourceBounds, opts, user);
605         } catch (RemoteException re) {
606             throw re.rethrowFromSystemServer();
607         }
608     }
609 
610     /**
611      * Retrieves a list of config activities for creating {@link ShortcutInfo}.
612      *
613      * @param packageName The specific package to query. If null, it checks all installed packages
614      *            in the profile.
615      * @param user The UserHandle of the profile.
616      * @return List of config activities. Can be an empty list but will not be null.
617      *
618      * @see Intent#ACTION_CREATE_SHORTCUT
619      * @see #getShortcutConfigActivityIntent(LauncherActivityInfo)
620      */
getShortcutConfigActivityList(@ullable String packageName, @NonNull UserHandle user)621     public List<LauncherActivityInfo> getShortcutConfigActivityList(@Nullable String packageName,
622             @NonNull UserHandle user) {
623         logErrorForInvalidProfileAccess(user);
624         try {
625             return convertToActivityList(mService.getShortcutConfigActivities(
626                     mContext.getPackageName(), packageName, user),
627                     user);
628         } catch (RemoteException re) {
629             throw re.rethrowFromSystemServer();
630         }
631     }
632 
convertToActivityList( @ullable ParceledListSlice<ResolveInfo> activities, UserHandle user)633     private List<LauncherActivityInfo> convertToActivityList(
634             @Nullable ParceledListSlice<ResolveInfo> activities, UserHandle user) {
635         if (activities == null) {
636             return Collections.EMPTY_LIST;
637         }
638         ArrayList<LauncherActivityInfo> lais = new ArrayList<>();
639         for (ResolveInfo ri : activities.getList()) {
640             LauncherActivityInfo lai = new LauncherActivityInfo(mContext, ri.activityInfo, user);
641             if (DEBUG) {
642                 Log.v(TAG, "Returning activity for profile " + user + " : "
643                         + lai.getComponentName());
644             }
645             lais.add(lai);
646         }
647         return lais;
648     }
649 
650     /**
651      * Returns an intent sender which can be used to start the configure activity for creating
652      * custom shortcuts. Use this method if the provider is in another profile as you are not
653      * allowed to start an activity in another profile.
654      *
655      * <p>The caller should receive {@link PinItemRequest} in onActivityResult on
656      * {@link android.app.Activity#RESULT_OK}.
657      *
658      * <p>Callers must be allowed to access the shortcut information, as defined in {@link
659      * #hasShortcutHostPermission()}.
660      *
661      * @param info a configuration activity returned by {@link #getShortcutConfigActivityList}
662      *
663      * @throws IllegalStateException when the user is locked or not running.
664      * @throws SecurityException if {@link #hasShortcutHostPermission()} is false.
665      *
666      * @see #getPinItemRequest(Intent)
667      * @see Intent#ACTION_CREATE_SHORTCUT
668      * @see android.app.Activity#startIntentSenderForResult
669      */
670     @Nullable
getShortcutConfigActivityIntent(@onNull LauncherActivityInfo info)671     public IntentSender getShortcutConfigActivityIntent(@NonNull LauncherActivityInfo info) {
672         try {
673             return mService.getShortcutConfigActivityIntent(
674                     mContext.getPackageName(), info.getComponentName(), info.getUser());
675         } catch (RemoteException re) {
676             throw re.rethrowFromSystemServer();
677         }
678     }
679 
680     /**
681      * Checks if the package is installed and enabled for a profile.
682      *
683      * @param packageName The package to check.
684      * @param user The UserHandle of the profile.
685      *
686      * @return true if the package exists and is enabled.
687      */
isPackageEnabled(String packageName, UserHandle user)688     public boolean isPackageEnabled(String packageName, UserHandle user) {
689         logErrorForInvalidProfileAccess(user);
690         try {
691             return mService.isPackageEnabled(mContext.getPackageName(), packageName, user);
692         } catch (RemoteException re) {
693             throw re.rethrowFromSystemServer();
694         }
695     }
696 
697     /**
698      * Gets the launcher extras supplied to the system when the given package was suspended via
699      * {@code PackageManager#setPackagesSuspended(String[], boolean, PersistableBundle,
700      * PersistableBundle, String)}.
701      *
702      * <p>The contents of this {@link Bundle} are supposed to be a contract between the suspending
703      * app and the launcher.
704      *
705      * <p>Note: This just returns whatever extras were provided to the system, <em>which might
706      * even be {@code null}.</em>
707      *
708      * @param packageName The package for which to fetch the launcher extras.
709      * @param user The {@link UserHandle} of the profile.
710      * @return A {@link Bundle} of launcher extras. Or {@code null} if the package is not currently
711      *         suspended.
712      *
713      * @see Callback#onPackagesSuspended(String[], UserHandle, Bundle)
714      * @see PackageManager#isPackageSuspended()
715      */
getSuspendedPackageLauncherExtras(String packageName, UserHandle user)716     public @Nullable Bundle getSuspendedPackageLauncherExtras(String packageName, UserHandle user) {
717         logErrorForInvalidProfileAccess(user);
718         try {
719             return mService.getSuspendedPackageLauncherExtras(packageName, user);
720         } catch (RemoteException re) {
721             throw re.rethrowFromSystemServer();
722         }
723     }
724 
725     /**
726      * Returns whether a package should be hidden from suggestions to the user. Currently, this
727      * could be done because the package was marked as distracting to the user via
728      * {@code PackageManager.setDistractingPackageRestrictions(String[], int)}.
729      *
730      * @param packageName The package for which to check.
731      * @param user the {@link UserHandle} of the profile.
732      * @return
733      */
shouldHideFromSuggestions(@onNull String packageName, @NonNull UserHandle user)734     public boolean shouldHideFromSuggestions(@NonNull String packageName,
735             @NonNull UserHandle user) {
736         Preconditions.checkNotNull(packageName, "packageName");
737         Preconditions.checkNotNull(user, "user");
738         try {
739             return mService.shouldHideFromSuggestions(packageName, user);
740         } catch (RemoteException re) {
741             throw re.rethrowFromSystemServer();
742         }
743     }
744 
745     /**
746      * Returns {@link ApplicationInfo} about an application installed for a specific user profile.
747      *
748      * @param packageName The package name of the application
749      * @param flags Additional option flags {@link PackageManager#getApplicationInfo}
750      * @param user The UserHandle of the profile.
751      *
752      * @return {@link ApplicationInfo} containing information about the package. Returns
753      *         {@code null} if the package isn't installed for the given profile, or the profile
754      *         isn't enabled.
755      */
getApplicationInfo(@onNull String packageName, @ApplicationInfoFlags int flags, @NonNull UserHandle user)756     public ApplicationInfo getApplicationInfo(@NonNull String packageName,
757             @ApplicationInfoFlags int flags, @NonNull UserHandle user)
758             throws PackageManager.NameNotFoundException {
759         Preconditions.checkNotNull(packageName, "packageName");
760         Preconditions.checkNotNull(user, "user");
761         logErrorForInvalidProfileAccess(user);
762         try {
763             final ApplicationInfo ai = mService
764                     .getApplicationInfo(mContext.getPackageName(), packageName, flags, user);
765             if (ai == null) {
766                 throw new NameNotFoundException("Package " + packageName + " not found for user "
767                         + user.getIdentifier());
768             }
769             return ai;
770         } catch (RemoteException re) {
771             throw re.rethrowFromSystemServer();
772         }
773     }
774 
775     /**
776      * Returns an object describing the app usage limit for the given package.
777      * If there are multiple limits that apply to the package, the one with the smallest
778      * time remaining will be returned.
779      *
780      * @param packageName name of the package whose app usage limit will be returned
781      * @param user the user of the package
782      *
783      * @return an {@link AppUsageLimit} object describing the app time limit containing
784      * the given package with the smallest time remaining, or {@code null} if none exist.
785      * @throws SecurityException when the caller is not the recents app.
786      * @hide
787      */
788     @Nullable
789     @SystemApi
getAppUsageLimit(@onNull String packageName, @NonNull UserHandle user)790     public LauncherApps.AppUsageLimit getAppUsageLimit(@NonNull String packageName,
791             @NonNull UserHandle user) {
792         try {
793             return mService.getAppUsageLimit(mContext.getPackageName(), packageName, user);
794         } catch (RemoteException re) {
795             throw re.rethrowFromSystemServer();
796         }
797     }
798 
799     /**
800      * Checks if the activity exists and it enabled for a profile.
801      *
802      * <p>The activity may still not be exported, in which case {@link #startMainActivity} will
803      * throw a {@link SecurityException} unless the caller has the same UID as the target app's.
804      *
805      * @param component The activity to check.
806      * @param user The UserHandle of the profile.
807      *
808      * @return true if the activity exists and is enabled.
809      */
isActivityEnabled(ComponentName component, UserHandle user)810     public boolean isActivityEnabled(ComponentName component, UserHandle user) {
811         logErrorForInvalidProfileAccess(user);
812         try {
813             return mService.isActivityEnabled(mContext.getPackageName(), component, user);
814         } catch (RemoteException re) {
815             throw re.rethrowFromSystemServer();
816         }
817     }
818 
819     /**
820      * Returns whether the caller can access the shortcut information.  Access is currently
821      * available to:
822      *
823      * <ul>
824      *     <li>The current launcher (or default launcher if there is no set current launcher).</li>
825      *     <li>The currently active voice interaction service.</li>
826      * </ul>
827      *
828      * <p>Note when this method returns {@code false}, it may be a temporary situation because
829      * the user is trying a new launcher application.  The user may decide to change the default
830      * launcher back to the calling application again, so even if a launcher application loses
831      * this permission, it does <b>not</b> have to purge pinned shortcut information.
832      * If the calling launcher application contains pinned shortcuts, they will still work,
833      * even though the caller no longer has the shortcut host permission.
834      *
835      * @throws IllegalStateException when the user is locked.
836      *
837      * @see ShortcutManager
838      */
hasShortcutHostPermission()839     public boolean hasShortcutHostPermission() {
840         try {
841             return mService.hasShortcutHostPermission(mContext.getPackageName());
842         } catch (RemoteException re) {
843             throw re.rethrowFromSystemServer();
844         }
845     }
846 
maybeUpdateDisabledMessage(List<ShortcutInfo> shortcuts)847     private List<ShortcutInfo> maybeUpdateDisabledMessage(List<ShortcutInfo> shortcuts) {
848         if (shortcuts == null) {
849             return null;
850         }
851         for (int i = shortcuts.size() - 1; i >= 0; i--) {
852             final ShortcutInfo si = shortcuts.get(i);
853             final String message = ShortcutInfo.getDisabledReasonForRestoreIssue(mContext,
854                     si.getDisabledReason());
855             if (message != null) {
856                 si.setDisabledMessage(message);
857             }
858         }
859         return shortcuts;
860     }
861 
862     /**
863      * Returns {@link ShortcutInfo}s that match {@code query}.
864      *
865      * <p>Callers must be allowed to access the shortcut information, as defined in {@link
866      * #hasShortcutHostPermission()}.
867      *
868      * @param query result includes shortcuts matching this query.
869      * @param user The UserHandle of the profile.
870      *
871      * @return the IDs of {@link ShortcutInfo}s that match the query.
872      * @throws IllegalStateException when the user is locked, or when the {@code user} user
873      * is locked or not running.
874      *
875      * @see ShortcutManager
876      */
877     @Nullable
getShortcuts(@onNull ShortcutQuery query, @NonNull UserHandle user)878     public List<ShortcutInfo> getShortcuts(@NonNull ShortcutQuery query,
879             @NonNull UserHandle user) {
880         logErrorForInvalidProfileAccess(user);
881         try {
882             // Note this is the only case we need to update the disabled message for shortcuts
883             // that weren't restored.
884             // The restore problem messages are only shown by the user, and publishers will never
885             // see them. The only other API that the launcher gets shortcuts is the shortcut
886             // changed callback, but that only returns shortcuts with the "key" information, so
887             // that won't return disabled message.
888             return maybeUpdateDisabledMessage(mService.getShortcuts(mContext.getPackageName(),
889                     query.mChangedSince, query.mPackage, query.mShortcutIds, query.mActivity,
890                     query.mQueryFlags, user)
891                     .getList());
892         } catch (RemoteException e) {
893             throw e.rethrowFromSystemServer();
894         }
895     }
896 
897     /**
898      * @hide // No longer used.  Use getShortcuts() instead.  Kept for unit tests.
899      */
900     @Nullable
901     @Deprecated
getShortcutInfo(@onNull String packageName, @NonNull List<String> ids, @NonNull UserHandle user)902     public List<ShortcutInfo> getShortcutInfo(@NonNull String packageName,
903             @NonNull List<String> ids, @NonNull UserHandle user) {
904         final ShortcutQuery q = new ShortcutQuery();
905         q.setPackage(packageName);
906         q.setShortcutIds(ids);
907         q.setQueryFlags(ShortcutQuery.FLAG_GET_ALL_KINDS);
908         return getShortcuts(q, user);
909     }
910 
911     /**
912      * Pin shortcuts on a package.
913      *
914      * <p>This API is <b>NOT</b> cumulative; this will replace all pinned shortcuts for the package.
915      * However, different launchers may have different set of pinned shortcuts.
916      *
917      * <p>The calling launcher application must be allowed to access the shortcut information,
918      * as defined in {@link #hasShortcutHostPermission()}.
919      *
920      * @param packageName The target package name.
921      * @param shortcutIds The IDs of the shortcut to be pinned.
922      * @param user The UserHandle of the profile.
923      * @throws IllegalStateException when the user is locked, or when the {@code user} user
924      * is locked or not running.
925      *
926      * @see ShortcutManager
927      */
pinShortcuts(@onNull String packageName, @NonNull List<String> shortcutIds, @NonNull UserHandle user)928     public void pinShortcuts(@NonNull String packageName, @NonNull List<String> shortcutIds,
929             @NonNull UserHandle user) {
930         logErrorForInvalidProfileAccess(user);
931         try {
932             mService.pinShortcuts(mContext.getPackageName(), packageName, shortcutIds, user);
933         } catch (RemoteException e) {
934             throw e.rethrowFromSystemServer();
935         }
936     }
937 
938     /**
939      * @hide kept for testing.
940      */
941     @Deprecated
getShortcutIconResId(@onNull ShortcutInfo shortcut)942     public int getShortcutIconResId(@NonNull ShortcutInfo shortcut) {
943         return shortcut.getIconResourceId();
944     }
945 
946     /**
947      * @hide kept for testing.
948      */
949     @Deprecated
getShortcutIconResId(@onNull String packageName, @NonNull String shortcutId, @NonNull UserHandle user)950     public int getShortcutIconResId(@NonNull String packageName, @NonNull String shortcutId,
951             @NonNull UserHandle user) {
952         final ShortcutQuery q = new ShortcutQuery();
953         q.setPackage(packageName);
954         q.setShortcutIds(Arrays.asList(shortcutId));
955         q.setQueryFlags(ShortcutQuery.FLAG_GET_ALL_KINDS);
956         final List<ShortcutInfo> shortcuts = getShortcuts(q, user);
957 
958         return shortcuts.size() > 0 ? shortcuts.get(0).getIconResourceId() : 0;
959     }
960 
961     /**
962      * @hide internal/unit tests only
963      */
getShortcutIconFd( @onNull ShortcutInfo shortcut)964     public ParcelFileDescriptor getShortcutIconFd(
965             @NonNull ShortcutInfo shortcut) {
966         return getShortcutIconFd(shortcut.getPackage(), shortcut.getId(),
967                 shortcut.getUserId());
968     }
969 
970     /**
971      * @hide internal/unit tests only
972      */
getShortcutIconFd( @onNull String packageName, @NonNull String shortcutId, @NonNull UserHandle user)973     public ParcelFileDescriptor getShortcutIconFd(
974             @NonNull String packageName, @NonNull String shortcutId, @NonNull UserHandle user) {
975         return getShortcutIconFd(packageName, shortcutId, user.getIdentifier());
976     }
977 
getShortcutIconFd( @onNull String packageName, @NonNull String shortcutId, int userId)978     private ParcelFileDescriptor getShortcutIconFd(
979             @NonNull String packageName, @NonNull String shortcutId, int userId) {
980         try {
981             return mService.getShortcutIconFd(mContext.getPackageName(),
982                     packageName, shortcutId, userId);
983         } catch (RemoteException e) {
984             throw e.rethrowFromSystemServer();
985         }
986     }
987 
988     /**
989      * Returns the icon for this shortcut, without any badging for the profile.
990      *
991      * <p>The calling launcher application must be allowed to access the shortcut information,
992      * as defined in {@link #hasShortcutHostPermission()}.
993      *
994      * @param density The preferred density of the icon, zero for default density. Use
995      * density DPI values from {@link DisplayMetrics}.
996      *
997      * @return The drawable associated with the shortcut.
998      * @throws IllegalStateException when the user is locked, or when the {@code user} user
999      * is locked or not running.
1000      *
1001      * @see ShortcutManager
1002      * @see #getShortcutBadgedIconDrawable(ShortcutInfo, int)
1003      * @see DisplayMetrics
1004      */
getShortcutIconDrawable(@onNull ShortcutInfo shortcut, int density)1005     public Drawable getShortcutIconDrawable(@NonNull ShortcutInfo shortcut, int density) {
1006         if (shortcut.hasIconFile()) {
1007             final ParcelFileDescriptor pfd = getShortcutIconFd(shortcut);
1008             if (pfd == null) {
1009                 return null;
1010             }
1011             try {
1012                 final Bitmap bmp = BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
1013                 if (bmp != null) {
1014                     BitmapDrawable dr = new BitmapDrawable(mContext.getResources(), bmp);
1015                     if (shortcut.hasAdaptiveBitmap()) {
1016                         return new AdaptiveIconDrawable(null, dr);
1017                     } else {
1018                         return dr;
1019                     }
1020                 }
1021                 return null;
1022             } finally {
1023                 try {
1024                     pfd.close();
1025                 } catch (IOException ignore) {
1026                 }
1027             }
1028         } else if (shortcut.hasIconResource()) {
1029             return loadDrawableResourceFromPackage(shortcut.getPackage(),
1030                     shortcut.getIconResourceId(), shortcut.getUserHandle(), density);
1031         } else if (shortcut.getIcon() != null) {
1032             // This happens if a shortcut is pending-approval.
1033             final Icon icon = shortcut.getIcon();
1034             switch (icon.getType()) {
1035                 case Icon.TYPE_RESOURCE: {
1036                     return loadDrawableResourceFromPackage(shortcut.getPackage(),
1037                             icon.getResId(), shortcut.getUserHandle(), density);
1038                 }
1039                 case Icon.TYPE_BITMAP:
1040                 case Icon.TYPE_ADAPTIVE_BITMAP: {
1041                     return icon.loadDrawable(mContext);
1042                 }
1043                 default:
1044                     return null; // Shouldn't happen though.
1045             }
1046         } else {
1047             return null; // Has no icon.
1048         }
1049     }
1050 
loadDrawableResourceFromPackage(String packageName, int resId, UserHandle user, int density)1051     private Drawable loadDrawableResourceFromPackage(String packageName, int resId,
1052             UserHandle user, int density) {
1053         try {
1054             if (resId == 0) {
1055                 return null; // Shouldn't happen but just in case.
1056             }
1057             final ApplicationInfo ai = getApplicationInfo(packageName, /* flags =*/ 0, user);
1058             final Resources res = mContext.getPackageManager().getResourcesForApplication(ai);
1059             return res.getDrawableForDensity(resId, density);
1060         } catch (NameNotFoundException | Resources.NotFoundException e) {
1061             return null;
1062         }
1063     }
1064 
1065     /**
1066      * Returns the shortcut icon with badging appropriate for the profile.
1067      *
1068      * <p>The calling launcher application must be allowed to access the shortcut information,
1069      * as defined in {@link #hasShortcutHostPermission()}.
1070      *
1071      * @param density Optional density for the icon, or 0 to use the default density. Use
1072      * @return A badged icon for the shortcut.
1073      * @throws IllegalStateException when the user is locked, or when the {@code user} user
1074      * is locked or not running.
1075      *
1076      * @see ShortcutManager
1077      * @see #getShortcutIconDrawable(ShortcutInfo, int)
1078      * @see DisplayMetrics
1079      */
getShortcutBadgedIconDrawable(ShortcutInfo shortcut, int density)1080     public Drawable getShortcutBadgedIconDrawable(ShortcutInfo shortcut, int density) {
1081         final Drawable originalIcon = getShortcutIconDrawable(shortcut, density);
1082 
1083         return (originalIcon == null) ? null : mContext.getPackageManager().getUserBadgedIcon(
1084                 originalIcon, shortcut.getUserHandle());
1085     }
1086 
1087     /**
1088      * Starts a shortcut.
1089      *
1090      * <p>The calling launcher application must be allowed to access the shortcut information,
1091      * as defined in {@link #hasShortcutHostPermission()}.
1092      *
1093      * @param packageName The target shortcut package name.
1094      * @param shortcutId The target shortcut ID.
1095      * @param sourceBounds The Rect containing the source bounds of the clicked icon.
1096      * @param startActivityOptions Options to pass to startActivity.
1097      * @param user The UserHandle of the profile.
1098      * @throws IllegalStateException when the user is locked, or when the {@code user} user
1099      * is locked or not running.
1100      *
1101      * @throws android.content.ActivityNotFoundException failed to start shortcut. (e.g.
1102      * the shortcut no longer exists, is disabled, the intent receiver activity doesn't exist, etc)
1103      */
startShortcut(@onNull String packageName, @NonNull String shortcutId, @Nullable Rect sourceBounds, @Nullable Bundle startActivityOptions, @NonNull UserHandle user)1104     public void startShortcut(@NonNull String packageName, @NonNull String shortcutId,
1105             @Nullable Rect sourceBounds, @Nullable Bundle startActivityOptions,
1106             @NonNull UserHandle user) {
1107         logErrorForInvalidProfileAccess(user);
1108 
1109         startShortcut(packageName, shortcutId, sourceBounds, startActivityOptions,
1110                 user.getIdentifier());
1111     }
1112 
1113     /**
1114      * Launches a shortcut.
1115      *
1116      * <p>The calling launcher application must be allowed to access the shortcut information,
1117      * as defined in {@link #hasShortcutHostPermission()}.
1118      *
1119      * @param shortcut The target shortcut.
1120      * @param sourceBounds The Rect containing the source bounds of the clicked icon.
1121      * @param startActivityOptions Options to pass to startActivity.
1122      * @throws IllegalStateException when the user is locked, or when the {@code user} user
1123      * is locked or not running.
1124      *
1125      * @throws android.content.ActivityNotFoundException failed to start shortcut. (e.g.
1126      * the shortcut no longer exists, is disabled, the intent receiver activity doesn't exist, etc)
1127      */
startShortcut(@onNull ShortcutInfo shortcut, @Nullable Rect sourceBounds, @Nullable Bundle startActivityOptions)1128     public void startShortcut(@NonNull ShortcutInfo shortcut,
1129             @Nullable Rect sourceBounds, @Nullable Bundle startActivityOptions) {
1130         startShortcut(shortcut.getPackage(), shortcut.getId(),
1131                 sourceBounds, startActivityOptions,
1132                 shortcut.getUserId());
1133     }
1134 
1135     @UnsupportedAppUsage
startShortcut(@onNull String packageName, @NonNull String shortcutId, @Nullable Rect sourceBounds, @Nullable Bundle startActivityOptions, int userId)1136     private void startShortcut(@NonNull String packageName, @NonNull String shortcutId,
1137             @Nullable Rect sourceBounds, @Nullable Bundle startActivityOptions,
1138             int userId) {
1139         try {
1140             final boolean success =
1141                     mService.startShortcut(mContext.getPackageName(), packageName, shortcutId,
1142                     sourceBounds, startActivityOptions, userId);
1143             if (!success) {
1144                 throw new ActivityNotFoundException("Shortcut could not be started");
1145             }
1146         } catch (RemoteException e) {
1147             throw e.rethrowFromSystemServer();
1148         }
1149     }
1150 
1151     /**
1152      * Registers a callback for changes to packages in this user and managed profiles.
1153      *
1154      * @param callback The callback to register.
1155      */
registerCallback(Callback callback)1156     public void registerCallback(Callback callback) {
1157         registerCallback(callback, null);
1158     }
1159 
1160     /**
1161      * Registers a callback for changes to packages in this user and managed profiles.
1162      *
1163      * @param callback The callback to register.
1164      * @param handler that should be used to post callbacks on, may be null.
1165      */
registerCallback(Callback callback, Handler handler)1166     public void registerCallback(Callback callback, Handler handler) {
1167         synchronized (this) {
1168             if (callback != null && findCallbackLocked(callback) < 0) {
1169                 boolean addedFirstCallback = mCallbacks.size() == 0;
1170                 addCallbackLocked(callback, handler);
1171                 if (addedFirstCallback) {
1172                     try {
1173                         mService.addOnAppsChangedListener(mContext.getPackageName(),
1174                                 mAppsChangedListener);
1175                     } catch (RemoteException re) {
1176                         throw re.rethrowFromSystemServer();
1177                     }
1178                 }
1179             }
1180         }
1181     }
1182 
1183     /**
1184      * Unregisters a callback that was previously registered.
1185      *
1186      * @param callback The callback to unregister.
1187      * @see #registerCallback(Callback)
1188      */
unregisterCallback(Callback callback)1189     public void unregisterCallback(Callback callback) {
1190         synchronized (this) {
1191             removeCallbackLocked(callback);
1192             if (mCallbacks.size() == 0) {
1193                 try {
1194                     mService.removeOnAppsChangedListener(mAppsChangedListener);
1195                 } catch (RemoteException re) {
1196                     throw re.rethrowFromSystemServer();
1197                 }
1198             }
1199         }
1200     }
1201 
1202     /** @return position in mCallbacks for callback or -1 if not present. */
findCallbackLocked(Callback callback)1203     private int findCallbackLocked(Callback callback) {
1204         if (callback == null) {
1205             throw new IllegalArgumentException("Callback cannot be null");
1206         }
1207         final int size = mCallbacks.size();
1208         for (int i = 0; i < size; ++i) {
1209             if (mCallbacks.get(i).mCallback == callback) {
1210                 return i;
1211             }
1212         }
1213         return -1;
1214     }
1215 
removeCallbackLocked(Callback callback)1216     private void removeCallbackLocked(Callback callback) {
1217         int pos = findCallbackLocked(callback);
1218         if (pos >= 0) {
1219             mCallbacks.remove(pos);
1220         }
1221     }
1222 
addCallbackLocked(Callback callback, Handler handler)1223     private void addCallbackLocked(Callback callback, Handler handler) {
1224         // Remove if already present.
1225         removeCallbackLocked(callback);
1226         if (handler == null) {
1227             handler = new Handler();
1228         }
1229         CallbackMessageHandler toAdd = new CallbackMessageHandler(handler.getLooper(), callback);
1230         mCallbacks.add(toAdd);
1231     }
1232 
1233     private IOnAppsChangedListener.Stub mAppsChangedListener = new IOnAppsChangedListener.Stub() {
1234 
1235         @Override
1236         public void onPackageRemoved(UserHandle user, String packageName)
1237                 throws RemoteException {
1238             if (DEBUG) {
1239                 Log.d(TAG, "onPackageRemoved " + user.getIdentifier() + "," + packageName);
1240             }
1241             synchronized (LauncherApps.this) {
1242                 for (CallbackMessageHandler callback : mCallbacks) {
1243                     callback.postOnPackageRemoved(packageName, user);
1244                 }
1245             }
1246         }
1247 
1248         @Override
1249         public void onPackageChanged(UserHandle user, String packageName) throws RemoteException {
1250             if (DEBUG) {
1251                 Log.d(TAG, "onPackageChanged " + user.getIdentifier() + "," + packageName);
1252             }
1253             synchronized (LauncherApps.this) {
1254                 for (CallbackMessageHandler callback : mCallbacks) {
1255                     callback.postOnPackageChanged(packageName, user);
1256                 }
1257             }
1258         }
1259 
1260         @Override
1261         public void onPackageAdded(UserHandle user, String packageName) throws RemoteException {
1262             if (DEBUG) {
1263                 Log.d(TAG, "onPackageAdded " + user.getIdentifier() + "," + packageName);
1264             }
1265             synchronized (LauncherApps.this) {
1266                 for (CallbackMessageHandler callback : mCallbacks) {
1267                     callback.postOnPackageAdded(packageName, user);
1268                 }
1269             }
1270         }
1271 
1272         @Override
1273         public void onPackagesAvailable(UserHandle user, String[] packageNames, boolean replacing)
1274                 throws RemoteException {
1275             if (DEBUG) {
1276                 Log.d(TAG, "onPackagesAvailable " + user.getIdentifier() + "," + packageNames);
1277             }
1278             synchronized (LauncherApps.this) {
1279                 for (CallbackMessageHandler callback : mCallbacks) {
1280                     callback.postOnPackagesAvailable(packageNames, user, replacing);
1281                 }
1282             }
1283         }
1284 
1285         @Override
1286         public void onPackagesUnavailable(UserHandle user, String[] packageNames, boolean replacing)
1287                 throws RemoteException {
1288             if (DEBUG) {
1289                 Log.d(TAG, "onPackagesUnavailable " + user.getIdentifier() + "," + packageNames);
1290             }
1291             synchronized (LauncherApps.this) {
1292                 for (CallbackMessageHandler callback : mCallbacks) {
1293                     callback.postOnPackagesUnavailable(packageNames, user, replacing);
1294                 }
1295             }
1296         }
1297 
1298         @Override
1299         public void onPackagesSuspended(UserHandle user, String[] packageNames,
1300                 Bundle launcherExtras)
1301                 throws RemoteException {
1302             if (DEBUG) {
1303                 Log.d(TAG, "onPackagesSuspended " + user.getIdentifier() + "," + packageNames);
1304             }
1305             synchronized (LauncherApps.this) {
1306                 for (CallbackMessageHandler callback : mCallbacks) {
1307                     callback.postOnPackagesSuspended(packageNames, launcherExtras, user);
1308                 }
1309             }
1310         }
1311 
1312         @Override
1313         public void onPackagesUnsuspended(UserHandle user, String[] packageNames)
1314                 throws RemoteException {
1315             if (DEBUG) {
1316                 Log.d(TAG, "onPackagesUnsuspended " + user.getIdentifier() + "," + packageNames);
1317             }
1318             synchronized (LauncherApps.this) {
1319                 for (CallbackMessageHandler callback : mCallbacks) {
1320                     callback.postOnPackagesUnsuspended(packageNames, user);
1321                 }
1322             }
1323         }
1324 
1325         @Override
1326         public void onShortcutChanged(UserHandle user, String packageName,
1327                 ParceledListSlice shortcuts) {
1328             if (DEBUG) {
1329                 Log.d(TAG, "onShortcutChanged " + user.getIdentifier() + "," + packageName);
1330             }
1331             final List<ShortcutInfo> list = shortcuts.getList();
1332             synchronized (LauncherApps.this) {
1333                 for (CallbackMessageHandler callback : mCallbacks) {
1334                     callback.postOnShortcutChanged(packageName, user, list);
1335                 }
1336             }
1337         }
1338     };
1339 
1340     private static class CallbackMessageHandler extends Handler {
1341         private static final int MSG_ADDED = 1;
1342         private static final int MSG_REMOVED = 2;
1343         private static final int MSG_CHANGED = 3;
1344         private static final int MSG_AVAILABLE = 4;
1345         private static final int MSG_UNAVAILABLE = 5;
1346         private static final int MSG_SUSPENDED = 6;
1347         private static final int MSG_UNSUSPENDED = 7;
1348         private static final int MSG_SHORTCUT_CHANGED = 8;
1349 
1350         private LauncherApps.Callback mCallback;
1351 
1352         private static class CallbackInfo {
1353             String[] packageNames;
1354             String packageName;
1355             Bundle launcherExtras;
1356             boolean replacing;
1357             UserHandle user;
1358             List<ShortcutInfo> shortcuts;
1359         }
1360 
CallbackMessageHandler(Looper looper, LauncherApps.Callback callback)1361         public CallbackMessageHandler(Looper looper, LauncherApps.Callback callback) {
1362             super(looper, null, true);
1363             mCallback = callback;
1364         }
1365 
1366         @Override
handleMessage(Message msg)1367         public void handleMessage(Message msg) {
1368             if (mCallback == null || !(msg.obj instanceof CallbackInfo)) {
1369                 return;
1370             }
1371             CallbackInfo info = (CallbackInfo) msg.obj;
1372             switch (msg.what) {
1373                 case MSG_ADDED:
1374                     mCallback.onPackageAdded(info.packageName, info.user);
1375                     break;
1376                 case MSG_REMOVED:
1377                     mCallback.onPackageRemoved(info.packageName, info.user);
1378                     break;
1379                 case MSG_CHANGED:
1380                     mCallback.onPackageChanged(info.packageName, info.user);
1381                     break;
1382                 case MSG_AVAILABLE:
1383                     mCallback.onPackagesAvailable(info.packageNames, info.user, info.replacing);
1384                     break;
1385                 case MSG_UNAVAILABLE:
1386                     mCallback.onPackagesUnavailable(info.packageNames, info.user, info.replacing);
1387                     break;
1388                 case MSG_SUSPENDED:
1389                     mCallback.onPackagesSuspended(info.packageNames, info.user, info.launcherExtras
1390                     );
1391                     break;
1392                 case MSG_UNSUSPENDED:
1393                     mCallback.onPackagesUnsuspended(info.packageNames, info.user);
1394                     break;
1395                 case MSG_SHORTCUT_CHANGED:
1396                     mCallback.onShortcutsChanged(info.packageName, info.shortcuts, info.user);
1397                     break;
1398             }
1399         }
1400 
postOnPackageAdded(String packageName, UserHandle user)1401         public void postOnPackageAdded(String packageName, UserHandle user) {
1402             CallbackInfo info = new CallbackInfo();
1403             info.packageName = packageName;
1404             info.user = user;
1405             obtainMessage(MSG_ADDED, info).sendToTarget();
1406         }
1407 
postOnPackageRemoved(String packageName, UserHandle user)1408         public void postOnPackageRemoved(String packageName, UserHandle user) {
1409             CallbackInfo info = new CallbackInfo();
1410             info.packageName = packageName;
1411             info.user = user;
1412             obtainMessage(MSG_REMOVED, info).sendToTarget();
1413         }
1414 
postOnPackageChanged(String packageName, UserHandle user)1415         public void postOnPackageChanged(String packageName, UserHandle user) {
1416             CallbackInfo info = new CallbackInfo();
1417             info.packageName = packageName;
1418             info.user = user;
1419             obtainMessage(MSG_CHANGED, info).sendToTarget();
1420         }
1421 
postOnPackagesAvailable(String[] packageNames, UserHandle user, boolean replacing)1422         public void postOnPackagesAvailable(String[] packageNames, UserHandle user,
1423                 boolean replacing) {
1424             CallbackInfo info = new CallbackInfo();
1425             info.packageNames = packageNames;
1426             info.replacing = replacing;
1427             info.user = user;
1428             obtainMessage(MSG_AVAILABLE, info).sendToTarget();
1429         }
1430 
postOnPackagesUnavailable(String[] packageNames, UserHandle user, boolean replacing)1431         public void postOnPackagesUnavailable(String[] packageNames, UserHandle user,
1432                 boolean replacing) {
1433             CallbackInfo info = new CallbackInfo();
1434             info.packageNames = packageNames;
1435             info.replacing = replacing;
1436             info.user = user;
1437             obtainMessage(MSG_UNAVAILABLE, info).sendToTarget();
1438         }
1439 
postOnPackagesSuspended(String[] packageNames, Bundle launcherExtras, UserHandle user)1440         public void postOnPackagesSuspended(String[] packageNames, Bundle launcherExtras,
1441                 UserHandle user) {
1442             CallbackInfo info = new CallbackInfo();
1443             info.packageNames = packageNames;
1444             info.user = user;
1445             info.launcherExtras = launcherExtras;
1446             obtainMessage(MSG_SUSPENDED, info).sendToTarget();
1447         }
1448 
postOnPackagesUnsuspended(String[] packageNames, UserHandle user)1449         public void postOnPackagesUnsuspended(String[] packageNames, UserHandle user) {
1450             CallbackInfo info = new CallbackInfo();
1451             info.packageNames = packageNames;
1452             info.user = user;
1453             obtainMessage(MSG_UNSUSPENDED, info).sendToTarget();
1454         }
1455 
postOnShortcutChanged(String packageName, UserHandle user, List<ShortcutInfo> shortcuts)1456         public void postOnShortcutChanged(String packageName, UserHandle user,
1457                 List<ShortcutInfo> shortcuts) {
1458             CallbackInfo info = new CallbackInfo();
1459             info.packageName = packageName;
1460             info.user = user;
1461             info.shortcuts = shortcuts;
1462             obtainMessage(MSG_SHORTCUT_CHANGED, info).sendToTarget();
1463         }
1464     }
1465 
1466     /**
1467      * Register a callback to watch for session lifecycle events in this user and managed profiles.
1468      * @param callback The callback to register.
1469      * @param executor {@link Executor} to handle the callbacks, cannot be null.
1470      *
1471      * @see PackageInstaller#registerSessionCallback(SessionCallback)
1472      */
registerPackageInstallerSessionCallback( @onNull @allbackExecutor Executor executor, @NonNull SessionCallback callback)1473     public void registerPackageInstallerSessionCallback(
1474             @NonNull @CallbackExecutor Executor executor, @NonNull SessionCallback callback) {
1475         if (executor == null) {
1476             throw new NullPointerException("Executor must not be null");
1477         }
1478 
1479         synchronized (mDelegates) {
1480             final SessionCallbackDelegate delegate = new SessionCallbackDelegate(callback,
1481                     executor);
1482             try {
1483                 mService.registerPackageInstallerCallback(mContext.getPackageName(),
1484                         delegate);
1485             } catch (RemoteException e) {
1486                 throw e.rethrowFromSystemServer();
1487             }
1488             mDelegates.add(delegate);
1489         }
1490     }
1491 
1492     /**
1493      * Unregisters a callback that was previously registered.
1494      *
1495      * @param callback The callback to unregister.
1496      * @see #registerPackageInstallerSessionCallback(Executor, SessionCallback)
1497      */
unregisterPackageInstallerSessionCallback(@onNull SessionCallback callback)1498     public void unregisterPackageInstallerSessionCallback(@NonNull SessionCallback callback) {
1499         synchronized (mDelegates) {
1500             for (Iterator<SessionCallbackDelegate> i = mDelegates.iterator(); i.hasNext();) {
1501                 final SessionCallbackDelegate delegate = i.next();
1502                 if (delegate.mCallback == callback) {
1503                     mPm.getPackageInstaller().unregisterSessionCallback(delegate.mCallback);
1504                     i.remove();
1505                 }
1506             }
1507         }
1508     }
1509 
1510     /**
1511      * Return list of all known install sessions in this user and managed profiles, regardless
1512      * of the installer.
1513      *
1514      * @see PackageInstaller#getAllSessions()
1515      */
getAllPackageInstallerSessions()1516     public @NonNull List<SessionInfo> getAllPackageInstallerSessions() {
1517         try {
1518             return mService.getAllSessions(mContext.getPackageName()).getList();
1519         } catch (RemoteException e) {
1520             throw e.rethrowFromSystemServer();
1521         }
1522     }
1523 
1524     /**
1525      * A helper method to extract a {@link PinItemRequest} set to
1526      * the {@link #EXTRA_PIN_ITEM_REQUEST} extra.
1527      */
getPinItemRequest(Intent intent)1528     public PinItemRequest getPinItemRequest(Intent intent) {
1529         return intent.getParcelableExtra(EXTRA_PIN_ITEM_REQUEST);
1530     }
1531 
1532     /**
1533      * Represents a "pin shortcut" or a "pin appwidget" request made by an app, which is sent with
1534      * an {@link #ACTION_CONFIRM_PIN_SHORTCUT} or {@link #ACTION_CONFIRM_PIN_APPWIDGET} intent
1535      * respectively to the default launcher app.
1536      *
1537      * <h3>Request of the {@link #REQUEST_TYPE_SHORTCUT} type.
1538      *
1539      * <p>A {@link #REQUEST_TYPE_SHORTCUT} request represents a request to pin a
1540      * {@link ShortcutInfo}.  If the launcher accepts a request, call {@link #accept()},
1541      * or {@link #accept(Bundle)} with a null or empty Bundle.  No options are defined for
1542      * pin-shortcuts requests.
1543      *
1544      * <p>{@link #getShortcutInfo()} always returns a non-null {@link ShortcutInfo} for this type.
1545      *
1546      * <p>The launcher may receive a request with a {@link ShortcutInfo} that is already pinned, in
1547      * which case {@link ShortcutInfo#isPinned()} returns true.  This means the user wants to create
1548      * another pinned shortcut for a shortcut that's already pinned.  If the launcher accepts it,
1549      * {@link #accept()} must still be called even though the shortcut is already pinned, and
1550      * create a new pinned shortcut icon for it.
1551      *
1552      * <p>See also {@link ShortcutManager} for more details.
1553      *
1554      * <h3>Request of the {@link #REQUEST_TYPE_APPWIDGET} type.
1555      *
1556      * <p>A {@link #REQUEST_TYPE_SHORTCUT} request represents a request to pin a
1557      * an AppWidget.  If the launcher accepts a request, call {@link #accept(Bundle)} with
1558      * the appwidget integer ID set to the
1559      * {@link android.appwidget.AppWidgetManager#EXTRA_APPWIDGET_ID} extra.
1560      *
1561      * <p>{@link #getAppWidgetProviderInfo(Context)} always returns a non-null
1562      * {@link AppWidgetProviderInfo} for this type.
1563      *
1564      * <p>See also {@link AppWidgetManager} for more details.
1565      *
1566      * @see #EXTRA_PIN_ITEM_REQUEST
1567      * @see #getPinItemRequest(Intent)
1568      */
1569     public static final class PinItemRequest implements Parcelable {
1570 
1571         /** This is a request to pin shortcut. */
1572         public static final int REQUEST_TYPE_SHORTCUT = 1;
1573 
1574         /** This is a request to pin app widget. */
1575         public static final int REQUEST_TYPE_APPWIDGET = 2;
1576 
1577         /** @hide */
1578         @IntDef(prefix = { "REQUEST_TYPE_" }, value = {
1579                 REQUEST_TYPE_SHORTCUT,
1580                 REQUEST_TYPE_APPWIDGET
1581         })
1582         @Retention(RetentionPolicy.SOURCE)
1583         public @interface RequestType {}
1584 
1585         private final int mRequestType;
1586         private final IPinItemRequest mInner;
1587 
1588         /**
1589          * @hide
1590          */
PinItemRequest(IPinItemRequest inner, int type)1591         public PinItemRequest(IPinItemRequest inner, int type) {
1592             mInner = inner;
1593             mRequestType = type;
1594         }
1595 
1596         /**
1597          * Represents the type of a request, which is one of the {@code REQUEST_TYPE_} constants.
1598          *
1599          * @return one of the {@code REQUEST_TYPE_} constants.
1600          */
1601         @RequestType
getRequestType()1602         public int getRequestType() {
1603             return mRequestType;
1604         }
1605 
1606         /**
1607          * {@link ShortcutInfo} sent by the requesting app.
1608          * Always non-null for a {@link #REQUEST_TYPE_SHORTCUT} request, and always null for a
1609          * different request type.
1610          *
1611          * @return requested {@link ShortcutInfo} when a request is of the
1612          * {@link #REQUEST_TYPE_SHORTCUT} type.  Null otherwise.
1613          */
1614         @Nullable
getShortcutInfo()1615         public ShortcutInfo getShortcutInfo() {
1616             try {
1617                 return mInner.getShortcutInfo();
1618             } catch (RemoteException e) {
1619                 throw e.rethrowAsRuntimeException();
1620             }
1621         }
1622 
1623         /**
1624          * {@link AppWidgetProviderInfo} sent by the requesting app.
1625          * Always non-null for a {@link #REQUEST_TYPE_APPWIDGET} request, and always null for a
1626          * different request type.
1627          *
1628          * <p>Launcher should not show any configuration activity associated with the provider, and
1629          * assume that the widget is already fully configured. Upon accepting the widget, it should
1630          * pass the widgetId in {@link #accept(Bundle)}.
1631          *
1632          * @return requested {@link AppWidgetProviderInfo} when a request is of the
1633          * {@link #REQUEST_TYPE_APPWIDGET} type.  Null otherwise.
1634          */
1635         @Nullable
getAppWidgetProviderInfo(Context context)1636         public AppWidgetProviderInfo getAppWidgetProviderInfo(Context context) {
1637             try {
1638                 final AppWidgetProviderInfo info = mInner.getAppWidgetProviderInfo();
1639                 if (info == null) {
1640                     return null;
1641                 }
1642                 info.updateDimensions(context.getResources().getDisplayMetrics());
1643                 return info;
1644             } catch (RemoteException e) {
1645                 throw e.rethrowAsRuntimeException();
1646             }
1647         }
1648 
1649         /**
1650          * Any extras sent by the requesting app.
1651          *
1652          * @return For a shortcut request, this method always return null.  For an AppWidget
1653          * request, this method returns the extras passed to the
1654          * {@link android.appwidget.AppWidgetManager#requestPinAppWidget(
1655          * ComponentName, Bundle, PendingIntent)} API.  See {@link AppWidgetManager} for details.
1656          */
1657         @Nullable
getExtras()1658         public Bundle getExtras() {
1659             try {
1660                 return mInner.getExtras();
1661             } catch (RemoteException e) {
1662                 throw e.rethrowAsRuntimeException();
1663             }
1664         }
1665 
1666         /**
1667          * Return whether a request is still valid.
1668          *
1669          * @return {@code TRUE} if a request is valid and {@link #accept(Bundle)} may be called.
1670          */
isValid()1671         public boolean isValid() {
1672             try {
1673                 return mInner.isValid();
1674             } catch (RemoteException e) {
1675                 return false;
1676             }
1677         }
1678 
1679         /**
1680          * Called by the receiving launcher app when the user accepts the request.
1681          *
1682          * @param options must be set for a {@link #REQUEST_TYPE_APPWIDGET} request.
1683          *
1684          * @return {@code TRUE} if the shortcut or the AppWidget has actually been pinned.
1685          * {@code FALSE} if the item hasn't been pinned, for example, because the request had
1686          * already been canceled, in which case the launcher must not pin the requested item.
1687          */
accept(@ullable Bundle options)1688         public boolean accept(@Nullable Bundle options) {
1689             try {
1690                 return mInner.accept(options);
1691             } catch (RemoteException e) {
1692                 throw e.rethrowFromSystemServer();
1693             }
1694         }
1695 
1696         /**
1697          * Called by the receiving launcher app when the user accepts the request, with no options.
1698          *
1699          * @return {@code TRUE} if the shortcut or the AppWidget has actually been pinned.
1700          * {@code FALSE} if the item hasn't been pinned, for example, because the request had
1701          * already been canceled, in which case the launcher must not pin the requested item.
1702          */
accept()1703         public boolean accept() {
1704             return accept(/* options= */ null);
1705         }
1706 
PinItemRequest(Parcel source)1707         private PinItemRequest(Parcel source) {
1708             final ClassLoader cl = getClass().getClassLoader();
1709 
1710             mRequestType = source.readInt();
1711             mInner = IPinItemRequest.Stub.asInterface(source.readStrongBinder());
1712         }
1713 
1714         @Override
writeToParcel(Parcel dest, int flags)1715         public void writeToParcel(Parcel dest, int flags) {
1716             dest.writeInt(mRequestType);
1717             dest.writeStrongBinder(mInner.asBinder());
1718         }
1719 
1720         public static final @android.annotation.NonNull Creator<PinItemRequest> CREATOR =
1721                 new Creator<PinItemRequest>() {
1722                     public PinItemRequest createFromParcel(Parcel source) {
1723                         return new PinItemRequest(source);
1724                     }
1725                     public PinItemRequest[] newArray(int size) {
1726                         return new PinItemRequest[size];
1727                     }
1728                 };
1729 
1730         @Override
describeContents()1731         public int describeContents() {
1732             return 0;
1733         }
1734     }
1735 
1736     /**
1737      * A class that encapsulates information about the usage limit set for an app or
1738      * a group of apps.
1739      *
1740      * <p>The launcher can query specifics about the usage limit such as how much usage time
1741      * the limit has and how much of the total usage time is remaining via the APIs available
1742      * in this class.
1743      *
1744      * @see #getAppUsageLimit(String, UserHandle)
1745      * @hide
1746      */
1747     @SystemApi
1748     public static final class AppUsageLimit implements Parcelable {
1749         private final long mTotalUsageLimit;
1750         private final long mUsageRemaining;
1751 
1752         /** @hide */
AppUsageLimit(long totalUsageLimit, long usageRemaining)1753         public AppUsageLimit(long totalUsageLimit, long usageRemaining) {
1754             this.mTotalUsageLimit = totalUsageLimit;
1755             this.mUsageRemaining = usageRemaining;
1756         }
1757 
1758         /**
1759          * Returns the total usage limit in milliseconds set for an app or a group of apps.
1760          *
1761          * @return the total usage limit in milliseconds
1762          */
getTotalUsageLimit()1763         public long getTotalUsageLimit() {
1764             return mTotalUsageLimit;
1765         }
1766 
1767         /**
1768          * Returns the usage remaining in milliseconds for an app or the group of apps
1769          * this limit refers to.
1770          *
1771          * @return the usage remaining in milliseconds
1772          */
getUsageRemaining()1773         public long getUsageRemaining() {
1774             return mUsageRemaining;
1775         }
1776 
AppUsageLimit(Parcel source)1777         private AppUsageLimit(Parcel source) {
1778             mTotalUsageLimit = source.readLong();
1779             mUsageRemaining = source.readLong();
1780         }
1781 
1782         public static final @android.annotation.NonNull Creator<AppUsageLimit> CREATOR = new Creator<AppUsageLimit>() {
1783             @Override
1784             public AppUsageLimit createFromParcel(Parcel source) {
1785                 return new AppUsageLimit(source);
1786             }
1787 
1788             @Override
1789             public AppUsageLimit[] newArray(int size) {
1790                 return new AppUsageLimit[size];
1791             }
1792         };
1793 
1794         @Override
describeContents()1795         public int describeContents() {
1796             return 0;
1797         }
1798 
1799         @Override
writeToParcel(Parcel dest, int flags)1800         public void writeToParcel(Parcel dest, int flags) {
1801             dest.writeLong(mTotalUsageLimit);
1802             dest.writeLong(mUsageRemaining);
1803         }
1804     }
1805 }
1806