LauncherAppsService.java revision c5475d42a45ba48477257879e7a5b2af54a23f98
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
17package com.android.server.pm;
18
19import android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.annotation.UserIdInt;
22import android.app.AppGlobals;
23import android.content.ComponentName;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.ActivityInfo;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.ILauncherApps;
29import android.content.pm.IOnAppsChangedListener;
30import android.content.pm.IPackageManager;
31import android.content.pm.LauncherApps.ShortcutQuery;
32import android.content.pm.PackageInfo;
33import android.content.pm.PackageManager;
34import android.content.pm.PackageManager.NameNotFoundException;
35import android.content.pm.ParceledListSlice;
36import android.content.pm.ResolveInfo;
37import android.content.pm.ShortcutInfo;
38import android.content.pm.ShortcutServiceInternal;
39import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
40import android.content.pm.UserInfo;
41import android.graphics.Rect;
42import android.net.Uri;
43import android.os.Binder;
44import android.os.Bundle;
45import android.os.Handler;
46import android.os.IInterface;
47import android.os.ParcelFileDescriptor;
48import android.os.RemoteCallbackList;
49import android.os.RemoteException;
50import android.os.UserHandle;
51import android.os.UserManager;
52import android.provider.Settings;
53import android.util.Log;
54import android.util.Slog;
55
56import com.android.internal.annotations.VisibleForTesting;
57import com.android.internal.content.PackageMonitor;
58import com.android.internal.os.BackgroundThread;
59import com.android.internal.util.Preconditions;
60import com.android.server.LocalServices;
61import com.android.server.SystemService;
62
63import java.util.List;
64
65/**
66 * Service that manages requests and callbacks for launchers that support
67 * managed profiles.
68 */
69public class LauncherAppsService extends SystemService {
70
71    private final LauncherAppsImpl mLauncherAppsImpl;
72
73    public LauncherAppsService(Context context) {
74        super(context);
75        mLauncherAppsImpl = new LauncherAppsImpl(context);
76    }
77
78    @Override
79    public void onStart() {
80        Binder.LOG_RUNTIME_EXCEPTION = true;
81        publishBinderService(Context.LAUNCHER_APPS_SERVICE, mLauncherAppsImpl);
82    }
83
84    static class BroadcastCookie {
85        public final UserHandle user;
86        public final String packageName;
87
88        BroadcastCookie(UserHandle userHandle, String packageName) {
89            this.user = userHandle;
90            this.packageName = packageName;
91        }
92    }
93
94    @VisibleForTesting
95    static class LauncherAppsImpl extends ILauncherApps.Stub {
96        private static final boolean DEBUG = false;
97        private static final String TAG = "LauncherAppsService";
98        private final Context mContext;
99        private final PackageManager mPm;
100        private final UserManager mUm;
101        private final ShortcutServiceInternal mShortcutServiceInternal;
102        private final PackageCallbackList<IOnAppsChangedListener> mListeners
103                = new PackageCallbackList<IOnAppsChangedListener>();
104
105        private final MyPackageMonitor mPackageMonitor = new MyPackageMonitor();
106
107        private final Handler mCallbackHandler;
108
109        public LauncherAppsImpl(Context context) {
110            mContext = context;
111            mPm = mContext.getPackageManager();
112            mUm = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
113            mShortcutServiceInternal = Preconditions.checkNotNull(
114                    LocalServices.getService(ShortcutServiceInternal.class));
115            mShortcutServiceInternal.addListener(mPackageMonitor);
116            mCallbackHandler = BackgroundThread.getHandler();
117        }
118
119        @VisibleForTesting
120        int injectBinderCallingUid() {
121            return getCallingUid();
122        }
123
124        private int getCallingUserId() {
125            return UserHandle.getUserId(injectBinderCallingUid());
126        }
127
128        /*
129         * @see android.content.pm.ILauncherApps#addOnAppsChangedListener(
130         *          android.content.pm.IOnAppsChangedListener)
131         */
132        @Override
133        public void addOnAppsChangedListener(String callingPackage, IOnAppsChangedListener listener)
134                throws RemoteException {
135            synchronized (mListeners) {
136                if (DEBUG) {
137                    Log.d(TAG, "Adding listener from " + Binder.getCallingUserHandle());
138                }
139                if (mListeners.getRegisteredCallbackCount() == 0) {
140                    if (DEBUG) {
141                        Log.d(TAG, "Starting package monitoring");
142                    }
143                    startWatchingPackageBroadcasts();
144                }
145                mListeners.unregister(listener);
146                mListeners.register(listener, new BroadcastCookie(UserHandle.of(getCallingUserId()),
147                        callingPackage));
148            }
149        }
150
151        /*
152         * @see android.content.pm.ILauncherApps#removeOnAppsChangedListener(
153         *          android.content.pm.IOnAppsChangedListener)
154         */
155        @Override
156        public void removeOnAppsChangedListener(IOnAppsChangedListener listener)
157                throws RemoteException {
158            synchronized (mListeners) {
159                if (DEBUG) {
160                    Log.d(TAG, "Removing listener from " + Binder.getCallingUserHandle());
161                }
162                mListeners.unregister(listener);
163                if (mListeners.getRegisteredCallbackCount() == 0) {
164                    stopWatchingPackageBroadcasts();
165                }
166            }
167        }
168
169        /**
170         * Register a receiver to watch for package broadcasts
171         */
172        private void startWatchingPackageBroadcasts() {
173            mPackageMonitor.register(mContext, UserHandle.ALL, true, mCallbackHandler);
174        }
175
176        /**
177         * Unregister package broadcast receiver
178         */
179        private void stopWatchingPackageBroadcasts() {
180            if (DEBUG) {
181                Log.d(TAG, "Stopped watching for packages");
182            }
183            mPackageMonitor.unregister();
184        }
185
186        void checkCallbackCount() {
187            synchronized (mListeners) {
188                if (DEBUG) {
189                    Log.d(TAG, "Callback count = " + mListeners.getRegisteredCallbackCount());
190                }
191                if (mListeners.getRegisteredCallbackCount() == 0) {
192                    stopWatchingPackageBroadcasts();
193                }
194            }
195        }
196
197        /**
198         * Checks if the caller is in the same group as the userToCheck.
199         */
200        @VisibleForTesting // We override it in unit tests
201        void ensureInUserProfiles(UserHandle userToCheck, String message) {
202            final int callingUserId = UserHandle.getCallingUserId();
203            final int targetUserId = userToCheck.getIdentifier();
204
205            if (targetUserId == callingUserId) return;
206
207            long ident = Binder.clearCallingIdentity();
208            try {
209                UserInfo callingUserInfo = mUm.getUserInfo(callingUserId);
210                UserInfo targetUserInfo = mUm.getUserInfo(targetUserId);
211                if (targetUserInfo == null
212                        || targetUserInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID
213                        || targetUserInfo.profileGroupId != callingUserInfo.profileGroupId) {
214                    throw new SecurityException(message);
215                }
216            } finally {
217                Binder.restoreCallingIdentity(ident);
218            }
219        }
220
221        @VisibleForTesting // We override it in unit tests
222        void verifyCallingPackage(String callingPackage) {
223            int packageUid = -1;
224            try {
225                packageUid = mPm.getPackageUidAsUser(callingPackage,
226                        PackageManager.MATCH_DIRECT_BOOT_AWARE
227                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
228                                | PackageManager.MATCH_UNINSTALLED_PACKAGES,
229                        UserHandle.getUserId(getCallingUid()));
230            } catch (NameNotFoundException e) {
231                Log.e(TAG, "Package not found: " + callingPackage);
232            }
233            if (packageUid != Binder.getCallingUid()) {
234                throw new SecurityException("Calling package name mismatch");
235            }
236        }
237
238        /**
239         * Checks if the user is enabled.
240         */
241        private boolean isUserEnabled(UserHandle user) {
242            long ident = Binder.clearCallingIdentity();
243            try {
244                UserInfo targetUserInfo = mUm.getUserInfo(user.getIdentifier());
245                return targetUserInfo != null && targetUserInfo.isEnabled();
246            } finally {
247                Binder.restoreCallingIdentity(ident);
248            }
249        }
250
251        @Override
252        public ParceledListSlice<ResolveInfo> getLauncherActivities(String packageName, UserHandle user)
253                throws RemoteException {
254            ensureInUserProfiles(user, "Cannot retrieve activities for unrelated profile " + user);
255            if (!isUserEnabled(user)) {
256                return null;
257            }
258
259            final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
260            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
261            mainIntent.setPackage(packageName);
262            long ident = Binder.clearCallingIdentity();
263            try {
264                List<ResolveInfo> apps = mPm.queryIntentActivitiesAsUser(mainIntent,
265                        PackageManager.MATCH_DIRECT_BOOT_AWARE
266                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
267                        user.getIdentifier());
268                return new ParceledListSlice<>(apps);
269            } finally {
270                Binder.restoreCallingIdentity(ident);
271            }
272        }
273
274        @Override
275        public ResolveInfo resolveActivity(Intent intent, UserHandle user)
276                throws RemoteException {
277            ensureInUserProfiles(user, "Cannot resolve activity for unrelated profile " + user);
278            if (!isUserEnabled(user)) {
279                return null;
280            }
281
282            long ident = Binder.clearCallingIdentity();
283            try {
284                ResolveInfo app = mPm.resolveActivityAsUser(intent,
285                        PackageManager.MATCH_DIRECT_BOOT_AWARE
286                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
287                        user.getIdentifier());
288                return app;
289            } finally {
290                Binder.restoreCallingIdentity(ident);
291            }
292        }
293
294        @Override
295        public boolean isPackageEnabled(String packageName, UserHandle user)
296                throws RemoteException {
297            ensureInUserProfiles(user, "Cannot check package for unrelated profile " + user);
298            if (!isUserEnabled(user)) {
299                return false;
300            }
301
302            long ident = Binder.clearCallingIdentity();
303            try {
304                IPackageManager pm = AppGlobals.getPackageManager();
305                PackageInfo info = pm.getPackageInfo(packageName,
306                        PackageManager.MATCH_DIRECT_BOOT_AWARE
307                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
308                        user.getIdentifier());
309                return info != null && info.applicationInfo.enabled;
310            } finally {
311                Binder.restoreCallingIdentity(ident);
312            }
313        }
314
315        @Override
316        public ApplicationInfo getApplicationInfo(String packageName, int flags, UserHandle user)
317                throws RemoteException {
318            ensureInUserProfiles(user, "Cannot check package for unrelated profile " + user);
319            if (!isUserEnabled(user)) {
320                return null;
321            }
322
323            long ident = Binder.clearCallingIdentity();
324            try {
325                IPackageManager pm = AppGlobals.getPackageManager();
326                ApplicationInfo info = pm.getApplicationInfo(packageName, flags,
327                        user.getIdentifier());
328                return info;
329            } finally {
330                Binder.restoreCallingIdentity(ident);
331            }
332        }
333
334        private void ensureShortcutPermission(@NonNull String callingPackage, UserHandle user) {
335            verifyCallingPackage(callingPackage);
336            ensureInUserProfiles(user, "Cannot start activity for unrelated profile " + user);
337
338            if (!mShortcutServiceInternal.hasShortcutHostPermission(callingPackage,
339                    user.getIdentifier())) {
340                throw new SecurityException("Caller can't access shortcut information");
341            }
342        }
343
344        @Override
345        public ParceledListSlice getShortcuts(String callingPackage, long changedSince,
346                String packageName, ComponentName componentName, int flags, UserHandle user)
347                throws RemoteException {
348            ensureShortcutPermission(callingPackage, user);
349
350            return new ParceledListSlice<>(
351                    mShortcutServiceInternal.getShortcuts(callingPackage, changedSince, packageName,
352                    componentName, flags, user.getIdentifier()));
353        }
354
355        @Override
356        public ParceledListSlice getShortcutInfo(String callingPackage, String packageName,
357                List<String> ids, UserHandle user) throws RemoteException {
358            ensureShortcutPermission(callingPackage, user);
359
360            return new ParceledListSlice<>(
361                    mShortcutServiceInternal.getShortcutInfo(callingPackage, packageName,
362                    ids, user.getIdentifier()));
363        }
364
365        @Override
366        public void pinShortcuts(String callingPackage, String packageName, List<String> ids,
367                UserHandle user) throws RemoteException {
368            ensureShortcutPermission(callingPackage, user);
369
370            mShortcutServiceInternal.pinShortcuts(callingPackage, packageName,
371                    ids, user.getIdentifier());
372        }
373
374        @Override
375        public int getShortcutIconResId(String callingPackage, ShortcutInfo shortcut,
376                UserHandle user) {
377            ensureShortcutPermission(callingPackage, user);
378
379            return mShortcutServiceInternal.getShortcutIconResId(callingPackage, shortcut,
380                    user.getIdentifier());
381        }
382
383        @Override
384        public ParcelFileDescriptor getShortcutIconFd(String callingPackage, ShortcutInfo shortcut,
385                UserHandle user) {
386            ensureShortcutPermission(callingPackage, user);
387
388            return mShortcutServiceInternal.getShortcutIconFd(callingPackage, shortcut,
389                    user.getIdentifier());
390        }
391
392        @Override
393        public boolean hasShortcutHostPermission(String callingPackage) throws RemoteException {
394            verifyCallingPackage(callingPackage);
395            return mShortcutServiceInternal.hasShortcutHostPermission(callingPackage,
396                    getCallingUserId());
397        }
398
399        @Override
400        public boolean startShortcut(String callingPackage, String packageName, String shortcutId,
401                Rect sourceBounds, Bundle startActivityOptions, UserHandle user)
402                throws RemoteException {
403            ensureShortcutPermission(callingPackage, user);
404
405            final Intent intent = mShortcutServiceInternal.createShortcutIntent(callingPackage,
406                    packageName, shortcutId, user.getIdentifier());
407            if (intent == null) {
408                return false;
409            }
410            // Note the target activity doesn't have to be exported.
411
412            intent.setSourceBounds(sourceBounds);
413            prepareIntentForLaunch(intent, sourceBounds);
414
415            final long ident = Binder.clearCallingIdentity();
416            try {
417                mContext.startActivityAsUser(intent, startActivityOptions, user);
418            } finally {
419                Binder.restoreCallingIdentity(ident);
420            }
421            return true;
422        }
423
424        @Override
425        public boolean isActivityEnabled(ComponentName component, UserHandle user)
426                throws RemoteException {
427            ensureInUserProfiles(user, "Cannot check component for unrelated profile " + user);
428            if (!isUserEnabled(user)) {
429                return false;
430            }
431
432            long ident = Binder.clearCallingIdentity();
433            try {
434                IPackageManager pm = AppGlobals.getPackageManager();
435                ActivityInfo info = pm.getActivityInfo(component,
436                        PackageManager.MATCH_DIRECT_BOOT_AWARE
437                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
438                        user.getIdentifier());
439                return info != null;
440            } finally {
441                Binder.restoreCallingIdentity(ident);
442            }
443        }
444
445        @Override
446        public void startActivityAsUser(ComponentName component, Rect sourceBounds,
447                Bundle opts, UserHandle user) throws RemoteException {
448            ensureInUserProfiles(user, "Cannot start activity for unrelated profile " + user);
449            if (!isUserEnabled(user)) {
450                throw new IllegalStateException("Cannot start activity for disabled profile "  + user);
451            }
452
453            Intent launchIntent = new Intent(Intent.ACTION_MAIN);
454            launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
455            prepareIntentForLaunch(launchIntent, sourceBounds);
456            launchIntent.setPackage(component.getPackageName());
457
458            long ident = Binder.clearCallingIdentity();
459            try {
460                IPackageManager pm = AppGlobals.getPackageManager();
461                ActivityInfo info = pm.getActivityInfo(component,
462                        PackageManager.MATCH_DIRECT_BOOT_AWARE
463                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
464                        user.getIdentifier());
465                if (!info.exported) {
466                    throw new SecurityException("Cannot launch non-exported components "
467                            + component);
468                }
469
470                // Check that the component actually has Intent.CATEGORY_LAUCNCHER
471                // as calling startActivityAsUser ignores the category and just
472                // resolves based on the component if present.
473                List<ResolveInfo> apps = mPm.queryIntentActivitiesAsUser(launchIntent,
474                        PackageManager.MATCH_DIRECT_BOOT_AWARE
475                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
476                        user.getIdentifier());
477                final int size = apps.size();
478                for (int i = 0; i < size; ++i) {
479                    ActivityInfo activityInfo = apps.get(i).activityInfo;
480                    if (activityInfo.packageName.equals(component.getPackageName()) &&
481                            activityInfo.name.equals(component.getClassName())) {
482                        // Found an activity with category launcher that matches
483                        // this component so ok to launch.
484                        launchIntent.setComponent(component);
485                        mContext.startActivityAsUser(launchIntent, opts, user);
486                        return;
487                    }
488                }
489                throw new SecurityException("Attempt to launch activity without "
490                        + " category Intent.CATEGORY_LAUNCHER " + component);
491            } finally {
492                Binder.restoreCallingIdentity(ident);
493            }
494        }
495
496        private void prepareIntentForLaunch(@NonNull Intent launchIntent,
497                @Nullable Rect sourceBounds) {
498            launchIntent.setSourceBounds(sourceBounds);
499            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
500                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
501        }
502
503        @Override
504        public void showAppDetailsAsUser(ComponentName component, Rect sourceBounds,
505                Bundle opts, UserHandle user) throws RemoteException {
506            ensureInUserProfiles(user, "Cannot show app details for unrelated profile " + user);
507            if (!isUserEnabled(user)) {
508                throw new IllegalStateException("Cannot show app details for disabled profile "
509                        + user);
510            }
511
512            long ident = Binder.clearCallingIdentity();
513            try {
514                String packageName = component.getPackageName();
515                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
516                        Uri.fromParts("package", packageName, null));
517                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
518                intent.setSourceBounds(sourceBounds);
519                mContext.startActivityAsUser(intent, opts, user);
520            } finally {
521                Binder.restoreCallingIdentity(ident);
522            }
523        }
524
525        /** Checks if user is a profile of or same as listeningUser.
526         * and the user is enabled. */
527        boolean isEnabledProfileOf(UserHandle user, UserHandle listeningUser,
528                String debugMsg) {
529            if (user.getIdentifier() == listeningUser.getIdentifier()) {
530                if (DEBUG) Log.d(TAG, "Delivering msg to same user " + debugMsg);
531                return true;
532            }
533            long ident = Binder.clearCallingIdentity();
534            try {
535                UserInfo userInfo = mUm.getUserInfo(user.getIdentifier());
536                UserInfo listeningUserInfo = mUm.getUserInfo(listeningUser.getIdentifier());
537                if (userInfo == null || listeningUserInfo == null
538                        || userInfo.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID
539                        || userInfo.profileGroupId != listeningUserInfo.profileGroupId
540                        || !userInfo.isEnabled()) {
541                    if (DEBUG) {
542                        Log.d(TAG, "Not delivering msg from " + user + " to " + listeningUser + ":"
543                                + debugMsg);
544                    }
545                    return false;
546                } else {
547                    if (DEBUG) {
548                        Log.d(TAG, "Delivering msg from " + user + " to " + listeningUser + ":"
549                                + debugMsg);
550                    }
551                    return true;
552                }
553            } finally {
554                Binder.restoreCallingIdentity(ident);
555            }
556        }
557
558        @VisibleForTesting
559        void postToPackageMonitorHandler(Runnable r) {
560            mCallbackHandler.post(r);
561        }
562
563        private class MyPackageMonitor extends PackageMonitor implements ShortcutChangeListener {
564
565            // TODO Simplify with lambdas.
566
567            @Override
568            public void onPackageAdded(String packageName, int uid) {
569                UserHandle user = new UserHandle(getChangingUserId());
570                final int n = mListeners.beginBroadcast();
571                for (int i = 0; i < n; i++) {
572                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
573                    BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
574                    if (!isEnabledProfileOf(user, cookie.user, "onPackageAdded")) continue;
575                    try {
576                        listener.onPackageAdded(user, packageName);
577                    } catch (RemoteException re) {
578                        Slog.d(TAG, "Callback failed ", re);
579                    }
580                }
581                mListeners.finishBroadcast();
582
583                super.onPackageAdded(packageName, uid);
584            }
585
586            @Override
587            public void onPackageRemoved(String packageName, int uid) {
588                UserHandle user = new UserHandle(getChangingUserId());
589                final int n = mListeners.beginBroadcast();
590                for (int i = 0; i < n; i++) {
591                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
592                    BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
593                    if (!isEnabledProfileOf(user, cookie.user, "onPackageRemoved")) continue;
594                    try {
595                        listener.onPackageRemoved(user, packageName);
596                    } catch (RemoteException re) {
597                        Slog.d(TAG, "Callback failed ", re);
598                    }
599                }
600                mListeners.finishBroadcast();
601
602                super.onPackageRemoved(packageName, uid);
603            }
604
605            @Override
606            public void onPackageModified(String packageName) {
607                UserHandle user = new UserHandle(getChangingUserId());
608                final int n = mListeners.beginBroadcast();
609                for (int i = 0; i < n; i++) {
610                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
611                    BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
612                    if (!isEnabledProfileOf(user, cookie.user, "onPackageModified")) continue;
613                    try {
614                        listener.onPackageChanged(user, packageName);
615                    } catch (RemoteException re) {
616                        Slog.d(TAG, "Callback failed ", re);
617                    }
618                }
619                mListeners.finishBroadcast();
620
621                super.onPackageModified(packageName);
622            }
623
624            @Override
625            public void onPackagesAvailable(String[] packages) {
626                UserHandle user = new UserHandle(getChangingUserId());
627                final int n = mListeners.beginBroadcast();
628                for (int i = 0; i < n; i++) {
629                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
630                    BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
631                    if (!isEnabledProfileOf(user, cookie.user, "onPackagesAvailable")) continue;
632                    try {
633                        listener.onPackagesAvailable(user, packages, isReplacing());
634                    } catch (RemoteException re) {
635                        Slog.d(TAG, "Callback failed ", re);
636                    }
637                }
638                mListeners.finishBroadcast();
639
640                super.onPackagesAvailable(packages);
641            }
642
643            @Override
644            public void onPackagesUnavailable(String[] packages) {
645                UserHandle user = new UserHandle(getChangingUserId());
646                final int n = mListeners.beginBroadcast();
647                for (int i = 0; i < n; i++) {
648                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
649                    BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
650                    if (!isEnabledProfileOf(user, cookie.user, "onPackagesUnavailable")) continue;
651                    try {
652                        listener.onPackagesUnavailable(user, packages, isReplacing());
653                    } catch (RemoteException re) {
654                        Slog.d(TAG, "Callback failed ", re);
655                    }
656                }
657                mListeners.finishBroadcast();
658
659                super.onPackagesUnavailable(packages);
660            }
661
662            @Override
663            public void onPackagesSuspended(String[] packages) {
664                UserHandle user = new UserHandle(getChangingUserId());
665                final int n = mListeners.beginBroadcast();
666                for (int i = 0; i < n; i++) {
667                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
668                    BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
669                    if (!isEnabledProfileOf(user, cookie.user, "onPackagesSuspended")) continue;
670                    try {
671                        listener.onPackagesSuspended(user, packages);
672                    } catch (RemoteException re) {
673                        Slog.d(TAG, "Callback failed ", re);
674                    }
675                }
676                mListeners.finishBroadcast();
677
678                super.onPackagesSuspended(packages);
679            }
680
681            @Override
682            public void onPackagesUnsuspended(String[] packages) {
683                UserHandle user = new UserHandle(getChangingUserId());
684                final int n = mListeners.beginBroadcast();
685                for (int i = 0; i < n; i++) {
686                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
687                    BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
688                    if (!isEnabledProfileOf(user, cookie.user, "onPackagesUnsuspended")) continue;
689                    try {
690                        listener.onPackagesUnsuspended(user, packages);
691                    } catch (RemoteException re) {
692                        Slog.d(TAG, "Callback failed ", re);
693                    }
694                }
695                mListeners.finishBroadcast();
696
697                super.onPackagesUnsuspended(packages);
698            }
699
700            @Override
701            public void onShortcutChanged(@NonNull String packageName,
702                    @UserIdInt int userId) {
703                postToPackageMonitorHandler(() -> onShortcutChangedInner(packageName, userId));
704            }
705
706            private void onShortcutChangedInner(@NonNull String packageName,
707                    @UserIdInt int userId) {
708                final UserHandle user = UserHandle.of(userId);
709
710                final int n = mListeners.beginBroadcast();
711                for (int i = 0; i < n; i++) {
712                    IOnAppsChangedListener listener = mListeners.getBroadcastItem(i);
713                    BroadcastCookie cookie = (BroadcastCookie) mListeners.getBroadcastCookie(i);
714                    if (!isEnabledProfileOf(user, cookie.user, "onShortcutChanged")) continue;
715
716                    // Make sure the caller has the permission.
717                    if (!mShortcutServiceInternal.hasShortcutHostPermission(cookie.packageName,
718                            cookie.user.getIdentifier())) {
719                        continue;
720                    }
721                    // Each launcher has a different set of pinned shortcuts, so we need to do a
722                    // query in here.
723                    // (As of now, only one launcher has the permission at a time, so it's bit
724                    // moot, but we may change the permission model eventually.)
725                    final List<ShortcutInfo> list =
726                            mShortcutServiceInternal.getShortcuts(cookie.packageName,
727                            /* changedSince= */ 0, packageName, /* component= */ null,
728                                    ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY
729                                    | ShortcutQuery.FLAG_GET_PINNED
730                                    | ShortcutQuery.FLAG_GET_DYNAMIC
731                                    , userId);
732                    try {
733                        listener.onShortcutChanged(user, packageName,
734                                new ParceledListSlice<>(list));
735                    } catch (RemoteException re) {
736                        Slog.d(TAG, "Callback failed ", re);
737                    }
738                }
739                mListeners.finishBroadcast();
740            }
741        }
742
743        class PackageCallbackList<T extends IInterface> extends RemoteCallbackList<T> {
744            @Override
745            public void onCallbackDied(T callback, Object cookie) {
746                checkCallbackCount();
747            }
748        }
749    }
750}
751