2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package com.android.server.pm;
18 import android.annotation.NonNull;
19 import android.annotation.Nullable;
20 import android.annotation.UserIdInt;
21 import android.content.ComponentName;
22 import android.content.Intent;
23 import android.content.pm.PackageInfo;
24 import android.content.pm.ShortcutInfo;
25 import android.content.res.Resources;
26 import android.os.Bundle;
27 import android.os.PersistableBundle;
28 import android.text.format.Formatter;
29 import android.util.ArrayMap;
30 import android.util.ArraySet;
31 import android.util.Log;
32 import android.util.Slog;
34 import com.android.internal.annotations.VisibleForTesting;
35 import com.android.internal.util.Preconditions;
36 import com.android.internal.util.XmlUtils;
37 import com.android.server.pm.ShortcutService.ShortcutOperation;
38 import com.android.server.pm.ShortcutService.Stats;
40 import org.json.JSONException;
41 import org.json.JSONObject;
42 import org.xmlpull.v1.XmlPullParser;
43 import org.xmlpull.v1.XmlPullParserException;
44 import org.xmlpull.v1.XmlSerializer;
47 import java.io.IOException;
48 import java.io.PrintWriter;
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Comparator;
52 import java.util.List;
54 import java.util.function.Predicate;
57 * Package information used by {@link ShortcutService}.
58 * User information used by {@link ShortcutService}.
60 * All methods should be guarded by {@code #mShortcutUser.mService.mLock}.
62 class ShortcutPackage extends ShortcutPackageItem {
63 private static final String TAG = ShortcutService.TAG;
64 private static final String TAG_VERIFY = ShortcutService.TAG + ".verify";
66 static final String TAG_ROOT = "package";
67 private static final String TAG_INTENT_EXTRAS_LEGACY = "intent-extras";
68 private static final String TAG_INTENT = "intent";
69 private static final String TAG_EXTRAS = "extras";
70 private static final String TAG_SHORTCUT = "shortcut";
71 private static final String TAG_CATEGORIES = "categories";
73 private static final String ATTR_NAME = "name";
74 private static final String ATTR_CALL_COUNT = "call-count";
75 private static final String ATTR_LAST_RESET = "last-reset";
76 private static final String ATTR_ID = "id";
77 private static final String ATTR_ACTIVITY = "activity";
78 private static final String ATTR_TITLE = "title";
79 private static final String ATTR_TITLE_RES_ID = "titleid";
80 private static final String ATTR_TITLE_RES_NAME = "titlename";
81 private static final String ATTR_TEXT = "text";
82 private static final String ATTR_TEXT_RES_ID = "textid";
83 private static final String ATTR_TEXT_RES_NAME = "textname";
84 private static final String ATTR_DISABLED_MESSAGE = "dmessage";
85 private static final String ATTR_DISABLED_MESSAGE_RES_ID = "dmessageid";
86 private static final String ATTR_DISABLED_MESSAGE_RES_NAME = "dmessagename";
87 private static final String ATTR_INTENT_LEGACY = "intent";
88 private static final String ATTR_INTENT_NO_EXTRA = "intent-base";
89 private static final String ATTR_RANK = "rank";
90 private static final String ATTR_TIMESTAMP = "timestamp";
91 private static final String ATTR_FLAGS = "flags";
92 private static final String ATTR_ICON_RES_ID = "icon-res";
93 private static final String ATTR_ICON_RES_NAME = "icon-resname";
94 private static final String ATTR_BITMAP_PATH = "bitmap-path";
96 private static final String NAME_CATEGORIES = "categories";
98 private static final String TAG_STRING_ARRAY_XMLUTILS = "string-array";
99 private static final String ATTR_NAME_XMLUTILS = "name";
101 private static final String KEY_DYNAMIC = "dynamic";
102 private static final String KEY_MANIFEST = "manifest";
103 private static final String KEY_PINNED = "pinned";
104 private static final String KEY_BITMAPS = "bitmaps";
105 private static final String KEY_BITMAP_BYTES = "bitmapBytes";
108 * All the shortcuts from the package, keyed on IDs.
110 final private ArrayMap<String, ShortcutInfo> mShortcuts = new ArrayMap<>();
113 * # of times the package has called rate-limited APIs.
115 private int mApiCallCount;
118 * When {@link #mApiCallCount} was reset last time.
120 private long mLastResetTime;
122 private final int mPackageUid;
124 private long mLastKnownForegroundElapsedTime;
126 private ShortcutPackage(ShortcutUser shortcutUser,
127 int packageUserId, String packageName, ShortcutPackageInfo spi) {
128 super(shortcutUser, packageUserId, packageName,
129 spi != null ? spi : ShortcutPackageInfo.newEmpty());
131 mPackageUid = shortcutUser.mService.injectGetPackageUid(packageName, packageUserId);
134 public ShortcutPackage(ShortcutUser shortcutUser, int packageUserId, String packageName) {
135 this(shortcutUser, packageUserId, packageName, null);
139 public int getOwnerUserId() {
140 // For packages, always owner user == package user.
141 return getPackageUserId();
144 public int getPackageUid() {
149 * Called when a shortcut is about to be published. At this point we know the publisher
151 * exists (as opposed to Launcher trying to fetch shortcuts from a non-existent package), so
152 * we do some initialization for the package.
154 private void ensurePackageVersionInfo() {
155 // Make sure we have the version code for the app. We need the version code in
156 // handlePackageUpdated().
157 if (getPackageInfo().getVersionCode() < 0) {
158 final ShortcutService s = mShortcutUser.mService;
160 final PackageInfo pi = s.getPackageInfo(getPackageName(), getOwnerUserId());
162 if (ShortcutService.DEBUG) {
163 Slog.d(TAG, String.format("Package %s version = %d", getPackageName(),
166 getPackageInfo().updateVersionInfo(pi);
167 s.scheduleSaveUser(getOwnerUserId());
173 public Resources getPackageResources() {
174 return mShortcutUser.mService.injectGetResourcesForApplicationAsUser(
175 getPackageName(), getPackageUserId());
179 protected void onRestoreBlocked() {
180 // Can't restore due to version/signature mismatch. Remove all shortcuts.
185 protected void onRestored() {
186 // Because some launchers may not have been restored (e.g. allowBackup=false),
187 // we need to re-calculate the pinned shortcuts.
188 refreshPinnedFlags();
192 * Note this does *not* provide a correct view to the calling launcher.
195 public ShortcutInfo findShortcutById(String id) {
196 return mShortcuts.get(id);
199 private void ensureNotImmutable(@Nullable ShortcutInfo shortcut) {
200 if (shortcut != null && shortcut.isImmutable()) {
201 throw new IllegalArgumentException(
202 "Manifest shortcut ID=" + shortcut.getId()
203 + " may not be manipulated via APIs");
207 private void ensureNotImmutable(@NonNull String id) {
208 ensureNotImmutable(mShortcuts.get(id));
211 public void ensureImmutableShortcutsNotIncludedWithIds(@NonNull List<String> shortcutIds) {
212 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
213 ensureNotImmutable(shortcutIds.get(i));
217 public void ensureImmutableShortcutsNotIncluded(@NonNull List<ShortcutInfo> shortcuts) {
218 for (int i = shortcuts.size() - 1; i >= 0; i--) {
219 ensureNotImmutable(shortcuts.get(i).getId());
223 private ShortcutInfo deleteShortcutInner(@NonNull String id) {
224 final ShortcutInfo shortcut = mShortcuts.remove(id);
225 if (shortcut != null) {
226 mShortcutUser.mService.removeIcon(getPackageUserId(), shortcut);
227 shortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_PINNED
228 | ShortcutInfo.FLAG_MANIFEST);
233 private void addShortcutInner(@NonNull ShortcutInfo newShortcut) {
234 final ShortcutService s = mShortcutUser.mService;
236 deleteShortcutInner(newShortcut.getId());
238 // Extract Icon and update the icon res ID and the bitmap path.
239 s.saveIconAndFixUpShortcut(getPackageUserId(), newShortcut);
240 s.fixUpShortcutResourceNamesAndValues(newShortcut);
241 mShortcuts.put(newShortcut.getId(), newShortcut);
245 * Add a shortcut, or update one with the same ID, with taking over existing flags.
247 * It checks the max number of dynamic shortcuts.
249 public void addOrUpdateDynamicShortcut(@NonNull ShortcutInfo newShortcut) {
251 Preconditions.checkArgument(newShortcut.isEnabled(),
252 "add/setDynamicShortcuts() cannot publish disabled shortcuts");
254 ensurePackageVersionInfo();
256 newShortcut.addFlags(ShortcutInfo.FLAG_DYNAMIC);
258 final ShortcutInfo oldShortcut = mShortcuts.get(newShortcut.getId());
260 final boolean wasPinned;
262 if (oldShortcut == null) {
265 // It's an update case.
266 // Make sure the target is updatable. (i.e. should be mutable.)
267 oldShortcut.ensureUpdatableWith(newShortcut);
269 wasPinned = oldShortcut.isPinned();
272 // If it was originally pinned, the new one should be pinned too.
274 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
277 addShortcutInner(newShortcut);
281 * Remove all shortcuts that aren't pinned nor dynamic.
283 private void removeOrphans() {
284 ArrayList<String> removeList = null; // Lazily initialize.
286 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
287 final ShortcutInfo si = mShortcuts.valueAt(i);
289 if (si.isAlive()) continue;
291 if (removeList == null) {
292 removeList = new ArrayList<>();
294 removeList.add(si.getId());
296 if (removeList != null) {
297 for (int i = removeList.size() - 1; i >= 0; i--) {
298 deleteShortcutInner(removeList.get(i));
304 * Remove all dynamic shortcuts.
306 public void deleteAllDynamicShortcuts() {
307 final long now = mShortcutUser.mService.injectCurrentTimeMillis();
309 boolean changed = false;
310 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
311 final ShortcutInfo si = mShortcuts.valueAt(i);
312 if (si.isDynamic()) {
315 si.setTimestamp(now);
316 si.clearFlags(ShortcutInfo.FLAG_DYNAMIC);
317 si.setRank(0); // It may still be pinned, so clear the rank.
326 * Remove a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
327 * is pinned, it'll remain as a pinned shortcut, and is still enabled.
329 * @return true if it's actually removed because it wasn't pinned, or false if it's still
332 public boolean deleteDynamicWithId(@NonNull String shortcutId) {
333 final ShortcutInfo removed = deleteOrDisableWithId(
334 shortcutId, /* disable =*/ false, /* overrideImmutable=*/ false);
335 return removed == null;
339 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
340 * is pinned, it'll remain as a pinned shortcut, but will be disabled.
342 * @return true if it's actually removed because it wasn't pinned, or false if it's still
345 private boolean disableDynamicWithId(@NonNull String shortcutId) {
346 final ShortcutInfo disabled = deleteOrDisableWithId(
347 shortcutId, /* disable =*/ true, /* overrideImmutable=*/ false);
348 return disabled == null;
352 * Disable a dynamic shortcut by ID. It'll be removed from the dynamic set, but if the shortcut
353 * is pinned, it'll remain as a pinned shortcut but will be disabled.
355 public void disableWithId(@NonNull String shortcutId, String disabledMessage,
356 int disabledMessageResId, boolean overrideImmutable) {
357 final ShortcutInfo disabled = deleteOrDisableWithId(shortcutId, /* disable =*/ true,
360 if (disabled != null) {
361 if (disabledMessage != null) {
362 disabled.setDisabledMessage(disabledMessage);
363 } else if (disabledMessageResId != 0) {
364 disabled.setDisabledMessageResId(disabledMessageResId);
366 mShortcutUser.mService.fixUpShortcutResourceNamesAndValues(disabled);
372 private ShortcutInfo deleteOrDisableWithId(@NonNull String shortcutId, boolean disable,
373 boolean overrideImmutable) {
374 final ShortcutInfo oldShortcut = mShortcuts.get(shortcutId);
376 if (oldShortcut == null || !oldShortcut.isEnabled()) {
377 return null; // Doesn't exist or already disabled.
379 if (!overrideImmutable) {
380 ensureNotImmutable(oldShortcut);
382 if (oldShortcut.isPinned()) {
384 oldShortcut.setRank(0);
385 oldShortcut.clearFlags(ShortcutInfo.FLAG_DYNAMIC | ShortcutInfo.FLAG_MANIFEST);
387 oldShortcut.addFlags(ShortcutInfo.FLAG_DISABLED);
389 oldShortcut.setTimestamp(mShortcutUser.mService.injectCurrentTimeMillis());
393 deleteShortcutInner(shortcutId);
398 public void enableWithId(@NonNull String shortcutId) {
399 final ShortcutInfo shortcut = mShortcuts.get(shortcutId);
400 if (shortcut != null) {
401 ensureNotImmutable(shortcut);
402 shortcut.clearFlags(ShortcutInfo.FLAG_DISABLED);
407 * Called after a launcher updates the pinned set. For each shortcut in this package,
408 * set FLAG_PINNED if any launcher has pinned it. Otherwise, clear it.
410 * <p>Then remove all shortcuts that are not dynamic and no longer pinned either.
412 public void refreshPinnedFlags() {
413 // First, un-pin all shortcuts
414 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
415 mShortcuts.valueAt(i).clearFlags(ShortcutInfo.FLAG_PINNED);
418 // Then, for the pinned set for each launcher, set the pin flag one by one.
419 mShortcutUser.mService.getUserShortcutsLocked(getPackageUserId())
420 .forAllLaunchers(launcherShortcuts -> {
421 final ArraySet<String> pinned = launcherShortcuts.getPinnedShortcutIds(
422 getPackageName(), getPackageUserId());
424 if (pinned == null || pinned.size() == 0) {
427 for (int i = pinned.size() - 1; i >= 0; i--) {
428 final String id = pinned.valueAt(i);
429 final ShortcutInfo si = mShortcuts.get(id);
431 // This happens if a launcher pinned shortcuts from this package, then backup&
432 // restored, but this package doesn't allow backing up.
433 // In that case the launcher ends up having a dangling pinned shortcuts.
434 // That's fine, when the launcher is restored, we'll fix it.
437 si.addFlags(ShortcutInfo.FLAG_PINNED);
441 // Lastly, remove the ones that are no longer pinned nor dynamic.
446 * Number of calls that the caller has made, since the last reset.
448 * <p>This takes care of the resetting the counter for foreground apps as well as after
451 public int getApiCallCount() {
452 final ShortcutService s = mShortcutUser.mService;
454 // Reset the counter if:
455 // - the package is in foreground now.
456 // - the package is *not* in foreground now, but was in foreground at some point
457 // since the previous time it had been.
458 if (s.isUidForegroundLocked(mPackageUid)
459 || mLastKnownForegroundElapsedTime
460 < s.getUidLastForegroundElapsedTimeLocked(mPackageUid)) {
461 mLastKnownForegroundElapsedTime = s.injectElapsedRealtime();
465 // Note resetThrottlingIfNeeded() and resetRateLimiting() will set 0 to mApiCallCount,
466 // but we just can't return 0 at this point, because we may have to update
469 final long last = s.getLastResetTimeLocked();
471 final long now = s.injectCurrentTimeMillis();
472 if (ShortcutService.isClockValid(now) && mLastResetTime > now) {
473 Slog.w(TAG, "Clock rewound");
475 mLastResetTime = now;
477 return mApiCallCount;
480 // If not reset yet, then reset.
481 if (mLastResetTime < last) {
482 if (ShortcutService.DEBUG) {
483 Slog.d(TAG, String.format("%s: last reset=%d, now=%d, last=%d: resetting",
484 getPackageName(), mLastResetTime, now, last));
487 mLastResetTime = last;
489 return mApiCallCount;
493 * If the caller app hasn't been throttled yet, increment {@link #mApiCallCount}
494 * and return true. Otherwise just return false.
496 * <p>This takes care of the resetting the counter for foreground apps as well as after
497 * locale changes, which is done internally by {@link #getApiCallCount}.
499 public boolean tryApiCall() {
500 final ShortcutService s = mShortcutUser.mService;
502 if (getApiCallCount() >= s.mMaxUpdatesPerInterval) {
506 s.scheduleSaveUser(getOwnerUserId());
510 public void resetRateLimiting() {
511 if (ShortcutService.DEBUG) {
512 Slog.d(TAG, "resetRateLimiting: " + getPackageName());
514 if (mApiCallCount > 0) {
516 mShortcutUser.mService.scheduleSaveUser(getOwnerUserId());
520 public void resetRateLimitingForCommandLineNoSaving() {
526 * Find all shortcuts that match {@code query}.
528 public void findAll(@NonNull List<ShortcutInfo> result,
529 @Nullable Predicate<ShortcutInfo> query, int cloneFlag) {
530 findAll(result, query, cloneFlag, null, 0);
534 * Find all shortcuts that match {@code query}.
536 * This will also provide a "view" for each launcher -- a non-dynamic shortcut that's not pinned
537 * by the calling launcher will not be included in the result, and also "isPinned" will be
538 * adjusted for the caller too.
540 public void findAll(@NonNull List<ShortcutInfo> result,
541 @Nullable Predicate<ShortcutInfo> query, int cloneFlag,
542 @Nullable String callingLauncher, int launcherUserId) {
543 if (getPackageInfo().isShadow()) {
544 // Restored and the app not installed yet, so don't return any.
548 final ShortcutService s = mShortcutUser.mService;
550 // Set of pinned shortcuts by the calling launcher.
551 final ArraySet<String> pinnedByCallerSet = (callingLauncher == null) ? null
552 : s.getLauncherShortcutsLocked(callingLauncher, getPackageUserId(), launcherUserId)
553 .getPinnedShortcutIds(getPackageName(), getPackageUserId());
555 for (int i = 0; i < mShortcuts.size(); i++) {
556 final ShortcutInfo si = mShortcuts.valueAt(i);
558 // Need to adjust PINNED flag depending on the caller.
559 // Basically if the caller is a launcher (callingLauncher != null) and the launcher
560 // isn't pinning it, then we need to clear PINNED for this caller.
561 final boolean isPinnedByCaller = (callingLauncher == null)
562 || ((pinnedByCallerSet != null) && pinnedByCallerSet.contains(si.getId()));
564 if (si.isFloating()) {
565 if (!isPinnedByCaller) {
569 final ShortcutInfo clone = si.clone(cloneFlag);
571 // Fix up isPinned for the caller. Note we need to do it before the "test" callback,
572 // since it may check isPinned.
573 if (!isPinnedByCaller) {
574 clone.clearFlags(ShortcutInfo.FLAG_PINNED);
576 if (query == null || query.test(clone)) {
582 public void resetThrottling() {
587 * Return the filenames (excluding path names) of icon bitmap files from this package.
589 public ArraySet<String> getUsedBitmapFiles() {
590 final ArraySet<String> usedFiles = new ArraySet<>(mShortcuts.size());
592 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
593 final ShortcutInfo si = mShortcuts.valueAt(i);
594 if (si.getBitmapPath() != null) {
595 usedFiles.add(getFileName(si.getBitmapPath()));
601 private static String getFileName(@NonNull String path) {
602 final int sep = path.lastIndexOf(File.separatorChar);
606 return path.substring(sep + 1);
611 * @return false if any of the target activities are no longer enabled.
613 private boolean areAllActivitiesStillEnabled() {
614 if (mShortcuts.size() == 0) {
617 final ShortcutService s = mShortcutUser.mService;
619 // Normally the number of target activities is 1 or so, so no need to use a complex
620 // structure like a set.
621 final ArrayList<ComponentName> checked = new ArrayList<>(4);
623 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
624 final ShortcutInfo si = mShortcuts.valueAt(i);
625 final ComponentName activity = si.getActivity();
627 if (checked.contains(activity)) {
628 continue; // Already checked.
630 checked.add(activity);
632 if (!s.injectIsActivityEnabledAndExported(activity, getOwnerUserId())) {
640 * Called when the package may be added or updated, or its activities may be disabled, and
641 * if so, rescan the package and do the necessary stuff.
644 * - Publish manifest shortcuts.
647 * - Re-publish manifest shortcuts.
648 * - If there are shortcuts with resources (icons or strings), update their timestamps.
649 * - Disable shortcuts whose target activities are disabled.
651 * @return TRUE if any shortcuts have been changed.
653 public boolean rescanPackageIfNeeded(boolean isNewApp, boolean forceRescan) {
654 final ShortcutService s = mShortcutUser.mService;
655 final long start = s.injectElapsedRealtime();
657 final PackageInfo pi;
659 pi = mShortcutUser.mService.getPackageInfo(
660 getPackageName(), getPackageUserId());
662 return false; // Shouldn't happen.
665 if (!isNewApp && !forceRescan) {
666 // Return if the package hasn't changed, ie:
667 // - version code hasn't change
668 // - lastUpdateTime hasn't change
669 // - all target activities are still enabled.
670 if ((getPackageInfo().getVersionCode() == pi.versionCode)
671 && (getPackageInfo().getLastUpdateTime() == pi.lastUpdateTime)
672 && areAllActivitiesStillEnabled()) {
677 s.logDurationStat(Stats.PACKAGE_UPDATE_CHECK, start);
680 // Now prepare to publish manifest shortcuts.
681 List<ShortcutInfo> newManifestShortcutList = null;
683 newManifestShortcutList = ShortcutParser.parseShortcuts(mShortcutUser.mService,
684 getPackageName(), getPackageUserId());
685 } catch (IOException|XmlPullParserException e) {
686 Slog.e(TAG, "Failed to load shortcuts from AndroidManifest.xml.", e);
688 final int manifestShortcutSize = newManifestShortcutList == null ? 0
689 : newManifestShortcutList.size();
690 if (ShortcutService.DEBUG) {
691 Slog.d(TAG, String.format("Package %s has %d manifest shortcut(s)",
692 getPackageName(), manifestShortcutSize));
694 if (isNewApp && (manifestShortcutSize == 0)) {
695 // If it's a new app, and it doesn't have manifest shortcuts, then nothing to do.
697 // If it's an update, then it may already have manifest shortcuts, which need to be
701 if (ShortcutService.DEBUG) {
702 Slog.d(TAG, String.format("Package %s %s, version %d -> %d", getPackageName(),
703 (isNewApp ? "added" : "updated"),
704 getPackageInfo().getVersionCode(), pi.versionCode));
707 getPackageInfo().updateVersionInfo(pi);
709 boolean changed = false;
711 // For existing shortcuts, update timestamps if they have any resources.
712 // Also check if shortcuts' activities are still main activities. Otherwise, disable them.
714 Resources publisherRes = null;
716 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
717 final ShortcutInfo si = mShortcuts.valueAt(i);
719 if (si.isDynamic()) {
720 if (!s.injectIsMainActivity(si.getActivity(), getPackageUserId())) {
721 Slog.w(TAG, String.format(
722 "%s is no longer main activity. Disabling shorcut %s.",
723 getPackageName(), si.getId()));
724 if (disableDynamicWithId(si.getId())) {
725 continue; // Actually removed.
727 // Still pinned, so fall-through and possibly update the resources.
732 if (si.hasAnyResources()) {
733 if (!si.isOriginallyFromManifest()) {
734 if (publisherRes == null) {
735 publisherRes = getPackageResources();
736 if (publisherRes == null) {
737 break; // Resources couldn't be loaded.
741 // If this shortcut is not from a manifest, then update all resource IDs
742 // from resource names. (We don't allow resource strings for
743 // non-manifest at the moment, but icons can still be resources.)
744 si.lookupAndFillInResourceIds(publisherRes);
747 si.setTimestamp(s.injectCurrentTimeMillis());
752 // (Re-)publish manifest shortcut.
753 changed |= publishManifestShortcuts(newManifestShortcutList);
755 if (newManifestShortcutList != null) {
756 changed |= pushOutExcessShortcuts();
762 // This will send a notification to the launcher, and also save .
763 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
765 // Still save the version code.
766 s.scheduleSaveUser(getPackageUserId());
771 private boolean publishManifestShortcuts(List<ShortcutInfo> newManifestShortcutList) {
772 if (ShortcutService.DEBUG) {
773 Slog.d(TAG, String.format(
774 "Package %s: publishing manifest shortcuts", getPackageName()));
776 boolean changed = false;
778 // Keep the previous IDs.
779 ArraySet<String> toDisableList = null;
780 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
781 final ShortcutInfo si = mShortcuts.valueAt(i);
783 if (si.isManifestShortcut()) {
784 if (toDisableList == null) {
785 toDisableList = new ArraySet<>();
787 toDisableList.add(si.getId());
792 if (newManifestShortcutList != null) {
793 final int newListSize = newManifestShortcutList.size();
795 for (int i = 0; i < newListSize; i++) {
798 final ShortcutInfo newShortcut = newManifestShortcutList.get(i);
799 final boolean newDisabled = !newShortcut.isEnabled();
801 final String id = newShortcut.getId();
802 final ShortcutInfo oldShortcut = mShortcuts.get(id);
804 boolean wasPinned = false;
806 if (oldShortcut != null) {
807 if (!oldShortcut.isOriginallyFromManifest()) {
808 Slog.e(TAG, "Shortcut with ID=" + newShortcut.getId()
809 + " exists but is not from AndroidManifest.xml, not updating.");
812 // Take over the pinned flag.
813 if (oldShortcut.isPinned()) {
815 newShortcut.addFlags(ShortcutInfo.FLAG_PINNED);
818 if (newDisabled && !wasPinned) {
819 // If the shortcut is disabled, and it was *not* pinned, then this
820 // just doesn't have to be published.
821 // Just keep it in toDisableList, so the previous one would be removed.
825 // Note even if enabled=false, we still need to update all fields, so do it
827 addShortcutInner(newShortcut); // This will clean up the old one too.
829 if (!newDisabled && toDisableList != null) {
830 // Still alive, don't remove.
831 toDisableList.remove(id);
836 // Disable the previous manifest shortcuts that are no longer in the manifest.
837 if (toDisableList != null) {
838 if (ShortcutService.DEBUG) {
839 Slog.d(TAG, String.format(
840 "Package %s: disabling %d stale shortcuts", getPackageName(),
841 toDisableList.size()));
843 for (int i = toDisableList.size() - 1; i >= 0; i--) {
846 final String id = toDisableList.valueAt(i);
848 disableWithId(id, /* disable message =*/ null, /* disable message resid */ 0,
849 /* overrideImmutable=*/ true);
858 * For each target activity, make sure # of dynamic + manifest shortcuts <= max.
859 * If too many, we'll remove the dynamic with the lowest ranks.
861 private boolean pushOutExcessShortcuts() {
862 final ShortcutService service = mShortcutUser.mService;
863 final int maxShortcuts = service.getMaxActivityShortcuts();
865 boolean changed = false;
867 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
868 sortShortcutsToActivities();
869 for (int outer = all.size() - 1; outer >= 0; outer--) {
870 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
871 if (list.size() <= maxShortcuts) {
874 // Sort by isManifestShortcut() and getRank().
875 Collections.sort(list, mShortcutTypeAndRankComparator);
877 // Keep [0 .. max), and remove (as dynamic) [max .. size)
878 for (int inner = list.size() - 1; inner >= maxShortcuts; inner--) {
879 final ShortcutInfo shortcut = list.get(inner);
881 if (shortcut.isManifestShortcut()) {
882 // This shouldn't happen -- excess shortcuts should all be non-manifest.
884 service.wtf("Found manifest shortcuts in excess list.");
887 deleteDynamicWithId(shortcut.getId());
895 * To sort by isManifestShortcut() and getRank(). i.e. manifest shortcuts come before
896 * non-manifest shortcuts, then sort by rank.
898 * This is used to decide which dynamic shortcuts to remove when an upgraded version has more
899 * manifest shortcuts than before and as a result we need to remove some of the dynamic
900 * shortcuts. We sort manifest + dynamic shortcuts by this order, and remove the ones with
903 * (Note the number of manifest shortcuts is always <= the max number, because if there are
904 * more, ShortcutParser would ignore the rest.)
906 final Comparator<ShortcutInfo> mShortcutTypeAndRankComparator = (ShortcutInfo a,
908 if (a.isManifestShortcut() && !b.isManifestShortcut()) {
911 if (!a.isManifestShortcut() && b.isManifestShortcut()) {
914 return Integer.compare(a.getRank(), b.getRank());
918 * Build a list of shortcuts for each target activity and return as a map. The result won't
919 * contain "floating" shortcuts because they don't belong on any activities.
921 private ArrayMap<ComponentName, ArrayList<ShortcutInfo>> sortShortcutsToActivities() {
922 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> activitiesToShortcuts
924 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
925 final ShortcutInfo si = mShortcuts.valueAt(i);
926 if (si.isFloating()) {
927 continue; // Ignore floating shortcuts, which are not tied to any activities.
930 final ComponentName activity = si.getActivity();
932 ArrayList<ShortcutInfo> list = activitiesToShortcuts.get(activity);
934 list = new ArrayList<>();
935 activitiesToShortcuts.put(activity, list);
939 return activitiesToShortcuts;
942 /** Used by {@link #enforceShortcutCountsBeforeOperation} */
943 private void incrementCountForActivity(ArrayMap<ComponentName, Integer> counts,
944 ComponentName cn, int increment) {
945 Integer oldValue = counts.get(cn);
946 if (oldValue == null) {
950 counts.put(cn, oldValue + increment);
955 * {@link android.content.pm.ShortcutManager#setDynamicShortcuts},
956 * {@link android.content.pm.ShortcutManager#addDynamicShortcuts}, and
957 * {@link android.content.pm.ShortcutManager#updateShortcuts} before actually performing
958 * the operation to make sure the operation wouldn't result in the target activities having
959 * more than the allowed number of dynamic/manifest shortcuts.
961 * @param newList shortcut list passed to set, add or updateShortcuts().
962 * @param operation add, set or update.
963 * @throws IllegalArgumentException if the operation would result in going over the max
964 * shortcut count for any activity.
966 public void enforceShortcutCountsBeforeOperation(List<ShortcutInfo> newList,
967 @ShortcutOperation int operation) {
968 final ShortcutService service = mShortcutUser.mService;
970 // Current # of dynamic / manifest shortcuts for each activity.
971 // (If it's for update, then don't count dynamic shortcuts, since they'll be replaced
973 final ArrayMap<ComponentName, Integer> counts = new ArrayMap<>(4);
974 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
975 final ShortcutInfo shortcut = mShortcuts.valueAt(i);
977 if (shortcut.isManifestShortcut()) {
978 incrementCountForActivity(counts, shortcut.getActivity(), 1);
979 } else if (shortcut.isDynamic() && (operation != ShortcutService.OPERATION_SET)) {
980 incrementCountForActivity(counts, shortcut.getActivity(), 1);
984 for (int i = newList.size() - 1; i >= 0; i--) {
985 final ShortcutInfo newShortcut = newList.get(i);
986 final ComponentName newActivity = newShortcut.getActivity();
987 if (newActivity == null) {
988 if (operation != ShortcutService.OPERATION_UPDATE) {
989 service.wtf("Activity must not be null at this point");
990 continue; // Just ignore this invalid case.
992 continue; // Activity can be null for update.
995 final ShortcutInfo original = mShortcuts.get(newShortcut.getId());
996 if (original == null) {
997 if (operation == ShortcutService.OPERATION_UPDATE) {
998 continue; // When updating, ignore if there's no target.
1000 // Add() or set(), and there's no existing shortcut with the same ID. We're
1001 // simply publishing (as opposed to updating) this shortcut, so just +1.
1002 incrementCountForActivity(counts, newActivity, 1);
1005 if (original.isFloating() && (operation == ShortcutService.OPERATION_UPDATE)) {
1006 // Updating floating shortcuts doesn't affect the count, so ignore.
1010 // If it's add() or update(), then need to decrement for the previous activity.
1011 // Skip it for set() since it's already been taken care of by not counting the original
1012 // dynamic shortcuts in the first loop.
1013 if (operation != ShortcutService.OPERATION_SET) {
1014 final ComponentName oldActivity = original.getActivity();
1015 if (!original.isFloating()) {
1016 incrementCountForActivity(counts, oldActivity, -1);
1019 incrementCountForActivity(counts, newActivity, 1);
1022 // Then make sure none of the activities have more than the max number of shortcuts.
1023 for (int i = counts.size() - 1; i >= 0; i--) {
1024 service.enforceMaxActivityShortcuts(counts.valueAt(i));
1029 * For all the text fields, refresh the string values if they're from resources.
1031 public void resolveResourceStrings() {
1032 final ShortcutService s = mShortcutUser.mService;
1033 boolean changed = false;
1035 Resources publisherRes = null;
1036 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1037 final ShortcutInfo si = mShortcuts.valueAt(i);
1039 if (si.hasStringResources()) {
1042 if (publisherRes == null) {
1043 publisherRes = getPackageResources();
1044 if (publisherRes == null) {
1045 break; // Resources couldn't be loaded.
1049 si.resolveResourceStrings(publisherRes);
1050 si.setTimestamp(s.injectCurrentTimeMillis());
1054 s.packageShortcutsChanged(getPackageName(), getPackageUserId());
1058 /** Clears the implicit ranks for all shortcuts. */
1059 public void clearAllImplicitRanks() {
1060 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1061 final ShortcutInfo si = mShortcuts.valueAt(i);
1062 si.clearImplicitRankAndRankChangedFlag();
1067 * Used to sort shortcuts for rank auto-adjusting.
1069 final Comparator<ShortcutInfo> mShortcutRankComparator = (ShortcutInfo a, ShortcutInfo b) -> {
1070 // First, sort by rank.
1071 int ret = Integer.compare(a.getRank(), b.getRank());
1075 // When ranks are tie, then prioritize the ones that have just been assigned new ranks.
1076 // e.g. when there are 3 shortcuts, "s1" "s2" and "s3" with rank 0, 1, 2 respectively,
1077 // adding a shortcut "s4" with rank 1 will "insert" it between "s1" and "s2", because
1078 // "s2" and "s4" have the same rank 1 but s4 has isRankChanged() set.
1079 // Similarly, updating s3's rank to 1 will insert it between s1 and s2.
1080 if (a.isRankChanged() != b.isRankChanged()) {
1081 return a.isRankChanged() ? -1 : 1;
1083 // If they're still tie, sort by implicit rank -- i.e. preserve the order in which
1084 // they're passed to the API.
1085 ret = Integer.compare(a.getImplicitRank(), b.getImplicitRank());
1089 // If they're stil tie, just sort by their IDs.
1090 // This may happen with updateShortcuts() -- see
1091 // the testUpdateShortcuts_noManifestShortcuts() test.
1092 return a.getId().compareTo(b.getId());
1096 * Re-calculate the ranks for all shortcuts.
1098 public void adjustRanks() {
1099 final ShortcutService s = mShortcutUser.mService;
1100 final long now = s.injectCurrentTimeMillis();
1102 // First, clear ranks for floating shortcuts.
1103 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1104 final ShortcutInfo si = mShortcuts.valueAt(i);
1105 if (si.isFloating()) {
1106 if (si.getRank() != 0) {
1107 si.setTimestamp(now);
1113 // Then adjust ranks. Ranks are unique for each activity, so we first need to sort
1114 // shortcuts to each activity.
1115 // Then sort the shortcuts within each activity with mShortcutRankComparator, and
1116 // assign ranks from 0.
1117 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1118 sortShortcutsToActivities();
1119 for (int outer = all.size() - 1; outer >= 0; outer--) { // For each activity.
1120 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1122 // Sort by ranks and other signals.
1123 Collections.sort(list, mShortcutRankComparator);
1127 final int size = list.size();
1128 for (int i = 0; i < size; i++) {
1129 final ShortcutInfo si = list.get(i);
1130 if (si.isManifestShortcut()) {
1131 // Don't adjust ranks for manifest shortcuts.
1134 // At this point, it must be dynamic.
1135 if (!si.isDynamic()) {
1136 s.wtf("Non-dynamic shortcut found.");
1139 final int thisRank = rank++;
1140 if (si.getRank() != thisRank) {
1141 si.setTimestamp(now);
1142 si.setRank(thisRank);
1148 public void dump(@NonNull PrintWriter pw, @NonNull String prefix) {
1152 pw.print("Package: ");
1153 pw.print(getPackageName());
1155 pw.print(mPackageUid);
1160 pw.print("Calls: ");
1161 pw.print(getApiCallCount());
1164 // getApiCallCount() may have updated mLastKnownForegroundElapsedTime.
1167 pw.print("Last known FG: ");
1168 pw.print(mLastKnownForegroundElapsedTime);
1171 // This should be after getApiCallCount(), which may update it.
1174 pw.print("Last reset: [");
1175 pw.print(mLastResetTime);
1177 pw.print(ShortcutService.formatTime(mLastResetTime));
1180 getPackageInfo().dump(pw, prefix + " ");
1184 pw.println(" Shortcuts:");
1185 long totalBitmapSize = 0;
1186 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1187 final int size = shortcuts.size();
1188 for (int i = 0; i < size; i++) {
1189 final ShortcutInfo si = shortcuts.valueAt(i);
1192 pw.println(si.toInsecureString());
1193 if (si.getBitmapPath() != null) {
1194 final long len = new File(si.getBitmapPath()).length();
1197 pw.print("bitmap size=");
1200 totalBitmapSize += len;
1205 pw.print("Total bitmap size: ");
1206 pw.print(totalBitmapSize);
1208 pw.print(Formatter.formatFileSize(mShortcutUser.mService.mContext, totalBitmapSize));
1213 public JSONObject dumpCheckin(boolean clear) throws JSONException {
1214 final JSONObject result = super.dumpCheckin(clear);
1218 int numManifest = 0;
1220 long totalBitmapSize = 0;
1222 final ArrayMap<String, ShortcutInfo> shortcuts = mShortcuts;
1223 final int size = shortcuts.size();
1224 for (int i = 0; i < size; i++) {
1225 final ShortcutInfo si = shortcuts.valueAt(i);
1227 if (si.isDynamic()) numDynamic++;
1228 if (si.isDeclaredInManifest()) numManifest++;
1229 if (si.isPinned()) numPinned++;
1231 if (si.getBitmapPath() != null) {
1233 totalBitmapSize += new File(si.getBitmapPath()).length();
1237 result.put(KEY_DYNAMIC, numDynamic);
1238 result.put(KEY_MANIFEST, numManifest);
1239 result.put(KEY_PINNED, numPinned);
1240 result.put(KEY_BITMAPS, numBitmaps);
1241 result.put(KEY_BITMAP_BYTES, totalBitmapSize);
1243 // TODO Log update frequency too.
1249 public void saveToXml(@NonNull XmlSerializer out, boolean forBackup)
1250 throws IOException, XmlPullParserException {
1251 final int size = mShortcuts.size();
1253 if (size == 0 && mApiCallCount == 0) {
1254 return; // nothing to write.
1257 out.startTag(null, TAG_ROOT);
1259 ShortcutService.writeAttr(out, ATTR_NAME, getPackageName());
1260 ShortcutService.writeAttr(out, ATTR_CALL_COUNT, mApiCallCount);
1261 ShortcutService.writeAttr(out, ATTR_LAST_RESET, mLastResetTime);
1262 getPackageInfo().saveToXml(out);
1264 for (int j = 0; j < size; j++) {
1265 saveShortcut(out, mShortcuts.valueAt(j), forBackup);
1268 out.endTag(null, TAG_ROOT);
1271 private static void saveShortcut(XmlSerializer out, ShortcutInfo si, boolean forBackup)
1272 throws IOException, XmlPullParserException {
1274 if (!(si.isPinned() && si.isEnabled())) {
1275 return; // We only backup pinned shortcuts that are enabled.
1278 out.startTag(null, TAG_SHORTCUT);
1279 ShortcutService.writeAttr(out, ATTR_ID, si.getId());
1280 // writeAttr(out, "package", si.getPackageName()); // not needed
1281 ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivity());
1282 // writeAttr(out, "icon", si.getIcon()); // We don't save it.
1283 ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
1284 ShortcutService.writeAttr(out, ATTR_TITLE_RES_ID, si.getTitleResId());
1285 ShortcutService.writeAttr(out, ATTR_TITLE_RES_NAME, si.getTitleResName());
1286 ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
1287 ShortcutService.writeAttr(out, ATTR_TEXT_RES_ID, si.getTextResId());
1288 ShortcutService.writeAttr(out, ATTR_TEXT_RES_NAME, si.getTextResName());
1289 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE, si.getDisabledMessage());
1290 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_ID,
1291 si.getDisabledMessageResourceId());
1292 ShortcutService.writeAttr(out, ATTR_DISABLED_MESSAGE_RES_NAME,
1293 si.getDisabledMessageResName());
1294 ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
1295 si.getLastChangedTimestamp());
1297 // Don't write icon information. Also drop the dynamic flag.
1298 ShortcutService.writeAttr(out, ATTR_FLAGS,
1300 ~(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES
1301 | ShortcutInfo.FLAG_DYNAMIC));
1303 // When writing for backup, ranks shouldn't be saved, since shortcuts won't be restored
1305 ShortcutService.writeAttr(out, ATTR_RANK, si.getRank());
1307 ShortcutService.writeAttr(out, ATTR_FLAGS, si.getFlags());
1308 ShortcutService.writeAttr(out, ATTR_ICON_RES_ID, si.getIconResourceId());
1309 ShortcutService.writeAttr(out, ATTR_ICON_RES_NAME, si.getIconResName());
1310 ShortcutService.writeAttr(out, ATTR_BITMAP_PATH, si.getBitmapPath());
1314 final Set<String> cat = si.getCategories();
1315 if (cat != null && cat.size() > 0) {
1316 out.startTag(null, TAG_CATEGORIES);
1317 XmlUtils.writeStringArrayXml(cat.toArray(new String[cat.size()]),
1318 NAME_CATEGORIES, out);
1319 out.endTag(null, TAG_CATEGORIES);
1322 final Intent[] intentsNoExtras = si.getIntentsNoExtras();
1323 final PersistableBundle[] intentsExtras = si.getIntentPersistableExtrases();
1324 final int numIntents = intentsNoExtras.length;
1325 for (int i = 0; i < numIntents; i++) {
1326 out.startTag(null, TAG_INTENT);
1327 ShortcutService.writeAttr(out, ATTR_INTENT_NO_EXTRA, intentsNoExtras[i]);
1328 ShortcutService.writeTagExtra(out, TAG_EXTRAS, intentsExtras[i]);
1329 out.endTag(null, TAG_INTENT);
1332 ShortcutService.writeTagExtra(out, TAG_EXTRAS, si.getExtras());
1334 out.endTag(null, TAG_SHORTCUT);
1337 public static ShortcutPackage loadFromXml(ShortcutService s, ShortcutUser shortcutUser,
1338 XmlPullParser parser, boolean fromBackup)
1339 throws IOException, XmlPullParserException {
1341 final String packageName = ShortcutService.parseStringAttribute(parser,
1344 final ShortcutPackage ret = new ShortcutPackage(shortcutUser,
1345 shortcutUser.getUserId(), packageName);
1348 ShortcutService.parseIntAttribute(parser, ATTR_CALL_COUNT);
1349 ret.mLastResetTime =
1350 ShortcutService.parseLongAttribute(parser, ATTR_LAST_RESET);
1352 final int outerDepth = parser.getDepth();
1354 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1355 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1356 if (type != XmlPullParser.START_TAG) {
1359 final int depth = parser.getDepth();
1360 final String tag = parser.getName();
1361 if (depth == outerDepth + 1) {
1363 case ShortcutPackageInfo.TAG_ROOT:
1364 ret.getPackageInfo().loadFromXml(parser, fromBackup);
1367 final ShortcutInfo si = parseShortcut(parser, packageName,
1368 shortcutUser.getUserId());
1370 // Don't use addShortcut(), we don't need to save the icon.
1371 ret.mShortcuts.put(si.getId(), si);
1375 ShortcutService.warnForInvalidTag(depth, tag);
1380 private static ShortcutInfo parseShortcut(XmlPullParser parser, String packageName,
1381 @UserIdInt int userId) throws IOException, XmlPullParserException {
1383 ComponentName activityComponent;
1387 String titleResName;
1391 String disabledMessage;
1392 int disabledMessageResId;
1393 String disabledMessageResName;
1394 Intent intentLegacy;
1395 PersistableBundle intentPersistableExtrasLegacy = null;
1396 ArrayList<Intent> intents = new ArrayList<>();
1398 PersistableBundle extras = null;
1399 long lastChangedTimestamp;
1404 ArraySet<String> categories = null;
1406 id = ShortcutService.parseStringAttribute(parser, ATTR_ID);
1407 activityComponent = ShortcutService.parseComponentNameAttribute(parser,
1409 title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
1410 titleResId = ShortcutService.parseIntAttribute(parser, ATTR_TITLE_RES_ID);
1411 titleResName = ShortcutService.parseStringAttribute(parser, ATTR_TITLE_RES_NAME);
1412 text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
1413 textResId = ShortcutService.parseIntAttribute(parser, ATTR_TEXT_RES_ID);
1414 textResName = ShortcutService.parseStringAttribute(parser, ATTR_TEXT_RES_NAME);
1415 disabledMessage = ShortcutService.parseStringAttribute(parser, ATTR_DISABLED_MESSAGE);
1416 disabledMessageResId = ShortcutService.parseIntAttribute(parser,
1417 ATTR_DISABLED_MESSAGE_RES_ID);
1418 disabledMessageResName = ShortcutService.parseStringAttribute(parser,
1419 ATTR_DISABLED_MESSAGE_RES_NAME);
1420 intentLegacy = ShortcutService.parseIntentAttributeNoDefault(parser, ATTR_INTENT_LEGACY);
1421 rank = (int) ShortcutService.parseLongAttribute(parser, ATTR_RANK);
1422 lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
1423 flags = (int) ShortcutService.parseLongAttribute(parser, ATTR_FLAGS);
1424 iconResId = (int) ShortcutService.parseLongAttribute(parser, ATTR_ICON_RES_ID);
1425 iconResName = ShortcutService.parseStringAttribute(parser, ATTR_ICON_RES_NAME);
1426 bitmapPath = ShortcutService.parseStringAttribute(parser, ATTR_BITMAP_PATH);
1428 final int outerDepth = parser.getDepth();
1430 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1431 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1432 if (type != XmlPullParser.START_TAG) {
1435 final int depth = parser.getDepth();
1436 final String tag = parser.getName();
1437 if (ShortcutService.DEBUG_LOAD) {
1438 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1442 case TAG_INTENT_EXTRAS_LEGACY:
1443 intentPersistableExtrasLegacy = PersistableBundle.restoreFromXml(parser);
1446 intents.add(parseIntent(parser));
1449 extras = PersistableBundle.restoreFromXml(parser);
1451 case TAG_CATEGORIES:
1452 // This just contains string-array.
1454 case TAG_STRING_ARRAY_XMLUTILS:
1455 if (NAME_CATEGORIES.equals(ShortcutService.parseStringAttribute(parser,
1456 ATTR_NAME_XMLUTILS))) {
1457 final String[] ar = XmlUtils.readThisStringArrayXml(
1458 parser, TAG_STRING_ARRAY_XMLUTILS, null);
1459 categories = new ArraySet<>(ar.length);
1460 for (int i = 0; i < ar.length; i++) {
1461 categories.add(ar[i]);
1466 throw ShortcutService.throwForInvalidTag(depth, tag);
1469 if (intentLegacy != null) {
1470 // For the legacy file format which supported only one intent per shortcut.
1471 ShortcutInfo.setIntentExtras(intentLegacy, intentPersistableExtrasLegacy);
1473 intents.add(intentLegacy);
1476 return new ShortcutInfo(
1477 userId, id, packageName, activityComponent, /* icon =*/ null,
1478 title, titleResId, titleResName, text, textResId, textResName,
1479 disabledMessage, disabledMessageResId, disabledMessageResName,
1481 intents.toArray(new Intent[intents.size()]),
1482 rank, extras, lastChangedTimestamp, flags,
1483 iconResId, iconResName, bitmapPath);
1486 private static Intent parseIntent(XmlPullParser parser)
1487 throws IOException, XmlPullParserException {
1489 Intent intent = ShortcutService.parseIntentAttribute(parser,
1490 ATTR_INTENT_NO_EXTRA);
1492 final int outerDepth = parser.getDepth();
1494 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1495 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1496 if (type != XmlPullParser.START_TAG) {
1499 final int depth = parser.getDepth();
1500 final String tag = parser.getName();
1501 if (ShortcutService.DEBUG_LOAD) {
1502 Slog.d(TAG, String.format(" depth=%d type=%d name=%s",
1507 ShortcutInfo.setIntentExtras(intent,
1508 PersistableBundle.restoreFromXml(parser));
1511 throw ShortcutService.throwForInvalidTag(depth, tag);
1517 List<ShortcutInfo> getAllShortcutsForTest() {
1518 return new ArrayList<>(mShortcuts.values());
1522 public void verifyStates() {
1523 super.verifyStates();
1525 boolean failed = false;
1527 final ArrayMap<ComponentName, ArrayList<ShortcutInfo>> all =
1528 sortShortcutsToActivities();
1530 // Make sure each activity won't have more than max shortcuts.
1531 for (int outer = all.size() - 1; outer >= 0; outer--) {
1532 final ArrayList<ShortcutInfo> list = all.valueAt(outer);
1533 if (list.size() > mShortcutUser.mService.getMaxActivityShortcuts()) {
1535 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": activity " + all.keyAt(outer)
1536 + " has " + all.valueAt(outer).size() + " shortcuts.");
1540 Collections.sort(list, (a, b) -> Integer.compare(a.getRank(), b.getRank()));
1542 // Split into two arrays for each kind.
1543 final ArrayList<ShortcutInfo> dynamicList = new ArrayList<>(list);
1544 dynamicList.removeIf((si) -> !si.isDynamic());
1546 final ArrayList<ShortcutInfo> manifestList = new ArrayList<>(list);
1547 dynamicList.removeIf((si) -> !si.isManifestShortcut());
1549 verifyRanksSequential(dynamicList);
1550 verifyRanksSequential(manifestList);
1553 // Verify each shortcut's status.
1554 for (int i = mShortcuts.size() - 1; i >= 0; i--) {
1555 final ShortcutInfo si = mShortcuts.valueAt(i);
1556 if (!(si.isDeclaredInManifest() || si.isDynamic() || si.isPinned())) {
1558 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1559 + " is not manifest, dynamic or pinned.");
1561 if (si.isDeclaredInManifest() && si.isDynamic()) {
1563 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1564 + " is both dynamic and manifest at the same time.");
1566 if (si.getActivity() == null) {
1568 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1569 + " has null activity.");
1571 if ((si.isDynamic() || si.isManifestShortcut()) && !si.isEnabled()) {
1573 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1574 + " is not floating, but is disabled.");
1576 if (si.isFloating() && si.getRank() != 0) {
1578 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1579 + " is floating, but has rank=" + si.getRank());
1581 if (si.getIcon() != null) {
1583 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1584 + " still has an icon");
1586 if (si.hasIconFile() && si.hasIconResource()) {
1588 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1589 + " has both resource and bitmap icons");
1594 throw new IllegalStateException("See logcat for errors");
1598 private boolean verifyRanksSequential(List<ShortcutInfo> list) {
1599 boolean failed = false;
1601 for (int i = 0; i < list.size(); i++) {
1602 final ShortcutInfo si = list.get(i);
1603 if (si.getRank() != i) {
1605 Log.e(TAG_VERIFY, "Package " + getPackageName() + ": shortcut " + si.getId()
1606 + " rank=" + si.getRank() + " but expected to be "+ i);