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