Revert "Revert "Revert "Handle package broadcasts before apps do"""

This reverts commit 886ba78dfb105eb45416587b73b6c6b336448de5.

With the tests updated.

Change-Id: I162e6ca23c667f90feddc1e9f42b554a416295cf
diff --git a/core/java/android/content/pm/ShortcutServiceInternal.java b/core/java/android/content/pm/ShortcutServiceInternal.java
index de52f73..3f8bad1 100644
--- a/core/java/android/content/pm/ShortcutServiceInternal.java
+++ b/core/java/android/content/pm/ShortcutServiceInternal.java
@@ -73,11 +73,4 @@
      * any locks in this method.
      */
     public abstract void onSystemLocaleChangedNoLock();
-
-    /**
-     * Called by PM before sending package broadcasts to other components.  PM doesn't hold the PM
-     * lock, but do not take any locks in here anyway, and don't do any heavy tasks, as doing so
-     * would slow down all the package broadcasts.
-     */
-    public abstract void onPackageBroadcast(Intent intent);
 }
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 1ca6148..5980715 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -159,7 +159,6 @@
 import android.content.pm.ProviderInfo;
 import android.content.pm.ResolveInfo;
 import android.content.pm.ServiceInfo;
-import android.content.pm.ShortcutServiceInternal;
 import android.content.pm.Signature;
 import android.content.pm.UserInfo;
 import android.content.pm.VerifierDeviceIdentity;
@@ -11439,9 +11438,6 @@
                     } else {
                         resolvedUserIds = userIds;
                     }
-                    final ShortcutServiceInternal shortcutService =
-                            LocalServices.getService(ShortcutServiceInternal.class);
-
                     for (int id : resolvedUserIds) {
                         final Intent intent = new Intent(action,
                                 pkg != null ? Uri.fromParts("package", pkg, null) : null);
@@ -11466,10 +11462,6 @@
                                     + intent.toShortString(false, true, false, false)
                                     + " " + intent.getExtras(), here);
                         }
-                        // TODO b/29385425 Consider making lifecycle callbacks for this.
-                        if (shortcutService != null) {
-                            shortcutService.onPackageBroadcast(intent);
-                        }
                         am.broadcastIntent(null, intent, null, finishedReceiver,
                                 0, null, null, null, android.app.AppOpsManager.OP_NONE,
                                 null, finishedReceiver != null, false, id);
diff --git a/services/core/java/com/android/server/pm/ShortcutPendingTasks.java b/services/core/java/com/android/server/pm/ShortcutPendingTasks.java
deleted file mode 100644
index a5ace56..0000000
--- a/services/core/java/com/android/server/pm/ShortcutPendingTasks.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.server.pm;
-
-import android.annotation.NonNull;
-import android.util.Slog;
-
-import java.io.PrintWriter;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.function.BooleanSupplier;
-import java.util.function.Consumer;
-import java.util.logging.Handler;
-
-/**
- * Used by {@link ShortcutService} to register tasks to be executed on Handler and also wait for
- * all pending tasks.
- *
- * Tasks can be registered with {@link #addTask(Runnable)}.  Call {@link #waitOnAllTasks()} to wait
- * on all tasks that have been registered.
- *
- * In order to avoid deadlocks, {@link #waitOnAllTasks} MUST NOT be called with any lock held, nor
- * on the handler thread.  These conditions are checked by {@link #mWaitThreadChecker} and wtf'ed.
- *
- * During unit tests, we can't run tasks asynchronously, so we just run Runnables synchronously,
- * which also means the "is lock held" check doesn't work properly during unit tests (e.g. normally
- * when a Runnable is executed on a Handler, the thread doesn't hold any lock, but during the tests
- * we just run a Runnable on the thread that registers it, so the thread may or may not hold locks.)
- * So unfortunately we have to disable {@link #mWaitThreadChecker} during unit tests.
- *
- * Because of the complications like those, this class should be used only for specific purposes:
- * - {@link #addTask(Runnable)} should only be used to register tasks on callbacks from lower level
- * services like the package manager or the activity manager.
- *
- * - {@link #waitOnAllTasks} should only be called at the entry point of RPC calls (or the test only
- * accessors}.
- */
-public class ShortcutPendingTasks {
-    private static final String TAG = "ShortcutPendingTasks";
-
-    private static final boolean DEBUG = false || ShortcutService.DEBUG; // DO NOT SUBMIT WITH TRUE.
-
-    private final Consumer<Runnable> mRunner;
-
-    private final BooleanSupplier mWaitThreadChecker;
-
-    private final Consumer<Throwable> mExceptionHandler;
-
-    /** # of tasks in the queue, including the running one. */
-    private final AtomicInteger mRunningTaskCount = new AtomicInteger();
-
-    /** For dumpsys */
-    private final AtomicLong mLastTaskStartTime = new AtomicLong();
-
-    /**
-     * Constructor.  In order to allow injection during unit tests, it doesn't take a
-     * {@link Handler} directly, and instead takes {@code runner} which will post an argument
-     * to a handler.
-     */
-    public ShortcutPendingTasks(Consumer<Runnable> runner, BooleanSupplier waitThreadChecker,
-            Consumer<Throwable> exceptionHandler) {
-        mRunner = runner;
-        mWaitThreadChecker = waitThreadChecker;
-        mExceptionHandler = exceptionHandler;
-    }
-
-    private static void dlog(String message) {
-        if (DEBUG) {
-            Slog.d(TAG, message);
-        }
-    }
-
-    /**
-     * Block until all tasks that are already queued finish.  DO NOT call it while holding any lock
-     * or on the handler thread.
-     */
-    public boolean waitOnAllTasks() {
-        dlog("waitOnAllTasks: enter");
-        try {
-            // Make sure it's not holding the lock.
-            if (!mWaitThreadChecker.getAsBoolean()) {
-                return false;
-            }
-
-            // Optimize for the no-task case.
-            if (mRunningTaskCount.get() == 0) {
-                return true;
-            }
-
-            final CountDownLatch latch = new CountDownLatch(1);
-
-            addTask(latch::countDown);
-
-            for (; ; ) {
-                try {
-                    if (latch.await(1, TimeUnit.SECONDS)) {
-                        return true;
-                    }
-                    dlog("waitOnAllTasks: Task(s) still running...");
-                } catch (InterruptedException ignore) {
-                }
-            }
-        } finally {
-            dlog("waitOnAllTasks: exit");
-        }
-    }
-
-    /**
-     * Add a new task.  This operation is lock-free.
-     */
-    public void addTask(Runnable task) {
-        mRunningTaskCount.incrementAndGet();
-        mLastTaskStartTime.set(System.currentTimeMillis());
-
-        dlog("Task registered");
-
-        mRunner.accept(() -> {
-            try {
-                dlog("Task started");
-
-                task.run();
-            } catch (Throwable th) {
-                mExceptionHandler.accept(th);
-            } finally {
-                dlog("Task finished");
-                mRunningTaskCount.decrementAndGet();
-            }
-        });
-    }
-
-    public void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
-        pw.print(prefix);
-        pw.print("Pending tasks:  # running tasks: ");
-        pw.println(mRunningTaskCount.get());
-
-        pw.print(prefix);
-        pw.print("  Last task started time: ");
-        final long lastStarted = mLastTaskStartTime.get();
-        pw.print(" [");
-        pw.print(lastStarted);
-        pw.print("] ");
-        pw.println(ShortcutService.formatTime(lastStarted));
-    }
-}
diff --git a/services/core/java/com/android/server/pm/ShortcutService.java b/services/core/java/com/android/server/pm/ShortcutService.java
index a9018b3..5f8cbbf 100644
--- a/services/core/java/com/android/server/pm/ShortcutService.java
+++ b/services/core/java/com/android/server/pm/ShortcutService.java
@@ -49,7 +49,6 @@
 import android.graphics.Canvas;
 import android.graphics.RectF;
 import android.graphics.drawable.Icon;
-import android.net.Uri;
 import android.os.Binder;
 import android.os.Environment;
 import android.os.FileUtils;
@@ -82,6 +81,7 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.content.PackageMonitor;
 import com.android.internal.os.BackgroundThread;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.util.Preconditions;
@@ -122,6 +122,9 @@
 
 /**
  * TODO:
+ * - Deal with the async nature of PACKAGE_ADD.  Basically when a publisher does anything after
+ *   it's upgraded, the manager should make sure the upgrade process has been executed.
+ *
  * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
  *   -> But TypedValue.applyDimension() doesn't differentiate x and y..?
  *
@@ -301,8 +304,6 @@
 
     private final AtomicBoolean mBootCompleted = new AtomicBoolean();
 
-    private final ShortcutPendingTasks mPendingTasks;
-
     private static final int PACKAGE_MATCH_FLAGS =
             PackageManager.MATCH_DIRECT_BOOT_AWARE
                     | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
@@ -376,41 +377,16 @@
         mUsageStatsManagerInternal = Preconditions.checkNotNull(
                 LocalServices.getService(UsageStatsManagerInternal.class));
 
-        mPendingTasks = new ShortcutPendingTasks(
-                this::injectPostToHandler,
-                this::injectCheckPendingTaskWaitThread,
-                throwable -> wtf(throwable.getMessage(), throwable));
-
         if (onlyForPackageManagerApis) {
             return; // Don't do anything further.  For unit tests only.
         }
 
+        mPackageMonitor.register(context, looper, UserHandle.ALL, /* externalStorage= */ false);
+
         injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
                 | ActivityManager.UID_OBSERVER_GONE);
     }
 
-    /**
-     * Check whether {@link ShortcutPendingTasks#waitOnAllTasks()} can be called on the current
-     * thread.
-     *
-     * During unit tests, all tasks are executed synchronously which makes the lock held check would
-     * misfire, so we override this method to always return true.
-     */
-    @VisibleForTesting
-    boolean injectCheckPendingTaskWaitThread() {
-        // We shouldn't wait while holding mLock.  We should never do this so wtf().
-        if (Thread.holdsLock(mLock)) {
-            wtf("waitOnAllTasks() called while holding the lock");
-            return false;
-        }
-        // This shouldn't be called on the handler thread either.
-        if (Thread.currentThread() == mHandler.getLooper().getThread()) {
-            wtf("waitOnAllTasks() called on handler thread");
-            return false;
-        }
-        return true;
-    }
-
     void logDurationStat(int statId, long start) {
         synchronized (mStatLock) {
             mCountStats[statId]++;
@@ -1516,8 +1492,6 @@
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
-        mPendingTasks.waitOnAllTasks();
-
         final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
         final int size = newShortcuts.size();
 
@@ -1567,8 +1541,6 @@
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
-        mPendingTasks.waitOnAllTasks();
-
         final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
         final int size = newShortcuts.size();
 
@@ -1647,8 +1619,6 @@
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
-        mPendingTasks.waitOnAllTasks();
-
         final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
         final int size = newShortcuts.size();
 
@@ -1699,8 +1669,6 @@
         verifyCaller(packageName, userId);
         Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
 
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
@@ -1728,8 +1696,6 @@
         verifyCaller(packageName, userId);
         Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
 
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
@@ -1750,8 +1716,6 @@
         verifyCaller(packageName, userId);
         Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
 
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
 
@@ -1774,8 +1738,6 @@
     public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             getPackageShortcutsLocked(packageName, userId).deleteAllDynamicShortcuts();
         }
@@ -1788,9 +1750,6 @@
     public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
-
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             return getShortcutsWithQueryLocked(
                     packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
@@ -1802,9 +1761,6 @@
     public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
-
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             return getShortcutsWithQueryLocked(
                     packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
@@ -1816,9 +1772,6 @@
     public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
             @UserIdInt int userId) {
         verifyCaller(packageName, userId);
-
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             return getShortcutsWithQueryLocked(
                     packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
@@ -1848,8 +1801,6 @@
     public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             return mMaxUpdatesPerInterval
                     - getPackageShortcutsLocked(packageName, userId).getApiCallCount();
@@ -1860,8 +1811,6 @@
     public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
         verifyCaller(packageName, userId);
 
-        mPendingTasks.waitOnAllTasks();
-
         synchronized (mLock) {
             return getNextResetTimeLocked();
         }
@@ -1880,8 +1829,6 @@
     public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
         verifyCaller(packageName, userId);
 
-        mPendingTasks.waitOnAllTasks();
-
         Preconditions.checkNotNull(shortcutId);
 
         if (DEBUG) {
@@ -1914,8 +1861,6 @@
     public void resetThrottling() {
         enforceSystemOrShell();
 
-        mPendingTasks.waitOnAllTasks();
-
         resetThrottlingInner(getCallingUserId());
     }
 
@@ -1948,9 +1893,6 @@
         if (DEBUG) {
             Slog.d(TAG, "onApplicationActive: package=" + packageName + "  userid=" + userId);
         }
-
-        mPendingTasks.waitOnAllTasks();
-
         enforceResetThrottlingPermission();
         resetPackageThrottling(packageName, userId);
     }
@@ -2113,14 +2055,6 @@
                 @Nullable String packageName, @Nullable List<String> shortcutIds,
                 @Nullable ComponentName componentName,
                 int queryFlags, int userId) {
-
-            // When this method is called from onShortcutChangedInner() in LauncherApps,
-            // we're on the handler thread.  Do not try to wait on tasks.  Not waiting for pending
-            // tasks on this specific case should be fine.
-            if (Thread.currentThread() != mHandler.getLooper().getThread()) {
-                mPendingTasks.waitOnAllTasks();
-            }
-
             final ArrayList<ShortcutInfo> ret = new ArrayList<>();
             final boolean cloneKeyFieldOnly =
                     ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
@@ -2199,8 +2133,6 @@
             Preconditions.checkStringNotEmpty(packageName, "packageName");
             Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
 
-            mPendingTasks.waitOnAllTasks();
-
             synchronized (mLock) {
                 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                         .attemptToRestoreIfNeededAndSave();
@@ -2238,8 +2170,6 @@
             Preconditions.checkStringNotEmpty(packageName, "packageName");
             Preconditions.checkNotNull(shortcutIds, "shortcutIds");
 
-            mPendingTasks.waitOnAllTasks();
-
             synchronized (mLock) {
                 final ShortcutLauncher launcher =
                         getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
@@ -2260,8 +2190,6 @@
             Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
             Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
 
-            mPendingTasks.waitOnAllTasks();
-
             synchronized (mLock) {
                 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                         .attemptToRestoreIfNeededAndSave();
@@ -2292,8 +2220,6 @@
             Preconditions.checkNotNull(packageName, "packageName");
             Preconditions.checkNotNull(shortcutId, "shortcutId");
 
-            mPendingTasks.waitOnAllTasks();
-
             synchronized (mLock) {
                 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                         .attemptToRestoreIfNeededAndSave();
@@ -2318,8 +2244,6 @@
             Preconditions.checkNotNull(packageName, "packageName");
             Preconditions.checkNotNull(shortcutId, "shortcutId");
 
-            mPendingTasks.waitOnAllTasks();
-
             synchronized (mLock) {
                 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                         .attemptToRestoreIfNeededAndSave();
@@ -2380,18 +2304,9 @@
                 if (DEBUG) {
                     Slog.d(TAG, "onSystemLocaleChangedNoLock: " + mLocaleChangeSequenceNumber.get());
                 }
-                mPendingTasks.addTask(() -> handleLocaleChanged());
+                injectPostToHandler(() -> handleLocaleChanged());
             }
         }
-
-        @Override
-        public void onPackageBroadcast(Intent intent) {
-            if (DEBUG) {
-                Slog.d(TAG, "onPackageBroadcast");
-            }
-            mPendingTasks.addTask(() -> ShortcutService.this.onPackageBroadcast(
-                    new Intent(intent)));
-        }
     }
 
     void handleLocaleChanged() {
@@ -2408,49 +2323,58 @@
         }
     }
 
-    private void onPackageBroadcast(Intent intent) {
-        final int userId  = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
-        if (userId == UserHandle.USER_NULL) {
-            Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
-            return;
+    /**
+     * Package event callbacks.
+     */
+    @VisibleForTesting
+    final PackageMonitor mPackageMonitor = new PackageMonitor() {
+
+        private boolean isUserUnlocked() {
+            return mUserManager.isUserUnlocked(getChangingUserId());
         }
 
-        final String action = intent.getAction();
-
-        if (!mUserManager.isUserUnlocked(userId)) {
-            if (DEBUG) {
-                Slog.d(TAG, "Ignoring package broadcast " + action + " for locked/stopped user "
-                        + userId);
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            // clearCallingIdentity is not needed normally, but need to do it for the unit test.
+            final long token = injectClearCallingIdentity();
+            try {
+                super.onReceive(context, intent);
+            } finally {
+                injectRestoreCallingIdentity(token);
             }
-            return;
         }
 
-        final Uri intentUri = intent.getData();
-        final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart() : null;
-        if (packageName == null) {
-            Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
-            return;
+        @Override
+        public void onPackageAdded(String packageName, int uid) {
+            if (!isUserUnlocked()) return;
+            handlePackageAdded(packageName, getChangingUserId());
         }
 
-        final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
-
-        if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
-            if (replacing) {
-                handlePackageUpdateFinished(packageName, userId);
-            } else {
-                handlePackageAdded(packageName, userId);
-            }
-        } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
-            if (!replacing) {
-                handlePackageRemoved(packageName, userId);
-            }
-        } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
-            handlePackageChanged(packageName, userId);
-
-        } else if (Intent.ACTION_PACKAGE_DATA_CLEARED.equals(action)) {
-            handlePackageDataCleared(packageName, userId);
+        @Override
+        public void onPackageUpdateFinished(String packageName, int uid) {
+            if (!isUserUnlocked()) return;
+            handlePackageUpdateFinished(packageName, getChangingUserId());
         }
-    }
+
+        @Override
+        public void onPackageRemoved(String packageName, int uid) {
+            if (!isUserUnlocked()) return;
+            handlePackageRemoved(packageName, getChangingUserId());
+        }
+
+        @Override
+        public void onPackageDataCleared(String packageName, int uid) {
+            if (!isUserUnlocked()) return;
+            handlePackageDataCleared(packageName, getChangingUserId());
+        }
+
+        @Override
+        public boolean onPackageChanged(String packageName, int uid, String[] components) {
+            if (!isUserUnlocked()) return false;
+            handlePackageChanged(packageName, getChangingUserId());
+            return false; // We don't need to receive onSomePackagesChanged(), so just false.
+        }
+    };
 
     /**
      * Called when a user is unlocked.
@@ -3097,9 +3021,6 @@
                 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
             }
 
-            pw.println();
-            mPendingTasks.dump(pw, "  ");
-
             for (int i = 0; i < mUsers.size(); i++) {
                 pw.println();
                 mUsers.valueAt(i).dump(pw, "  ");
@@ -3148,8 +3069,6 @@
 
         enforceShell();
 
-        mPendingTasks.waitOnAllTasks();
-
         final int status = (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver);
 
         resultReceiver.send(status, null);
@@ -3176,6 +3095,10 @@
                     case "--user":
                         if (takeUser) {
                             mUserId = UserHandle.parseUserArg(getNextArgRequired());
+                            if (!mUserManager.isUserUnlocked(mUserId)) {
+                                throw new CommandException(
+                                        "User " + mUserId + " is not running or locked");
+                            }
                             break;
                         }
                         // fallthrough
@@ -3501,7 +3424,6 @@
 
     @VisibleForTesting
     ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
-        mPendingTasks.waitOnAllTasks();
         synchronized (mLock) {
             final ShortcutUser user = mUsers.get(userId);
             if (user == null) return null;
@@ -3512,12 +3434,8 @@
 
     @VisibleForTesting
     ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
-        mPendingTasks.waitOnAllTasks();
         synchronized (mLock) {
-            final ShortcutUser user = mUsers.get(userId);
-            if (user == null) return null;
-
-            final ShortcutPackage pkg = user.getAllPackagesForTest().get(packageName);
+            final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
             if (pkg == null) return null;
 
             return pkg.findShortcutById(shortcutId);
@@ -3552,12 +3470,4 @@
             forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));
         }
     }
-
-    ShortcutPendingTasks getPendingTasksForTest() {
-        return mPendingTasks;
-    }
-
-    Object getLockForTest() {
-        return mLock;
-    }
 }
diff --git a/services/tests/servicestests/src/com/android/server/pm/BaseShortcutManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/BaseShortcutManagerTest.java
index 01c19d0..1be57bc 100644
--- a/services/tests/servicestests/src/com/android/server/pm/BaseShortcutManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/BaseShortcutManagerTest.java
@@ -404,11 +404,6 @@
             // During tests, WTF is fatal.
             fail(message + "  exception: " + th + "\n" + Log.getStackTraceString(th));
         }
-
-        @Override
-        boolean injectCheckPendingTaskWaitThread() {
-            return true;
-        }
     }
 
     /** ShortcutManager with injection override methods. */
@@ -853,8 +848,6 @@
 
     protected void shutdownServices() {
         if (mService != null) {
-            mService.getPendingTasksForTest().waitOnAllTasks();
-
             // Flush all the unsaved data from the previous instance.
             mService.saveDirtyInfo();
 
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
index c7673d1..bf6c2ff 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest1.java
@@ -62,7 +62,6 @@
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
 
 import android.Manifest.permission;
 import android.app.ActivityManager;
@@ -1298,7 +1297,8 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_3);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
             assertTrue(mManager.setDynamicShortcuts(list(
@@ -1316,7 +1316,8 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
+        mService.mPackageMonitor.onReceive(getTestContext(),
+                genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
             assertTrue(mManager.setDynamicShortcuts(list(
@@ -2814,7 +2815,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                     R.xml.shortcut_2);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mInternal.onPackageBroadcast(
+            mService.mPackageMonitor.onReceive(getTestContext(),
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
                 .areAllManifest()
@@ -2851,7 +2852,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_0);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+        mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         assertForLauncherCallback(mLauncherApps, () -> {
@@ -3471,7 +3472,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -3488,7 +3489,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -3850,7 +3851,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
             assertWith(getCallerShortcuts())
@@ -3890,7 +3891,7 @@
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
 
         uninstallPackage(USER_0, CALLING_PACKAGE_1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageDeleteIntent(CALLING_PACKAGE_1, USER_0));
 
         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
@@ -3910,7 +3911,7 @@
         mRunningUsers.put(USER_10, true);
 
         uninstallPackage(USER_10, CALLING_PACKAGE_2);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageDeleteIntent(CALLING_PACKAGE_2, USER_10));
 
         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
@@ -4001,7 +4002,7 @@
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_2, USER_10));
         assertTrue(bitmapDirectoryExists(CALLING_PACKAGE_3, USER_10));
 
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageDataClear(CALLING_PACKAGE_1, USER_0));
 
         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
@@ -4020,7 +4021,7 @@
 
         mRunningUsers.put(USER_10, true);
 
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageDataClear(CALLING_PACKAGE_2, USER_10));
 
         assertNull(mService.getPackageShortcutForTest(CALLING_PACKAGE_1, "s1", USER_0));
@@ -4047,7 +4048,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4068,7 +4069,7 @@
         });
 
         // Clear data
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageDataClear(CALLING_PACKAGE_1, USER_10));
 
         // Only manifest shortcuts will remain, and are no longer pinned.
@@ -4133,9 +4134,9 @@
         reset(c0);
         reset(c10);
 
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_10));
 
         waitOnMainThread();
@@ -4156,7 +4157,7 @@
         updatePackageVersion(CALLING_PACKAGE_1, 1);
 
         // Then send the broadcast, to only user-0.
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
 
         waitOnMainThread();
@@ -4221,7 +4222,7 @@
         updatePackageVersion(CALLING_PACKAGE_2, 10);
 
         // Then send the broadcast, to only user-0.
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageUpdateIntent(CALLING_PACKAGE_2, USER_0));
         mService.handleUnlockUser(USER_10);
 
@@ -4245,7 +4246,7 @@
         updatePackageVersion(CALLING_PACKAGE_3, 100);
 
         // Then send the broadcast, to only user-0.
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageUpdateIntent(CALLING_PACKAGE_3, USER_0));
         mService.handleUnlockUser(USER_10);
 
@@ -4327,7 +4328,7 @@
 
         // Update the package.
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -4356,7 +4357,7 @@
         mRunningUsers.put(USER_10, true);
 
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4388,7 +4389,7 @@
         });
 
         // First, no changes.
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4411,7 +4412,7 @@
 
         // Disable activity 1
         mEnabledActivityChecker = (activity, userId) -> !ACTIVITY1.equals(activity);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4431,7 +4432,7 @@
         // Re-enable activity 1.
         // Manifest shortcuts will be re-published, but dynamic ones are not.
         mEnabledActivityChecker = (activity, userId) -> true;
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4455,7 +4456,7 @@
         // Disable activity 2
         // Because "ms1-alt" and "s2" are both pinned, they will remain, but disabled.
         mEnabledActivityChecker = (activity, userId) -> !ACTIVITY2.equals(activity);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageChangedIntent(CALLING_PACKAGE_1, USER_10));
 
         runWithCaller(CALLING_PACKAGE_1, USER_10, () -> {
@@ -4518,7 +4519,7 @@
         setCaller(LAUNCHER_1, USER_0);
         assertForLauncherCallback(mLauncherApps, () -> {
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mInternal.onPackageBroadcast(
+                    mService.mPackageMonitor.onReceive(getTestContext(),
                     genPackageUpdateIntent(CALLING_PACKAGE_1, USER_0));
         }).assertCallbackCalledForPackageAndUser(CALLING_PACKAGE_1, HANDLE_USER_0)
                 // Make sure the launcher gets callbacks.
@@ -5160,7 +5161,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+        mService.mPackageMonitor.onReceive(mServiceContext,
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Pin from launcher 1.
@@ -5173,7 +5174,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+        mService.mPackageMonitor.onReceive(mServiceContext,
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Make sure the manifest shortcuts have been published.
@@ -5634,7 +5635,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5655,7 +5656,7 @@
                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_2, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5692,7 +5693,7 @@
                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5729,7 +5730,7 @@
         mRunningUsers.put(USER_10, false);
         mUnlockedUsers.put(USER_10, false);
 
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
             assertEmpty(mManager.getManifestShortcuts());
@@ -5739,7 +5740,7 @@
         // Try again, but the user is locked, so still ignored.
         mRunningUsers.put(USER_10, true);
 
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
             assertEmpty(mManager.getManifestShortcuts());
@@ -5750,7 +5751,7 @@
         mUnlockedUsers.put(USER_10, true);
 
         // Send PACKAGE_ADD broadcast to have Package 2 on user-10 publish manifest shortcuts.
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_10));
 
         runWithCaller(CALLING_PACKAGE_2, USER_10, () -> {
@@ -5791,7 +5792,7 @@
                 R.xml.shortcut_5_reverse);
 
         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
 
         runWithCaller(CALLING_PACKAGE_2, USER_0, () -> {
@@ -5819,7 +5820,7 @@
                 new ComponentName(CALLING_PACKAGE_2, ShortcutActivity2.class.getName()),
                 R.xml.shortcut_0);
         updatePackageLastUpdateTime(CALLING_PACKAGE_2, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_2, USER_0));
 
         // No manifest shortcuts, and pinned ones are disabled.
@@ -5850,7 +5851,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5865,7 +5866,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5880,7 +5881,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_3);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -5896,7 +5897,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_4);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5924,7 +5925,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -5962,7 +5963,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_error_4);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Make sure 3, 4 and 5 still exist but disabled.
@@ -6010,7 +6011,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -6115,7 +6116,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6212,7 +6213,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -6231,7 +6232,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1_disable);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Because shortcut 1 wasn't pinned, it'll just go away.
@@ -6252,7 +6253,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Only the valid one is published.
@@ -6275,7 +6276,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1_disable);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         // Because shortcut 1 was pinned, it'll still exist as pinned, but disabled.
@@ -6308,7 +6309,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2_duplicate);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6338,7 +6339,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6410,7 +6411,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6460,7 +6461,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_2);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(LAUNCHER_1, USER_0, () -> {
@@ -6471,7 +6472,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_1);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6553,7 +6554,7 @@
                 new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                 R.xml.shortcut_5);
         updatePackageVersion(CALLING_PACKAGE_1, 1);
-        mInternal.onPackageBroadcast(
+                mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
         runWithCaller(CALLING_PACKAGE_1, USER_0, () -> {
@@ -6623,7 +6624,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                     R.xml.shortcut_2);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mInternal.onPackageBroadcast(
+                    mService.mPackageMonitor.onReceive(getTestContext(),
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(2, mManager.getManifestShortcuts().size());
 
@@ -6749,7 +6750,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                     R.xml.shortcut_2);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mInternal.onPackageBroadcast(
+                    mService.mPackageMonitor.onReceive(getTestContext(),
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
 
             assertEquals(2, mManager.getManifestShortcuts().size());
@@ -6898,7 +6899,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity.class.getName()),
                     R.xml.shortcut_1);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mInternal.onPackageBroadcast(
+                    mService.mPackageMonitor.onReceive(getTestContext(),
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(1, mManager.getManifestShortcuts().size());
 
@@ -6918,7 +6919,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
                     R.xml.shortcut_1_alt);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mInternal.onPackageBroadcast(
+                    mService.mPackageMonitor.onReceive(getTestContext(),
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(3, mManager.getManifestShortcuts().size());
 
@@ -6938,7 +6939,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
                     R.xml.shortcut_5_alt); // manifest has 5, but max is 3, so a2 will have 3.
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mInternal.onPackageBroadcast(
+                    mService.mPackageMonitor.onReceive(getTestContext(),
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(5, mManager.getManifestShortcuts().size());
 
@@ -6957,7 +6958,7 @@
                     new ComponentName(CALLING_PACKAGE_1, ShortcutActivity2.class.getName()),
                     R.xml.shortcut_0);
             updatePackageVersion(CALLING_PACKAGE_1, 1);
-            mInternal.onPackageBroadcast(
+                    mService.mPackageMonitor.onReceive(getTestContext(),
                     genPackageAddIntent(CALLING_PACKAGE_1, USER_0));
             assertEquals(0, mManager.getManifestShortcuts().size());
 
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest3.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest3.java
index fcf7ea2..eb4db7a 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest3.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest3.java
@@ -66,7 +66,7 @@
     private void publishManifestShortcuts(ComponentName activity, int resId) {
         addManifestShortcutResource(activity, resId);
         updatePackageVersion(CALLING_PACKAGE, 1);
-        mInternal.onPackageBroadcast(
+        mService.mPackageMonitor.onReceive(getTestContext(),
                 genPackageAddIntent(CALLING_PACKAGE, USER_0));
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutPendingTasksTest.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutPendingTasksTest.java
deleted file mode 100644
index bf1ed98..0000000
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutPendingTasksTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.server.pm;
-
-import android.os.Handler;
-import android.os.Looper;
-import android.test.MoreAsserts;
-import android.test.suitebuilder.annotation.LargeTest;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * Run with:
- adb install \
-   -r -g ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
- adb shell am instrument -e class com.android.server.pm.ShortcutPendingTasksTest \
-   -w com.android.frameworks.servicestests
- */
-@LargeTest
-public class ShortcutPendingTasksTest extends BaseShortcutManagerTest {
-    public void testAll() {
-        final AtomicReference<Throwable> thrown = new AtomicReference<>();
-
-        final AtomicBoolean threadCheckerResult = new AtomicBoolean(true);
-
-        final Handler handler = new Handler(Looper.getMainLooper());
-
-        final ShortcutPendingTasks tasks = new ShortcutPendingTasks(
-                handler::post,
-                threadCheckerResult::get,
-                thrown::set);
-
-        // No pending tasks, shouldn't block.
-        assertTrue(tasks.waitOnAllTasks());
-
-        final AtomicInteger counter = new AtomicInteger();
-
-        // Run one task.
-        tasks.addTask(() -> {
-            try {
-                Thread.sleep(1000);
-            } catch (InterruptedException ignore) {
-            }
-            counter.incrementAndGet();
-        });
-
-        assertTrue(tasks.waitOnAllTasks());
-        assertNull(thrown.get());
-
-        assertEquals(1, counter.get());
-
-        // Run 3 tasks.
-
-        // We use this ID to make sure only one task can run at the same time.
-        final AtomicInteger currentTaskId = new AtomicInteger();
-
-        tasks.addTask(() -> {
-            currentTaskId.set(1);
-            try {
-                Thread.sleep(500);
-            } catch (InterruptedException ignore) {
-            }
-            counter.incrementAndGet();
-            assertEquals(1, currentTaskId.get());
-        });
-        tasks.addTask(() -> {
-            currentTaskId.set(2);
-            try {
-                Thread.sleep(500);
-            } catch (InterruptedException ignore) {
-            }
-            counter.incrementAndGet();
-            assertEquals(2, currentTaskId.get());
-        });
-        tasks.addTask(() -> {
-            currentTaskId.set(3);
-            try {
-                Thread.sleep(500);
-            } catch (InterruptedException ignore) {
-            }
-            counter.incrementAndGet();
-            assertEquals(3, currentTaskId.get());
-        });
-
-        assertTrue(tasks.waitOnAllTasks());
-        assertNull(thrown.get());
-        assertEquals(4, counter.get());
-
-        // No tasks running, shouldn't block.
-        assertTrue(tasks.waitOnAllTasks());
-        assertNull(thrown.get());
-        assertEquals(4, counter.get());
-
-        // Now the thread checker returns false, so waitOnAllTasks() returns false.
-        threadCheckerResult.set(false);
-        assertFalse(tasks.waitOnAllTasks());
-
-        threadCheckerResult.set(true);
-
-        // Make sure the exception handler is called.
-        tasks.addTask(() -> {
-            throw new RuntimeException("XXX");
-        });
-        assertTrue(tasks.waitOnAllTasks());
-        assertNotNull(thrown.get());
-        MoreAsserts.assertContainsRegex("XXX", thrown.get().getMessage());
-    }
-}