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.IntDef;
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.annotation.UserIdInt;
22 import android.app.ActivityManager;
23 import android.app.ActivityManagerInternal;
24 import android.app.ActivityManagerNative;
25 import android.app.AppGlobals;
26 import android.app.IUidObserver;
27 import android.app.usage.UsageStatsManagerInternal;
28 import android.content.BroadcastReceiver;
29 import android.content.ComponentName;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.pm.ActivityInfo;
34 import android.content.pm.ApplicationInfo;
35 import android.content.pm.IPackageManager;
36 import android.content.pm.IShortcutService;
37 import android.content.pm.LauncherApps;
38 import android.content.pm.LauncherApps.ShortcutQuery;
39 import android.content.pm.PackageInfo;
40 import android.content.pm.PackageManager;
41 import android.content.pm.PackageManager.NameNotFoundException;
42 import android.content.pm.PackageManagerInternal;
43 import android.content.pm.ParceledListSlice;
44 import android.content.pm.ResolveInfo;
45 import android.content.pm.ShortcutInfo;
46 import android.content.pm.ShortcutServiceInternal;
47 import android.content.pm.ShortcutServiceInternal.ShortcutChangeListener;
48 import android.content.res.Resources;
49 import android.content.res.XmlResourceParser;
50 import android.graphics.Bitmap;
51 import android.graphics.Bitmap.CompressFormat;
52 import android.graphics.Canvas;
53 import android.graphics.RectF;
54 import android.graphics.drawable.Icon;
55 import android.net.Uri;
56 import android.os.Binder;
57 import android.os.Build;
58 import android.os.Environment;
59 import android.os.FileUtils;
60 import android.os.Handler;
61 import android.os.LocaleList;
62 import android.os.Looper;
63 import android.os.ParcelFileDescriptor;
64 import android.os.PersistableBundle;
65 import android.os.Process;
66 import android.os.RemoteException;
67 import android.os.ResultReceiver;
68 import android.os.SELinux;
69 import android.os.ServiceManager;
70 import android.os.ShellCommand;
71 import android.os.SystemClock;
72 import android.os.UserHandle;
73 import android.os.UserManager;
74 import android.text.TextUtils;
75 import android.text.format.Time;
76 import android.util.ArraySet;
77 import android.util.AtomicFile;
78 import android.util.KeyValueListParser;
79 import android.util.Log;
80 import android.util.Slog;
81 import android.util.SparseArray;
82 import android.util.SparseBooleanArray;
83 import android.util.SparseIntArray;
84 import android.util.SparseLongArray;
85 import android.util.TypedValue;
86 import android.util.Xml;
87 import android.view.IWindowManager;
89 import com.android.internal.annotations.GuardedBy;
90 import com.android.internal.annotations.VisibleForTesting;
91 import com.android.internal.os.BackgroundThread;
92 import com.android.internal.util.FastXmlSerializer;
93 import com.android.internal.util.Preconditions;
94 import com.android.server.LocalServices;
95 import com.android.server.SystemService;
96 import com.android.server.pm.ShortcutUser.PackageWithUser;
98 import libcore.io.IoUtils;
100 import org.json.JSONArray;
101 import org.json.JSONException;
102 import org.json.JSONObject;
103 import org.xmlpull.v1.XmlPullParser;
104 import org.xmlpull.v1.XmlPullParserException;
105 import org.xmlpull.v1.XmlSerializer;
107 import java.io.BufferedInputStream;
108 import java.io.BufferedOutputStream;
109 import java.io.ByteArrayInputStream;
110 import java.io.ByteArrayOutputStream;
112 import java.io.FileDescriptor;
113 import java.io.FileInputStream;
114 import java.io.FileNotFoundException;
115 import java.io.FileOutputStream;
116 import java.io.IOException;
117 import java.io.InputStream;
118 import java.io.OutputStream;
119 import java.io.PrintWriter;
120 import java.lang.annotation.Retention;
121 import java.lang.annotation.RetentionPolicy;
122 import java.net.URISyntaxException;
123 import java.nio.charset.StandardCharsets;
124 import java.util.ArrayList;
125 import java.util.Collections;
126 import java.util.List;
127 import java.util.concurrent.atomic.AtomicBoolean;
128 import java.util.function.Consumer;
129 import java.util.function.Predicate;
133 * - getIconMaxWidth()/getIconMaxHeight() should use xdpi and ydpi.
134 * -> But TypedValue.applyDimension() doesn't differentiate x and y..?
136 * - Detect when already registered instances are passed to APIs again, which might break
137 * internal bitmap handling.
139 public class ShortcutService extends IShortcutService.Stub {
140 static final String TAG = "ShortcutService";
142 static final boolean DEBUG = false; // STOPSHIP if true
143 static final boolean DEBUG_LOAD = false; // STOPSHIP if true
144 static final boolean DEBUG_PROCSTATE = false; // STOPSHIP if true
147 static final long DEFAULT_RESET_INTERVAL_SEC = 24 * 60 * 60; // 1 day
150 static final int DEFAULT_MAX_UPDATES_PER_INTERVAL = 10;
153 static final int DEFAULT_MAX_SHORTCUTS_PER_APP = 5;
156 static final int DEFAULT_MAX_ICON_DIMENSION_DP = 96;
159 static final int DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP = 48;
162 static final String DEFAULT_ICON_PERSIST_FORMAT = CompressFormat.PNG.name();
165 static final int DEFAULT_ICON_PERSIST_QUALITY = 100;
168 static final int DEFAULT_SAVE_DELAY_MS = 3000;
171 static final String FILENAME_BASE_STATE = "shortcut_service.xml";
174 static final String DIRECTORY_PER_USER = "shortcut_service";
177 static final String FILENAME_USER_PACKAGES = "shortcuts.xml";
179 static final String DIRECTORY_BITMAPS = "bitmaps";
181 private static final String TAG_ROOT = "root";
182 private static final String TAG_LAST_RESET_TIME = "last_reset_time";
184 private static final String ATTR_VALUE = "value";
186 private static final String LAUNCHER_INTENT_CATEGORY = Intent.CATEGORY_LAUNCHER;
188 private static final String KEY_SHORTCUT = "shortcut";
189 private static final String KEY_LOW_RAM = "lowRam";
190 private static final String KEY_ICON_SIZE = "iconSize";
193 interface ConfigConstants {
195 * Key name for the save delay, in milliseconds. (int)
197 String KEY_SAVE_DELAY_MILLIS = "save_delay_ms";
200 * Key name for the throttling reset interval, in seconds. (long)
202 String KEY_RESET_INTERVAL_SEC = "reset_interval_sec";
205 * Key name for the max number of modifying API calls per app for every interval. (int)
207 String KEY_MAX_UPDATES_PER_INTERVAL = "max_updates_per_interval";
210 * Key name for the max icon dimensions in DP, for non-low-memory devices.
212 String KEY_MAX_ICON_DIMENSION_DP = "max_icon_dimension_dp";
215 * Key name for the max icon dimensions in DP, for low-memory devices.
217 String KEY_MAX_ICON_DIMENSION_DP_LOWRAM = "max_icon_dimension_dp_lowram";
220 * Key name for the max dynamic shortcuts per activity. (int)
222 String KEY_MAX_SHORTCUTS = "max_shortcuts";
225 * Key name for icon compression quality, 0-100.
227 String KEY_ICON_QUALITY = "icon_quality";
230 * Key name for icon compression format: "PNG", "JPEG" or "WEBP"
232 String KEY_ICON_FORMAT = "icon_format";
235 final Context mContext;
237 private final Object mLock = new Object();
239 private static List<ResolveInfo> EMPTY_RESOLVE_INFO = new ArrayList<>(0);
241 private static Predicate<ResolveInfo> ACTIVITY_NOT_EXPORTED =
242 ri -> !ri.activityInfo.exported;
244 private static Predicate<PackageInfo> PACKAGE_NOT_INSTALLED = pi -> !isInstalled(pi);
246 private final Handler mHandler;
249 private final ArrayList<ShortcutChangeListener> mListeners = new ArrayList<>(1);
252 private long mRawLastResetTime;
255 * User ID -> UserShortcuts
258 private final SparseArray<ShortcutUser> mUsers = new SparseArray<>();
261 * Max number of dynamic + manifest shortcuts that each application can have at a time.
263 private int mMaxShortcuts;
266 * Max number of updating API calls that each application can make during the interval.
268 int mMaxUpdatesPerInterval;
271 * Actual throttling-reset interval. By default it's a day.
273 private long mResetInterval;
276 * Icon max width/height in pixels.
278 private int mMaxIconDimension;
280 private CompressFormat mIconPersistFormat;
281 private int mIconPersistQuality;
283 private int mSaveDelayMillis;
285 private final IPackageManager mIPackageManager;
286 private final PackageManagerInternal mPackageManagerInternal;
287 private final UserManager mUserManager;
288 private final UsageStatsManagerInternal mUsageStatsManagerInternal;
289 private final ActivityManagerInternal mActivityManagerInternal;
292 final SparseIntArray mUidState = new SparseIntArray();
295 final SparseLongArray mUidLastForegroundElapsedTime = new SparseLongArray();
298 private List<Integer> mDirtyUserIds = new ArrayList<>();
300 private final AtomicBoolean mBootCompleted = new AtomicBoolean();
302 private static final int PACKAGE_MATCH_FLAGS =
303 PackageManager.MATCH_DIRECT_BOOT_AWARE
304 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
305 | PackageManager.MATCH_UNINSTALLED_PACKAGES;
308 final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
313 int GET_DEFAULT_HOME = 0;
314 int GET_PACKAGE_INFO = 1;
315 int GET_PACKAGE_INFO_WITH_SIG = 2;
316 int GET_APPLICATION_INFO = 3;
317 int LAUNCHER_PERMISSION_CHECK = 4;
318 int CLEANUP_DANGLING_BITMAPS = 5;
319 int GET_ACTIVITY_WITH_METADATA = 6;
320 int GET_INSTALLED_PACKAGES = 7;
321 int CHECK_PACKAGE_CHANGES = 8;
322 int GET_APPLICATION_RESOURCES = 9;
323 int RESOURCE_NAME_LOOKUP = 10;
324 int GET_LAUNCHER_ACTIVITY = 11;
325 int CHECK_LAUNCHER_ACTIVITY = 12;
326 int IS_ACTIVITY_ENABLED = 13;
327 int PACKAGE_UPDATE_CHECK = 14;
328 int ASYNC_PRELOAD_USER_DELAY = 15;
330 int COUNT = ASYNC_PRELOAD_USER_DELAY + 1;
333 private static final String[] STAT_LABELS = {
334 "getHomeActivities()",
335 "Launcher permission check",
337 "getPackageInfo(SIG)",
338 "getApplicationInfo",
339 "cleanupDanglingBitmaps",
340 "getActivity+metadata",
341 "getInstalledPackages",
342 "checkPackageChanges",
343 "getApplicationResources",
344 "resourceNameLookup",
345 "getLauncherActivity",
346 "checkLauncherActivity",
348 "packageUpdateCheck",
349 "asyncPreloadUserDelay"
352 final Object mStatLock = new Object();
354 @GuardedBy("mStatLock")
355 private final int[] mCountStats = new int[Stats.COUNT];
357 @GuardedBy("mStatLock")
358 private final long[] mDurationStats = new long[Stats.COUNT];
360 private static final int PROCESS_STATE_FOREGROUND_THRESHOLD =
361 ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
363 static final int OPERATION_SET = 0;
364 static final int OPERATION_ADD = 1;
365 static final int OPERATION_UPDATE = 2;
373 @Retention(RetentionPolicy.SOURCE)
374 @interface ShortcutOperation {
378 private int mWtfCount = 0;
381 private Exception mLastWtfStacktrace;
383 public ShortcutService(Context context) {
384 this(context, BackgroundThread.get().getLooper(), /*onyForPackgeManagerApis*/ false);
388 ShortcutService(Context context, Looper looper, boolean onlyForPackageManagerApis) {
389 mContext = Preconditions.checkNotNull(context);
390 LocalServices.addService(ShortcutServiceInternal.class, new LocalService());
391 mHandler = new Handler(looper);
392 mIPackageManager = AppGlobals.getPackageManager();
393 mPackageManagerInternal = Preconditions.checkNotNull(
394 LocalServices.getService(PackageManagerInternal.class));
395 mUserManager = Preconditions.checkNotNull(context.getSystemService(UserManager.class));
396 mUsageStatsManagerInternal = Preconditions.checkNotNull(
397 LocalServices.getService(UsageStatsManagerInternal.class));
398 mActivityManagerInternal = Preconditions.checkNotNull(
399 LocalServices.getService(ActivityManagerInternal.class));
401 if (onlyForPackageManagerApis) {
402 return; // Don't do anything further. For unit tests only.
405 // Register receivers.
407 // We need to set a priority, so let's just not use PackageMonitor for now.
408 // TODO Refactor PackageMonitor to support priorities.
409 final IntentFilter packageFilter = new IntentFilter();
410 packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
411 packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
412 packageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
413 packageFilter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
414 packageFilter.addDataScheme("package");
415 packageFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
416 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
417 packageFilter, null, mHandler);
419 final IntentFilter preferedActivityFilter = new IntentFilter();
420 preferedActivityFilter.addAction(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
421 preferedActivityFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
422 mContext.registerReceiverAsUser(mPackageMonitor, UserHandle.ALL,
423 preferedActivityFilter, null, mHandler);
425 final IntentFilter localeFilter = new IntentFilter();
426 localeFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
427 localeFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
428 mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL,
429 localeFilter, null, mHandler);
431 injectRegisterUidObserver(mUidObserver, ActivityManager.UID_OBSERVER_PROCSTATE
432 | ActivityManager.UID_OBSERVER_GONE);
435 void logDurationStat(int statId, long start) {
436 synchronized (mStatLock) {
437 mCountStats[statId]++;
438 mDurationStats[statId] += (injectElapsedRealtime() - start);
442 public String injectGetLocaleTagsForUser(@UserIdInt int userId) {
443 // TODO This should get the per-user locale. b/30123329 b/30119489
444 return LocaleList.getDefault().toLanguageTags();
447 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
449 public void onUidStateChanged(int uid, int procState) throws RemoteException {
450 handleOnUidStateChanged(uid, procState);
454 public void onUidGone(int uid) throws RemoteException {
455 handleOnUidStateChanged(uid, ActivityManager.MAX_PROCESS_STATE);
459 public void onUidActive(int uid) throws RemoteException {
463 public void onUidIdle(int uid) throws RemoteException {
467 void handleOnUidStateChanged(int uid, int procState) {
468 if (DEBUG_PROCSTATE) {
469 Slog.d(TAG, "onUidStateChanged: uid=" + uid + " state=" + procState);
471 synchronized (mLock) {
472 mUidState.put(uid, procState);
474 // We need to keep track of last time an app comes to foreground.
475 // See ShortcutPackage.getApiCallCount() for how it's used.
476 // It doesn't have to be persisted, but it needs to be the elapsed time.
477 if (isProcessStateForeground(procState)) {
478 mUidLastForegroundElapsedTime.put(uid, injectElapsedRealtime());
483 private boolean isProcessStateForeground(int processState) {
484 return (processState != ActivityManager.PROCESS_STATE_NONEXISTENT)
485 && (processState <= PROCESS_STATE_FOREGROUND_THRESHOLD);
488 boolean isUidForegroundLocked(int uid) {
489 if (uid == Process.SYSTEM_UID) {
490 // IUidObserver doesn't report the state of SYSTEM, but it always has bound services,
491 // so it's foreground anyway.
494 // First, check with the local cache.
495 if (isProcessStateForeground(mUidState.get(uid, ActivityManager.MAX_PROCESS_STATE))) {
498 // If the cache says background, reach out to AM. Since it'll internally need to hold
499 // the AM lock, we use it as a last resort.
500 return isProcessStateForeground(mActivityManagerInternal.getUidProcessState(uid));
503 long getUidLastForegroundElapsedTimeLocked(int uid) {
504 return mUidLastForegroundElapsedTime.get(uid);
508 * System service lifecycle.
510 public static final class Lifecycle extends SystemService {
511 final ShortcutService mService;
513 public Lifecycle(Context context) {
515 mService = new ShortcutService(context);
519 public void onStart() {
520 publishBinderService(Context.SHORTCUT_SERVICE, mService);
524 public void onBootPhase(int phase) {
525 mService.onBootPhase(phase);
529 public void onCleanupUser(int userHandle) {
530 mService.handleCleanupUser(userHandle);
534 public void onUnlockUser(int userId) {
535 mService.handleUnlockUser(userId);
539 /** lifecycle event */
540 void onBootPhase(int phase) {
542 Slog.d(TAG, "onBootPhase: " + phase);
545 case SystemService.PHASE_LOCK_SETTINGS_READY:
548 case SystemService.PHASE_BOOT_COMPLETED:
549 mBootCompleted.set(true);
554 /** lifecycle event */
555 void handleUnlockUser(int userId) {
557 Slog.d(TAG, "handleUnlockUser: user=" + userId);
559 synchronized (mLock) {
560 mUnlockedUsers.put(userId, true);
563 // Preload the user data.
564 // Note, we don't use mHandler here but instead just start a new thread.
565 // This is because mHandler (which uses com.android.internal.os.BackgroundThread) is very
566 // busy at this point and this could take hundreds of milliseconds, which would be too
567 // late since the launcher would already have started.
568 // So we just create a new thread. This code runs rarely, so we don't use a thread pool
570 final long start = injectElapsedRealtime();
571 injectRunOnNewThread(() -> {
572 synchronized (mLock) {
573 logDurationStat(Stats.ASYNC_PRELOAD_USER_DELAY, start);
574 getUserShortcutsLocked(userId);
579 /** lifecycle event */
580 void handleCleanupUser(int userId) {
582 Slog.d(TAG, "handleCleanupUser: user=" + userId);
584 synchronized (mLock) {
585 unloadUserLocked(userId);
587 mUnlockedUsers.put(userId, false);
591 private void unloadUserLocked(int userId) {
593 Slog.d(TAG, "unloadUserLocked: user=" + userId);
595 // Save all dirty information.
599 mUsers.delete(userId);
602 /** Return the base state file name */
603 private AtomicFile getBaseStateFile() {
604 final File path = new File(injectSystemDataPath(), FILENAME_BASE_STATE);
606 return new AtomicFile(path);
610 * Init the instance. (load the state file, etc)
612 private void initialize() {
613 synchronized (mLock) {
614 loadConfigurationLocked();
615 loadBaseStateLocked();
620 * Load the configuration from Settings.
622 private void loadConfigurationLocked() {
623 updateConfigurationLocked(injectShortcutManagerConstants());
627 * Load the configuration from Settings.
630 boolean updateConfigurationLocked(String config) {
631 boolean result = true;
633 final KeyValueListParser parser = new KeyValueListParser(',');
635 parser.setString(config);
636 } catch (IllegalArgumentException e) {
637 // Failed to parse the settings string, log this and move on
639 Slog.e(TAG, "Bad shortcut manager settings", e);
643 mSaveDelayMillis = Math.max(0, (int) parser.getLong(ConfigConstants.KEY_SAVE_DELAY_MILLIS,
644 DEFAULT_SAVE_DELAY_MS));
646 mResetInterval = Math.max(1, parser.getLong(
647 ConfigConstants.KEY_RESET_INTERVAL_SEC, DEFAULT_RESET_INTERVAL_SEC)
650 mMaxUpdatesPerInterval = Math.max(0, (int) parser.getLong(
651 ConfigConstants.KEY_MAX_UPDATES_PER_INTERVAL, DEFAULT_MAX_UPDATES_PER_INTERVAL));
653 mMaxShortcuts = Math.max(0, (int) parser.getLong(
654 ConfigConstants.KEY_MAX_SHORTCUTS, DEFAULT_MAX_SHORTCUTS_PER_APP));
656 final int iconDimensionDp = Math.max(1, injectIsLowRamDevice()
657 ? (int) parser.getLong(
658 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP_LOWRAM,
659 DEFAULT_MAX_ICON_DIMENSION_LOWRAM_DP)
660 : (int) parser.getLong(
661 ConfigConstants.KEY_MAX_ICON_DIMENSION_DP,
662 DEFAULT_MAX_ICON_DIMENSION_DP));
664 mMaxIconDimension = injectDipToPixel(iconDimensionDp);
666 mIconPersistFormat = CompressFormat.valueOf(
667 parser.getString(ConfigConstants.KEY_ICON_FORMAT, DEFAULT_ICON_PERSIST_FORMAT));
669 mIconPersistQuality = (int) parser.getLong(
670 ConfigConstants.KEY_ICON_QUALITY,
671 DEFAULT_ICON_PERSIST_QUALITY);
677 String injectShortcutManagerConstants() {
678 return android.provider.Settings.Global.getString(
679 mContext.getContentResolver(),
680 android.provider.Settings.Global.SHORTCUT_MANAGER_CONSTANTS);
684 int injectDipToPixel(int dip) {
685 return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
686 mContext.getResources().getDisplayMetrics());
689 // === Persisting ===
692 static String parseStringAttribute(XmlPullParser parser, String attribute) {
693 return parser.getAttributeValue(null, attribute);
696 static boolean parseBooleanAttribute(XmlPullParser parser, String attribute) {
697 return parseLongAttribute(parser, attribute) == 1;
700 static int parseIntAttribute(XmlPullParser parser, String attribute) {
701 return (int) parseLongAttribute(parser, attribute);
704 static int parseIntAttribute(XmlPullParser parser, String attribute, int def) {
705 return (int) parseLongAttribute(parser, attribute, def);
708 static long parseLongAttribute(XmlPullParser parser, String attribute) {
709 return parseLongAttribute(parser, attribute, 0);
712 static long parseLongAttribute(XmlPullParser parser, String attribute, long def) {
713 final String value = parseStringAttribute(parser, attribute);
714 if (TextUtils.isEmpty(value)) {
718 return Long.parseLong(value);
719 } catch (NumberFormatException e) {
720 Slog.e(TAG, "Error parsing long " + value);
726 static ComponentName parseComponentNameAttribute(XmlPullParser parser, String attribute) {
727 final String value = parseStringAttribute(parser, attribute);
728 if (TextUtils.isEmpty(value)) {
731 return ComponentName.unflattenFromString(value);
735 static Intent parseIntentAttributeNoDefault(XmlPullParser parser, String attribute) {
736 final String value = parseStringAttribute(parser, attribute);
737 Intent parsed = null;
738 if (!TextUtils.isEmpty(value)) {
740 parsed = Intent.parseUri(value, /* flags =*/ 0);
741 } catch (URISyntaxException e) {
742 Slog.e(TAG, "Error parsing intent", e);
749 static Intent parseIntentAttribute(XmlPullParser parser, String attribute) {
750 Intent parsed = parseIntentAttributeNoDefault(parser, attribute);
751 if (parsed == null) {
753 parsed = new Intent(Intent.ACTION_VIEW);
758 static void writeTagValue(XmlSerializer out, String tag, String value) throws IOException {
759 if (TextUtils.isEmpty(value)) return;
761 out.startTag(null, tag);
762 out.attribute(null, ATTR_VALUE, value);
763 out.endTag(null, tag);
766 static void writeTagValue(XmlSerializer out, String tag, long value) throws IOException {
767 writeTagValue(out, tag, Long.toString(value));
770 static void writeTagValue(XmlSerializer out, String tag, ComponentName name) throws IOException {
771 if (name == null) return;
772 writeTagValue(out, tag, name.flattenToString());
775 static void writeTagExtra(XmlSerializer out, String tag, PersistableBundle bundle)
776 throws IOException, XmlPullParserException {
777 if (bundle == null) return;
779 out.startTag(null, tag);
780 bundle.saveToXml(out);
781 out.endTag(null, tag);
784 static void writeAttr(XmlSerializer out, String name, CharSequence value) throws IOException {
785 if (TextUtils.isEmpty(value)) return;
787 out.attribute(null, name, value.toString());
790 static void writeAttr(XmlSerializer out, String name, long value) throws IOException {
791 writeAttr(out, name, String.valueOf(value));
794 static void writeAttr(XmlSerializer out, String name, boolean value) throws IOException {
796 writeAttr(out, name, "1");
800 static void writeAttr(XmlSerializer out, String name, ComponentName comp) throws IOException {
801 if (comp == null) return;
802 writeAttr(out, name, comp.flattenToString());
805 static void writeAttr(XmlSerializer out, String name, Intent intent) throws IOException {
806 if (intent == null) return;
808 writeAttr(out, name, intent.toUri(/* flags =*/ 0));
812 void saveBaseStateLocked() {
813 final AtomicFile file = getBaseStateFile();
815 Slog.d(TAG, "Saving to " + file.getBaseFile());
818 FileOutputStream outs = null;
820 outs = file.startWrite();
823 XmlSerializer out = new FastXmlSerializer();
824 out.setOutput(outs, StandardCharsets.UTF_8.name());
825 out.startDocument(null, true);
826 out.startTag(null, TAG_ROOT);
829 writeTagValue(out, TAG_LAST_RESET_TIME, mRawLastResetTime);
832 out.endTag(null, TAG_ROOT);
836 file.finishWrite(outs);
837 } catch (IOException e) {
838 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
839 file.failWrite(outs);
843 private void loadBaseStateLocked() {
844 mRawLastResetTime = 0;
846 final AtomicFile file = getBaseStateFile();
848 Slog.d(TAG, "Loading from " + file.getBaseFile());
850 try (FileInputStream in = file.openRead()) {
851 XmlPullParser parser = Xml.newPullParser();
852 parser.setInput(in, StandardCharsets.UTF_8.name());
855 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
856 if (type != XmlPullParser.START_TAG) {
859 final int depth = parser.getDepth();
860 // Check the root tag
861 final String tag = parser.getName();
863 if (!TAG_ROOT.equals(tag)) {
864 Slog.e(TAG, "Invalid root tag: " + tag);
871 case TAG_LAST_RESET_TIME:
872 mRawLastResetTime = parseLongAttribute(parser, ATTR_VALUE);
875 Slog.e(TAG, "Invalid tag: " + tag);
879 } catch (FileNotFoundException e) {
881 } catch (IOException | XmlPullParserException e) {
882 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
884 mRawLastResetTime = 0;
886 // Adjust the last reset time.
887 getLastResetTimeLocked();
891 final File getUserFile(@UserIdInt int userId) {
892 return new File(injectUserDataPath(userId), FILENAME_USER_PACKAGES);
895 private void saveUserLocked(@UserIdInt int userId) {
896 final File path = getUserFile(userId);
898 Slog.d(TAG, "Saving to " + path);
900 path.getParentFile().mkdirs();
901 final AtomicFile file = new AtomicFile(path);
902 FileOutputStream os = null;
904 os = file.startWrite();
906 saveUserInternalLocked(userId, os, /* forBackup= */ false);
908 file.finishWrite(os);
910 // Remove all dangling bitmap files.
911 cleanupDanglingBitmapDirectoriesLocked(userId);
912 } catch (XmlPullParserException | IOException e) {
913 Slog.e(TAG, "Failed to write to file " + file.getBaseFile(), e);
918 private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
919 boolean forBackup) throws IOException, XmlPullParserException {
921 final BufferedOutputStream bos = new BufferedOutputStream(os);
924 XmlSerializer out = new FastXmlSerializer();
925 out.setOutput(bos, StandardCharsets.UTF_8.name());
926 out.startDocument(null, true);
928 getUserShortcutsLocked(userId).saveToXml(out, forBackup);
936 static IOException throwForInvalidTag(int depth, String tag) throws IOException {
937 throw new IOException(String.format("Invalid tag '%s' found at depth %d", tag, depth));
940 static void warnForInvalidTag(int depth, String tag) throws IOException {
941 Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
945 private ShortcutUser loadUserLocked(@UserIdInt int userId) {
946 final File path = getUserFile(userId);
948 Slog.d(TAG, "Loading from " + path);
950 final AtomicFile file = new AtomicFile(path);
952 final FileInputStream in;
954 in = file.openRead();
955 } catch (FileNotFoundException e) {
957 Slog.d(TAG, "Not found " + path);
962 final ShortcutUser ret = loadUserInternal(userId, in, /* forBackup= */ false);
964 } catch (IOException | XmlPullParserException e) {
965 Slog.e(TAG, "Failed to read file " + file.getBaseFile(), e);
968 IoUtils.closeQuietly(in);
972 private ShortcutUser loadUserInternal(@UserIdInt int userId, InputStream is,
973 boolean fromBackup) throws XmlPullParserException, IOException {
975 final BufferedInputStream bis = new BufferedInputStream(is);
977 ShortcutUser ret = null;
978 XmlPullParser parser = Xml.newPullParser();
979 parser.setInput(bis, StandardCharsets.UTF_8.name());
982 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
983 if (type != XmlPullParser.START_TAG) {
986 final int depth = parser.getDepth();
988 final String tag = parser.getName();
990 Slog.d(TAG, String.format("depth=%d type=%d name=%s",
993 if ((depth == 1) && ShortcutUser.TAG_ROOT.equals(tag)) {
994 ret = ShortcutUser.loadFromXml(this, parser, userId, fromBackup);
997 throwForInvalidTag(depth, tag);
1002 private void scheduleSaveBaseState() {
1003 scheduleSaveInner(UserHandle.USER_NULL); // Special case -- use USER_NULL for base state.
1006 void scheduleSaveUser(@UserIdInt int userId) {
1007 scheduleSaveInner(userId);
1010 // In order to re-schedule, we need to reuse the same instance, so keep it in final.
1011 private final Runnable mSaveDirtyInfoRunner = this::saveDirtyInfo;
1013 private void scheduleSaveInner(@UserIdInt int userId) {
1015 Slog.d(TAG, "Scheduling to save for " + userId);
1017 synchronized (mLock) {
1018 if (!mDirtyUserIds.contains(userId)) {
1019 mDirtyUserIds.add(userId);
1022 // If already scheduled, remove that and re-schedule in N seconds.
1023 mHandler.removeCallbacks(mSaveDirtyInfoRunner);
1024 mHandler.postDelayed(mSaveDirtyInfoRunner, mSaveDelayMillis);
1028 void saveDirtyInfo() {
1030 Slog.d(TAG, "saveDirtyInfo");
1033 synchronized (mLock) {
1034 for (int i = mDirtyUserIds.size() - 1; i >= 0; i--) {
1035 final int userId = mDirtyUserIds.get(i);
1036 if (userId == UserHandle.USER_NULL) { // USER_NULL for base state.
1037 saveBaseStateLocked();
1039 saveUserLocked(userId);
1042 mDirtyUserIds.clear();
1044 } catch (Exception e) {
1045 wtf("Exception in saveDirtyInfo", e);
1049 /** Return the last reset time. */
1050 long getLastResetTimeLocked() {
1051 updateTimesLocked();
1052 return mRawLastResetTime;
1055 /** Return the next reset time. */
1056 long getNextResetTimeLocked() {
1057 updateTimesLocked();
1058 return mRawLastResetTime + mResetInterval;
1061 static boolean isClockValid(long time) {
1062 return time >= 1420070400; // Thu, 01 Jan 2015 00:00:00 GMT
1066 * Update the last reset time.
1068 private void updateTimesLocked() {
1070 final long now = injectCurrentTimeMillis();
1072 final long prevLastResetTime = mRawLastResetTime;
1074 if (mRawLastResetTime == 0) { // first launch.
1076 mRawLastResetTime = now;
1077 } else if (now < mRawLastResetTime) {
1079 if (isClockValid(now)) {
1080 Slog.w(TAG, "Clock rewound");
1082 mRawLastResetTime = now;
1085 if ((mRawLastResetTime + mResetInterval) <= now) {
1086 final long offset = mRawLastResetTime % mResetInterval;
1087 mRawLastResetTime = ((now / mResetInterval) * mResetInterval) + offset;
1090 if (prevLastResetTime != mRawLastResetTime) {
1091 scheduleSaveBaseState();
1095 // Requires mLock held, but "Locked" prefix would look weired so we just say "L".
1096 protected boolean isUserUnlockedL(@UserIdInt int userId) {
1097 // First, check the local copy.
1098 if (mUnlockedUsers.get(userId)) {
1101 // If the local copy says the user is locked, check with AM for the actual state, since
1102 // the user might just have been unlocked.
1103 // Note we just don't use isUserUnlockingOrUnlocked() here, because it'll return false
1104 // when the user is STOPPING, which we still want to consider as "unlocked".
1105 final long token = injectClearCallingIdentity();
1107 return mUserManager.isUserUnlockingOrUnlocked(userId);
1109 injectRestoreCallingIdentity(token);
1113 // Requires mLock held, but "Locked" prefix would look weired so we jsut say "L".
1114 void throwIfUserLockedL(@UserIdInt int userId) {
1115 if (!isUserUnlockedL(userId)) {
1116 throw new IllegalStateException("User " + userId + " is locked or not running");
1122 private boolean isUserLoadedLocked(@UserIdInt int userId) {
1123 return mUsers.get(userId) != null;
1126 /** Return the per-user state. */
1129 ShortcutUser getUserShortcutsLocked(@UserIdInt int userId) {
1130 if (!isUserUnlockedL(userId)) {
1131 wtf("User still locked");
1134 ShortcutUser userPackages = mUsers.get(userId);
1135 if (userPackages == null) {
1136 userPackages = loadUserLocked(userId);
1137 if (userPackages == null) {
1138 userPackages = new ShortcutUser(this, userId);
1140 mUsers.put(userId, userPackages);
1142 // Also when a user's data is first accessed, scan all packages.
1143 checkPackageChanges(userId);
1145 return userPackages;
1148 void forEachLoadedUserLocked(@NonNull Consumer<ShortcutUser> c) {
1149 for (int i = mUsers.size() - 1; i >= 0; i--) {
1150 c.accept(mUsers.valueAt(i));
1154 /** Return the per-user per-package state. */
1157 ShortcutPackage getPackageShortcutsLocked(
1158 @NonNull String packageName, @UserIdInt int userId) {
1159 return getUserShortcutsLocked(userId).getPackageShortcuts(packageName);
1164 ShortcutLauncher getLauncherShortcutsLocked(
1165 @NonNull String packageName, @UserIdInt int ownerUserId,
1166 @UserIdInt int launcherUserId) {
1167 return getUserShortcutsLocked(ownerUserId)
1168 .getLauncherShortcuts(packageName, launcherUserId);
1171 // === Caller validation ===
1173 void removeIcon(@UserIdInt int userId, ShortcutInfo shortcut) {
1174 // Do not remove the actual bitmap file yet, because if the device crashes before saving
1175 // he XML we'd lose the icon. We just remove all dangling files after saving the XML.
1176 shortcut.setIconResourceId(0);
1177 shortcut.setIconResName(null);
1178 shortcut.clearFlags(ShortcutInfo.FLAG_HAS_ICON_FILE | ShortcutInfo.FLAG_HAS_ICON_RES);
1181 public void cleanupBitmapsForPackage(@UserIdInt int userId, String packageName) {
1182 final File packagePath = new File(getUserBitmapFilePath(userId), packageName);
1183 if (!packagePath.isDirectory()) {
1186 if (!(FileUtils.deleteContents(packagePath) && packagePath.delete())) {
1187 Slog.w(TAG, "Unable to remove directory " + packagePath);
1191 private void cleanupDanglingBitmapDirectoriesLocked(@UserIdInt int userId) {
1193 Slog.d(TAG, "cleanupDanglingBitmaps: userId=" + userId);
1195 final long start = injectElapsedRealtime();
1197 final ShortcutUser user = getUserShortcutsLocked(userId);
1199 final File bitmapDir = getUserBitmapFilePath(userId);
1200 final File[] children = bitmapDir.listFiles();
1201 if (children == null) {
1204 for (File child : children) {
1205 if (!child.isDirectory()) {
1208 final String packageName = child.getName();
1210 Slog.d(TAG, "cleanupDanglingBitmaps: Found directory=" + packageName);
1212 if (!user.hasPackage(packageName)) {
1214 Slog.d(TAG, "Removing dangling bitmap directory: " + packageName);
1216 cleanupBitmapsForPackage(userId, packageName);
1218 cleanupDanglingBitmapFilesLocked(userId, user, packageName, child);
1221 logDurationStat(Stats.CLEANUP_DANGLING_BITMAPS, start);
1224 private void cleanupDanglingBitmapFilesLocked(@UserIdInt int userId, @NonNull ShortcutUser user,
1225 @NonNull String packageName, @NonNull File path) {
1226 final ArraySet<String> usedFiles =
1227 user.getPackageShortcuts(packageName).getUsedBitmapFiles();
1229 for (File child : path.listFiles()) {
1230 if (!child.isFile()) {
1233 final String name = child.getName();
1234 if (!usedFiles.contains(name)) {
1236 Slog.d(TAG, "Removing dangling bitmap file: " + child.getAbsolutePath());
1244 static class FileOutputStreamWithPath extends FileOutputStream {
1245 private final File mFile;
1247 public FileOutputStreamWithPath(File file) throws FileNotFoundException {
1252 public File getFile() {
1258 * Build the cached bitmap filename for a shortcut icon.
1260 * The filename will be based on the ID, except certain characters will be escaped.
1263 FileOutputStreamWithPath openIconFileForWrite(@UserIdInt int userId, ShortcutInfo shortcut)
1264 throws IOException {
1265 final File packagePath = new File(getUserBitmapFilePath(userId),
1266 shortcut.getPackage());
1267 if (!packagePath.isDirectory()) {
1268 packagePath.mkdirs();
1269 if (!packagePath.isDirectory()) {
1270 throw new IOException("Unable to create directory " + packagePath);
1272 SELinux.restorecon(packagePath);
1275 final String baseName = String.valueOf(injectCurrentTimeMillis());
1276 for (int suffix = 0; ; suffix++) {
1277 final String filename = (suffix == 0 ? baseName : baseName + "_" + suffix) + ".png";
1278 final File file = new File(packagePath, filename);
1279 if (!file.exists()) {
1281 Slog.d(TAG, "Saving icon to " + file.getAbsolutePath());
1283 return new FileOutputStreamWithPath(file);
1288 void saveIconAndFixUpShortcut(@UserIdInt int userId, ShortcutInfo shortcut) {
1289 if (shortcut.hasIconFile() || shortcut.hasIconResource()) {
1293 final long token = injectClearCallingIdentity();
1295 // Clear icon info on the shortcut.
1296 removeIcon(userId, shortcut);
1298 final Icon icon = shortcut.getIcon();
1300 return; // has no icon
1305 switch (icon.getType()) {
1306 case Icon.TYPE_RESOURCE: {
1307 injectValidateIconResPackage(shortcut, icon);
1309 shortcut.setIconResourceId(icon.getResId());
1310 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_RES);
1313 case Icon.TYPE_BITMAP: {
1314 bitmap = icon.getBitmap(); // Don't recycle in this case.
1318 // This shouldn't happen because we've already validated the icon, but
1320 throw ShortcutInfo.getInvalidIconException();
1322 if (bitmap == null) {
1323 Slog.e(TAG, "Null bitmap detected");
1326 // Shrink and write to the file.
1329 final FileOutputStreamWithPath out = openIconFileForWrite(userId, shortcut);
1331 path = out.getFile();
1333 Bitmap shrunk = shrinkBitmap(bitmap, mMaxIconDimension);
1335 shrunk.compress(mIconPersistFormat, mIconPersistQuality, out);
1337 if (bitmap != shrunk) {
1342 shortcut.setBitmapPath(out.getFile().getAbsolutePath());
1343 shortcut.addFlags(ShortcutInfo.FLAG_HAS_ICON_FILE);
1345 IoUtils.closeQuietly(out);
1347 } catch (IOException | RuntimeException e) {
1348 // STOPSHIP Change wtf to e
1349 Slog.wtf(ShortcutService.TAG, "Unable to write bitmap to file", e);
1350 if (path != null && path.exists()) {
1355 // Once saved, we won't use the original icon information, so null it out.
1356 shortcut.clearIcon();
1359 injectRestoreCallingIdentity(token);
1363 // Unfortunately we can't do this check in unit tests because we fake creator package names,
1364 // so override in unit tests.
1365 // TODO CTS this case.
1366 void injectValidateIconResPackage(ShortcutInfo shortcut, Icon icon) {
1367 if (!shortcut.getPackage().equals(icon.getResPackage())) {
1368 throw new IllegalArgumentException(
1369 "Icon resource must reside in shortcut owner package");
1374 static Bitmap shrinkBitmap(Bitmap in, int maxSize) {
1375 // Original width/height.
1376 final int ow = in.getWidth();
1377 final int oh = in.getHeight();
1378 if ((ow <= maxSize) && (oh <= maxSize)) {
1380 Slog.d(TAG, String.format("Icon size %dx%d, no need to shrink", ow, oh));
1384 final int longerDimension = Math.max(ow, oh);
1386 // New width and height.
1387 final int nw = ow * maxSize / longerDimension;
1388 final int nh = oh * maxSize / longerDimension;
1390 Slog.d(TAG, String.format("Icon size %dx%d, shrinking to %dx%d",
1394 final Bitmap scaledBitmap = Bitmap.createBitmap(nw, nh, Bitmap.Config.ARGB_8888);
1395 final Canvas c = new Canvas(scaledBitmap);
1397 final RectF dst = new RectF(0, 0, nw, nh);
1399 c.drawBitmap(in, /*src=*/ null, dst, /* paint =*/ null);
1401 return scaledBitmap;
1405 * For a shortcut, update all resource names from resource IDs, and also update all
1406 * resource-based strings.
1408 void fixUpShortcutResourceNamesAndValues(ShortcutInfo si) {
1409 final Resources publisherRes = injectGetResourcesForApplicationAsUser(
1410 si.getPackage(), si.getUserId());
1411 if (publisherRes != null) {
1412 final long start = injectElapsedRealtime();
1414 si.lookupAndFillInResourceNames(publisherRes);
1416 logDurationStat(Stats.RESOURCE_NAME_LOOKUP, start);
1418 si.resolveResourceStrings(publisherRes);
1422 // === Caller validation ===
1424 private boolean isCallerSystem() {
1425 final int callingUid = injectBinderCallingUid();
1426 return UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
1429 private boolean isCallerShell() {
1430 final int callingUid = injectBinderCallingUid();
1431 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
1434 private void enforceSystemOrShell() {
1435 if (!(isCallerSystem() || isCallerShell())) {
1436 throw new SecurityException("Caller must be system or shell");
1440 private void enforceShell() {
1441 if (!isCallerShell()) {
1442 throw new SecurityException("Caller must be shell");
1446 private void enforceSystem() {
1447 if (!isCallerSystem()) {
1448 throw new SecurityException("Caller must be system");
1452 private void enforceResetThrottlingPermission() {
1453 if (isCallerSystem()) {
1456 enforceCallingOrSelfPermission(
1457 android.Manifest.permission.RESET_SHORTCUT_MANAGER_THROTTLING, null);
1460 private void enforceCallingOrSelfPermission(
1461 @NonNull String permission, @Nullable String message) {
1462 if (isCallerSystem()) {
1465 injectEnforceCallingPermission(permission, message);
1469 * Somehow overriding ServiceContext.enforceCallingPermission() in the unit tests would confuse
1470 * mockito. So instead we extracted it here and override it in the tests.
1473 void injectEnforceCallingPermission(
1474 @NonNull String permission, @Nullable String message) {
1475 mContext.enforceCallingPermission(permission, message);
1478 private void verifyCaller(@NonNull String packageName, @UserIdInt int userId) {
1479 Preconditions.checkStringNotEmpty(packageName, "packageName");
1481 if (isCallerSystem()) {
1485 final int callingUid = injectBinderCallingUid();
1487 // Otherwise, make sure the arguments are valid.
1488 if (UserHandle.getUserId(callingUid) != userId) {
1489 throw new SecurityException("Invalid user-ID");
1491 if (injectGetPackageUid(packageName, userId) == injectBinderCallingUid()) {
1492 return; // Caller is valid.
1494 throw new SecurityException("Calling package name mismatch");
1497 // Overridden in unit tests to execute r synchronously.
1498 void injectPostToHandler(Runnable r) {
1502 void injectRunOnNewThread(Runnable r) {
1503 new Thread(r).start();
1507 * @throws IllegalArgumentException if {@code numShortcuts} is bigger than
1508 * {@link #getMaxActivityShortcuts()}.
1510 void enforceMaxActivityShortcuts(int numShortcuts) {
1511 if (numShortcuts > mMaxShortcuts) {
1512 throw new IllegalArgumentException("Max number of dynamic shortcuts exceeded");
1517 * Return the max number of dynamic + manifest shortcuts for each launcher icon.
1519 int getMaxActivityShortcuts() {
1520 return mMaxShortcuts;
1524 * - Sends a notification to LauncherApps
1527 void packageShortcutsChanged(@NonNull String packageName, @UserIdInt int userId) {
1529 Slog.d(TAG, String.format(
1530 "Shortcut changes: package=%s, user=%d", packageName, userId));
1532 notifyListeners(packageName, userId);
1533 scheduleSaveUser(userId);
1536 private void notifyListeners(@NonNull String packageName, @UserIdInt int userId) {
1537 injectPostToHandler(() -> {
1539 final ArrayList<ShortcutChangeListener> copy;
1540 synchronized (mLock) {
1541 if (!isUserUnlockedL(userId)) {
1545 copy = new ArrayList<>(mListeners);
1547 // Note onShortcutChanged() needs to be called with the system service permissions.
1548 for (int i = copy.size() - 1; i >= 0; i--) {
1549 copy.get(i).onShortcutChanged(packageName, userId);
1551 } catch (Exception ignore) {
1557 * Clean up / validate an incoming shortcut.
1558 * - Make sure all mandatory fields are set.
1559 * - Make sure the intent's extras are persistable, and them to set
1560 * {@link ShortcutInfo#mIntentPersistableExtrases}. Also clear its extras.
1563 * TODO Detailed unit tests
1565 private void fixUpIncomingShortcutInfo(@NonNull ShortcutInfo shortcut, boolean forUpdate) {
1566 Preconditions.checkNotNull(shortcut, "Null shortcut detected");
1567 if (shortcut.getActivity() != null) {
1568 Preconditions.checkState(
1569 shortcut.getPackage().equals(shortcut.getActivity().getPackageName()),
1570 "Cannot publish shortcut: activity " + shortcut.getActivity() + " does not"
1571 + " belong to package " + shortcut.getPackage());
1572 Preconditions.checkState(
1573 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1574 "Cannot publish shortcut: activity " + shortcut.getActivity() + " is not"
1575 + " main activity");
1579 shortcut.enforceMandatoryFields();
1580 Preconditions.checkArgument(
1581 injectIsMainActivity(shortcut.getActivity(), shortcut.getUserId()),
1582 "Cannot publish shortcut: " + shortcut.getActivity() + " is not main activity");
1584 if (shortcut.getIcon() != null) {
1585 ShortcutInfo.validateIcon(shortcut.getIcon());
1588 shortcut.replaceFlags(0);
1592 * When a shortcut has no target activity, set the default one from the package.
1594 private void fillInDefaultActivity(List<ShortcutInfo> shortcuts) {
1596 ComponentName defaultActivity = null;
1597 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1598 final ShortcutInfo si = shortcuts.get(i);
1599 if (si.getActivity() == null) {
1600 if (defaultActivity == null) {
1601 defaultActivity = injectGetDefaultMainActivity(
1602 si.getPackage(), si.getUserId());
1603 Preconditions.checkState(defaultActivity != null,
1604 "Launcher activity not found for package " + si.getPackage());
1606 si.setActivity(defaultActivity);
1611 private void assignImplicitRanks(List<ShortcutInfo> shortcuts) {
1612 for (int i = shortcuts.size() - 1; i >= 0; i--) {
1613 shortcuts.get(i).setImplicitRank(i);
1620 public boolean setDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1621 @UserIdInt int userId) {
1622 verifyCaller(packageName, userId);
1624 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1625 final int size = newShortcuts.size();
1627 synchronized (mLock) {
1628 throwIfUserLockedL(userId);
1630 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1631 ps.getUser().onCalledByPublisher(packageName);
1633 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1635 fillInDefaultActivity(newShortcuts);
1637 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_SET);
1640 if (!ps.tryApiCall()) {
1644 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1645 ps.clearAllImplicitRanks();
1646 assignImplicitRanks(newShortcuts);
1648 for (int i = 0; i < size; i++) {
1649 fixUpIncomingShortcutInfo(newShortcuts.get(i), /* forUpdate= */ false);
1652 // First, remove all un-pinned; dynamic shortcuts
1653 ps.deleteAllDynamicShortcuts();
1655 // Then, add/update all. We need to make sure to take over "pinned" flag.
1656 for (int i = 0; i < size; i++) {
1657 final ShortcutInfo newShortcut = newShortcuts.get(i);
1658 ps.addOrUpdateDynamicShortcut(newShortcut);
1661 // Lastly, adjust the ranks.
1664 packageShortcutsChanged(packageName, userId);
1672 public boolean updateShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1673 @UserIdInt int userId) {
1674 verifyCaller(packageName, userId);
1676 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1677 final int size = newShortcuts.size();
1679 synchronized (mLock) {
1680 throwIfUserLockedL(userId);
1682 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1683 ps.getUser().onCalledByPublisher(packageName);
1685 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1687 // For update, don't fill in the default activity. Having null activity means
1688 // "don't update the activity" here.
1690 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_UPDATE);
1693 if (!ps.tryApiCall()) {
1697 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1698 ps.clearAllImplicitRanks();
1699 assignImplicitRanks(newShortcuts);
1701 for (int i = 0; i < size; i++) {
1702 final ShortcutInfo source = newShortcuts.get(i);
1703 fixUpIncomingShortcutInfo(source, /* forUpdate= */ true);
1705 final ShortcutInfo target = ps.findShortcutById(source.getId());
1706 if (target == null) {
1710 if (target.isEnabled() != source.isEnabled()) {
1712 "ShortcutInfo.enabled cannot be changed with updateShortcuts()");
1715 // When updating the rank, we need to insert between existing ranks, so set
1716 // this setRankChanged, and also copy the implicit rank fo adjustRanks().
1717 if (source.hasRank()) {
1718 target.setRankChanged();
1719 target.setImplicitRank(source.getImplicitRank());
1722 final boolean replacingIcon = (source.getIcon() != null);
1723 if (replacingIcon) {
1724 removeIcon(userId, target);
1727 // Note copyNonNullFieldsFrom() does the "updatable with?" check too.
1728 target.copyNonNullFieldsFrom(source);
1729 target.setTimestamp(injectCurrentTimeMillis());
1731 if (replacingIcon) {
1732 saveIconAndFixUpShortcut(userId, target);
1735 // When we're updating any resource related fields, re-extract the res names and
1737 if (replacingIcon || source.hasStringResources()) {
1738 fixUpShortcutResourceNamesAndValues(target);
1742 // Lastly, adjust the ranks.
1745 packageShortcutsChanged(packageName, userId);
1753 public boolean addDynamicShortcuts(String packageName, ParceledListSlice shortcutInfoList,
1754 @UserIdInt int userId) {
1755 verifyCaller(packageName, userId);
1757 final List<ShortcutInfo> newShortcuts = (List<ShortcutInfo>) shortcutInfoList.getList();
1758 final int size = newShortcuts.size();
1760 synchronized (mLock) {
1761 throwIfUserLockedL(userId);
1763 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1764 ps.getUser().onCalledByPublisher(packageName);
1766 ps.ensureImmutableShortcutsNotIncluded(newShortcuts);
1768 fillInDefaultActivity(newShortcuts);
1770 ps.enforceShortcutCountsBeforeOperation(newShortcuts, OPERATION_ADD);
1772 // Initialize the implicit ranks for ShortcutPackage.adjustRanks().
1773 ps.clearAllImplicitRanks();
1774 assignImplicitRanks(newShortcuts);
1777 if (!ps.tryApiCall()) {
1780 for (int i = 0; i < size; i++) {
1781 final ShortcutInfo newShortcut = newShortcuts.get(i);
1783 // Validate the shortcut.
1784 fixUpIncomingShortcutInfo(newShortcut, /* forUpdate= */ false);
1786 // When ranks are changing, we need to insert between ranks, so set the
1787 // "rank changed" flag.
1788 newShortcut.setRankChanged();
1791 ps.addOrUpdateDynamicShortcut(newShortcut);
1794 // Lastly, adjust the ranks.
1797 packageShortcutsChanged(packageName, userId);
1805 public void disableShortcuts(String packageName, List shortcutIds,
1806 CharSequence disabledMessage, int disabledMessageResId, @UserIdInt int userId) {
1807 verifyCaller(packageName, userId);
1808 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1810 synchronized (mLock) {
1811 throwIfUserLockedL(userId);
1813 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1814 ps.getUser().onCalledByPublisher(packageName);
1816 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1818 final String disabledMessageString =
1819 (disabledMessage == null) ? null : disabledMessage.toString();
1821 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1822 ps.disableWithId(Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)),
1823 disabledMessageString, disabledMessageResId,
1824 /* overrideImmutable=*/ false);
1827 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1830 packageShortcutsChanged(packageName, userId);
1836 public void enableShortcuts(String packageName, List shortcutIds, @UserIdInt int userId) {
1837 verifyCaller(packageName, userId);
1838 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1840 synchronized (mLock) {
1841 throwIfUserLockedL(userId);
1843 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1844 ps.getUser().onCalledByPublisher(packageName);
1846 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1848 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1849 ps.enableWithId((String) shortcutIds.get(i));
1852 packageShortcutsChanged(packageName, userId);
1858 public void removeDynamicShortcuts(String packageName, List shortcutIds,
1859 @UserIdInt int userId) {
1860 verifyCaller(packageName, userId);
1861 Preconditions.checkNotNull(shortcutIds, "shortcutIds must be provided");
1863 synchronized (mLock) {
1864 throwIfUserLockedL(userId);
1866 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1867 ps.getUser().onCalledByPublisher(packageName);
1869 ps.ensureImmutableShortcutsNotIncludedWithIds((List<String>) shortcutIds);
1871 for (int i = shortcutIds.size() - 1; i >= 0; i--) {
1872 ps.deleteDynamicWithId(
1873 Preconditions.checkStringNotEmpty((String) shortcutIds.get(i)));
1876 // We may have removed dynamic shortcuts which may have left a gap, so adjust the ranks.
1879 packageShortcutsChanged(packageName, userId);
1885 public void removeAllDynamicShortcuts(String packageName, @UserIdInt int userId) {
1886 verifyCaller(packageName, userId);
1888 synchronized (mLock) {
1889 throwIfUserLockedL(userId);
1891 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1892 ps.getUser().onCalledByPublisher(packageName);
1893 ps.deleteAllDynamicShortcuts();
1895 packageShortcutsChanged(packageName, userId);
1901 public ParceledListSlice<ShortcutInfo> getDynamicShortcuts(String packageName,
1902 @UserIdInt int userId) {
1903 verifyCaller(packageName, userId);
1905 synchronized (mLock) {
1906 throwIfUserLockedL(userId);
1908 return getShortcutsWithQueryLocked(
1909 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1910 ShortcutInfo::isDynamic);
1915 public ParceledListSlice<ShortcutInfo> getManifestShortcuts(String packageName,
1916 @UserIdInt int userId) {
1917 verifyCaller(packageName, userId);
1919 synchronized (mLock) {
1920 throwIfUserLockedL(userId);
1922 return getShortcutsWithQueryLocked(
1923 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1924 ShortcutInfo::isManifestShortcut);
1929 public ParceledListSlice<ShortcutInfo> getPinnedShortcuts(String packageName,
1930 @UserIdInt int userId) {
1931 verifyCaller(packageName, userId);
1933 synchronized (mLock) {
1934 throwIfUserLockedL(userId);
1936 return getShortcutsWithQueryLocked(
1937 packageName, userId, ShortcutInfo.CLONE_REMOVE_FOR_CREATOR,
1938 ShortcutInfo::isPinned);
1942 private ParceledListSlice<ShortcutInfo> getShortcutsWithQueryLocked(@NonNull String packageName,
1943 @UserIdInt int userId, int cloneFlags, @NonNull Predicate<ShortcutInfo> query) {
1945 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
1947 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1948 ps.getUser().onCalledByPublisher(packageName);
1949 ps.findAll(ret, query, cloneFlags);
1951 return new ParceledListSlice<>(ret);
1955 public int getMaxShortcutCountPerActivity(String packageName, @UserIdInt int userId)
1956 throws RemoteException {
1957 verifyCaller(packageName, userId);
1959 return mMaxShortcuts;
1963 public int getRemainingCallCount(String packageName, @UserIdInt int userId) {
1964 verifyCaller(packageName, userId);
1966 synchronized (mLock) {
1967 throwIfUserLockedL(userId);
1969 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
1970 ps.getUser().onCalledByPublisher(packageName);
1971 return mMaxUpdatesPerInterval - ps.getApiCallCount();
1976 public long getRateLimitResetTime(String packageName, @UserIdInt int userId) {
1977 verifyCaller(packageName, userId);
1979 synchronized (mLock) {
1980 throwIfUserLockedL(userId);
1982 return getNextResetTimeLocked();
1987 public int getIconMaxDimensions(String packageName, int userId) {
1988 verifyCaller(packageName, userId);
1990 synchronized (mLock) {
1991 return mMaxIconDimension;
1996 public void reportShortcutUsed(String packageName, String shortcutId, int userId) {
1997 verifyCaller(packageName, userId);
1999 Preconditions.checkNotNull(shortcutId);
2002 Slog.d(TAG, String.format("reportShortcutUsed: Shortcut %s package %s used on user %d",
2003 shortcutId, packageName, userId));
2006 synchronized (mLock) {
2007 throwIfUserLockedL(userId);
2009 final ShortcutPackage ps = getPackageShortcutsLocked(packageName, userId);
2010 ps.getUser().onCalledByPublisher(packageName);
2012 if (ps.findShortcutById(shortcutId) == null) {
2013 Log.w(TAG, String.format("reportShortcutUsed: package %s doesn't have shortcut %s",
2014 packageName, shortcutId));
2019 final long token = injectClearCallingIdentity();
2021 mUsageStatsManagerInternal.reportShortcutUsage(packageName, shortcutId, userId);
2023 injectRestoreCallingIdentity(token);
2028 * Reset all throttling, for developer options and command line. Only system/shell can call
2032 public void resetThrottling() {
2033 enforceSystemOrShell();
2035 resetThrottlingInner(getCallingUserId());
2038 void resetThrottlingInner(@UserIdInt int userId) {
2039 synchronized (mLock) {
2040 if (!isUserUnlockedL(userId)) {
2041 Log.w(TAG, "User " + userId + " is locked or not running");
2045 getUserShortcutsLocked(userId).resetThrottling();
2047 scheduleSaveUser(userId);
2048 Slog.i(TAG, "ShortcutManager: throttling counter reset for user " + userId);
2051 void resetAllThrottlingInner() {
2052 synchronized (mLock) {
2053 mRawLastResetTime = injectCurrentTimeMillis();
2055 scheduleSaveBaseState();
2056 Slog.i(TAG, "ShortcutManager: throttling counter reset for all users");
2060 public void onApplicationActive(String packageName, int userId) {
2062 Slog.d(TAG, "onApplicationActive: package=" + packageName + " userid=" + userId);
2064 enforceResetThrottlingPermission();
2066 synchronized (mLock) {
2067 if (!isUserUnlockedL(userId)) {
2068 // This is called by system UI, so no need to throw. Just ignore.
2072 getPackageShortcutsLocked(packageName, userId)
2073 .resetRateLimitingForCommandLineNoSaving();
2074 saveUserLocked(userId);
2078 // We override this method in unit tests to do a simpler check.
2079 boolean hasShortcutHostPermission(@NonNull String callingPackage, int userId) {
2080 final long start = injectElapsedRealtime();
2082 return hasShortcutHostPermissionInner(callingPackage, userId);
2084 logDurationStat(Stats.LAUNCHER_PERMISSION_CHECK, start);
2088 // This method is extracted so we can directly call this method from unit tests,
2089 // even when hasShortcutPermission() is overridden.
2091 boolean hasShortcutHostPermissionInner(@NonNull String callingPackage, int userId) {
2092 synchronized (mLock) {
2093 throwIfUserLockedL(userId);
2095 final ShortcutUser user = getUserShortcutsLocked(userId);
2097 // Always trust the in-memory cache.
2098 final ComponentName cached = user.getCachedLauncher();
2099 if (cached != null) {
2100 if (cached.getPackageName().equals(callingPackage)) {
2104 // If the cached one doesn't match, then go ahead
2106 final List<ResolveInfo> allHomeCandidates = new ArrayList<>();
2108 // Default launcher from package manager.
2109 final long startGetHomeActivitiesAsUser = injectElapsedRealtime();
2110 final ComponentName defaultLauncher = mPackageManagerInternal
2111 .getHomeActivitiesAsUser(allHomeCandidates, userId);
2112 logDurationStat(Stats.GET_DEFAULT_HOME, startGetHomeActivitiesAsUser);
2114 ComponentName detected;
2115 if (defaultLauncher != null) {
2116 detected = defaultLauncher;
2118 Slog.v(TAG, "Default launcher from PM: " + detected);
2121 detected = user.getLastKnownLauncher();
2123 if (detected != null) {
2124 if (injectIsActivityEnabledAndExported(detected, userId)) {
2126 Slog.v(TAG, "Cached launcher: " + detected);
2129 Slog.w(TAG, "Cached launcher " + detected + " no longer exists");
2131 user.clearLauncher();
2136 if (detected == null) {
2137 // If we reach here, that means it's the first check since the user was created,
2138 // and there's already multiple launchers and there's no default set.
2139 // Find the system one with the highest priority.
2140 // (We need to check the priority too because of FallbackHome in Settings.)
2141 // If there's no system launcher yet, then no one can access shortcuts, until
2142 // the user explicitly
2143 final int size = allHomeCandidates.size();
2145 int lastPriority = Integer.MIN_VALUE;
2146 for (int i = 0; i < size; i++) {
2147 final ResolveInfo ri = allHomeCandidates.get(i);
2148 if (!ri.activityInfo.applicationInfo.isSystemApp()) {
2152 Slog.d(TAG, String.format("hasShortcutPermissionInner: pkg=%s prio=%d",
2153 ri.activityInfo.getComponentName(), ri.priority));
2155 if (ri.priority < lastPriority) {
2158 detected = ri.activityInfo.getComponentName();
2159 lastPriority = ri.priority;
2163 // Update the cache.
2164 user.setLauncher(detected);
2165 if (detected != null) {
2167 Slog.v(TAG, "Detected launcher: " + detected);
2169 return detected.getPackageName().equals(callingPackage);
2171 // Default launcher not found.
2177 // === House keeping ===
2179 private void cleanUpPackageForAllLoadedUsers(String packageName, @UserIdInt int packageUserId,
2180 boolean appStillExists) {
2181 synchronized (mLock) {
2182 forEachLoadedUserLocked(user ->
2183 cleanUpPackageLocked(packageName, user.getUserId(), packageUserId,
2189 * Remove all the information associated with a package. This will really remove all the
2190 * information, including the restore information (i.e. it'll remove packages even if they're
2193 * This is called when an app is uninstalled, or an app gets "clear data"ed.
2196 void cleanUpPackageLocked(String packageName, int owningUserId, int packageUserId,
2197 boolean appStillExists) {
2198 final boolean wasUserLoaded = isUserLoadedLocked(owningUserId);
2200 final ShortcutUser user = getUserShortcutsLocked(owningUserId);
2201 boolean doNotify = false;
2203 // First, remove the package from the package list (if the package is a publisher).
2204 if (packageUserId == owningUserId) {
2205 if (user.removePackage(packageName) != null) {
2210 // Also remove from the launcher list (if the package is a launcher).
2211 user.removeLauncher(packageUserId, packageName);
2213 // Then remove pinned shortcuts from all launchers.
2214 user.forAllLaunchers(l -> l.cleanUpPackage(packageName, packageUserId));
2216 // Now there may be orphan shortcuts because we removed pinned shortcuts at the previous
2217 // step. Remove them too.
2218 user.forAllPackages(p -> p.refreshPinnedFlags());
2220 scheduleSaveUser(owningUserId);
2223 notifyListeners(packageName, owningUserId);
2226 // If the app still exists (i.e. data cleared), we need to re-publish manifest shortcuts.
2227 if (appStillExists && (packageUserId == owningUserId)) {
2228 // This will do the notification and save when needed, so do it after the above
2230 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2233 if (!wasUserLoaded) {
2234 // Note this will execute the scheduled save.
2235 unloadUserLocked(owningUserId);
2240 * Entry point from {@link LauncherApps}.
2242 private class LocalService extends ShortcutServiceInternal {
2245 public List<ShortcutInfo> getShortcuts(int launcherUserId,
2246 @NonNull String callingPackage, long changedSince,
2247 @Nullable String packageName, @Nullable List<String> shortcutIds,
2248 @Nullable ComponentName componentName,
2249 int queryFlags, int userId) {
2250 final ArrayList<ShortcutInfo> ret = new ArrayList<>();
2252 final boolean cloneKeyFieldOnly =
2253 ((queryFlags & ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY) != 0);
2254 final int cloneFlag = cloneKeyFieldOnly ? ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO
2255 : ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER;
2256 if (packageName == null) {
2257 shortcutIds = null; // LauncherAppsService already threw for it though.
2260 synchronized (mLock) {
2261 throwIfUserLockedL(userId);
2262 throwIfUserLockedL(launcherUserId);
2264 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2265 .attemptToRestoreIfNeededAndSave();
2267 if (packageName != null) {
2268 getShortcutsInnerLocked(launcherUserId,
2269 callingPackage, packageName, shortcutIds, changedSince,
2270 componentName, queryFlags, userId, ret, cloneFlag);
2272 final List<String> shortcutIdsF = shortcutIds;
2273 getUserShortcutsLocked(userId).forAllPackages(p -> {
2274 getShortcutsInnerLocked(launcherUserId,
2275 callingPackage, p.getPackageName(), shortcutIdsF, changedSince,
2276 componentName, queryFlags, userId, ret, cloneFlag);
2283 private void getShortcutsInnerLocked(int launcherUserId, @NonNull String callingPackage,
2284 @Nullable String packageName, @Nullable List<String> shortcutIds, long changedSince,
2285 @Nullable ComponentName componentName, int queryFlags,
2286 int userId, ArrayList<ShortcutInfo> ret, int cloneFlag) {
2287 final ArraySet<String> ids = shortcutIds == null ? null
2288 : new ArraySet<>(shortcutIds);
2290 final ShortcutPackage p = getUserShortcutsLocked(userId)
2291 .getPackageShortcutsIfExists(packageName);
2293 return; // No need to instantiate ShortcutPackage.
2297 (ShortcutInfo si) -> {
2298 if (si.getLastChangedTimestamp() < changedSince) {
2301 if (ids != null && !ids.contains(si.getId())) {
2304 if (componentName != null) {
2305 if (si.getActivity() != null
2306 && !si.getActivity().equals(componentName)) {
2310 if (((queryFlags & ShortcutQuery.FLAG_GET_DYNAMIC) != 0)
2311 && si.isDynamic()) {
2314 if (((queryFlags & ShortcutQuery.FLAG_GET_PINNED) != 0)
2318 if (((queryFlags & ShortcutQuery.FLAG_GET_MANIFEST) != 0)
2319 && si.isManifestShortcut()) {
2323 }, cloneFlag, callingPackage, launcherUserId);
2327 public boolean isPinnedByCaller(int launcherUserId, @NonNull String callingPackage,
2328 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2329 Preconditions.checkStringNotEmpty(packageName, "packageName");
2330 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2332 synchronized (mLock) {
2333 throwIfUserLockedL(userId);
2334 throwIfUserLockedL(launcherUserId);
2336 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2337 .attemptToRestoreIfNeededAndSave();
2339 final ShortcutInfo si = getShortcutInfoLocked(
2340 launcherUserId, callingPackage, packageName, shortcutId, userId);
2341 return si != null && si.isPinned();
2345 private ShortcutInfo getShortcutInfoLocked(
2346 int launcherUserId, @NonNull String callingPackage,
2347 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2348 Preconditions.checkStringNotEmpty(packageName, "packageName");
2349 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId");
2351 throwIfUserLockedL(userId);
2352 throwIfUserLockedL(launcherUserId);
2354 final ShortcutPackage p = getUserShortcutsLocked(userId)
2355 .getPackageShortcutsIfExists(packageName);
2360 final ArrayList<ShortcutInfo> list = new ArrayList<>(1);
2362 (ShortcutInfo si) -> shortcutId.equals(si.getId()),
2363 /* clone flags=*/ 0, callingPackage, launcherUserId);
2364 return list.size() == 0 ? null : list.get(0);
2368 public void pinShortcuts(int launcherUserId,
2369 @NonNull String callingPackage, @NonNull String packageName,
2370 @NonNull List<String> shortcutIds, int userId) {
2371 // Calling permission must be checked by LauncherAppsImpl.
2372 Preconditions.checkStringNotEmpty(packageName, "packageName");
2373 Preconditions.checkNotNull(shortcutIds, "shortcutIds");
2375 synchronized (mLock) {
2376 throwIfUserLockedL(userId);
2377 throwIfUserLockedL(launcherUserId);
2379 final ShortcutLauncher launcher =
2380 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId);
2381 launcher.attemptToRestoreIfNeededAndSave();
2383 launcher.pinShortcuts(userId, packageName, shortcutIds);
2385 packageShortcutsChanged(packageName, userId);
2391 public Intent[] createShortcutIntents(int launcherUserId,
2392 @NonNull String callingPackage,
2393 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2394 // Calling permission must be checked by LauncherAppsImpl.
2395 Preconditions.checkStringNotEmpty(packageName, "packageName can't be empty");
2396 Preconditions.checkStringNotEmpty(shortcutId, "shortcutId can't be empty");
2398 synchronized (mLock) {
2399 throwIfUserLockedL(userId);
2400 throwIfUserLockedL(launcherUserId);
2402 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2403 .attemptToRestoreIfNeededAndSave();
2405 // Make sure the shortcut is actually visible to the launcher.
2406 final ShortcutInfo si = getShortcutInfoLocked(
2407 launcherUserId, callingPackage, packageName, shortcutId, userId);
2408 // "si == null" should suffice here, but check the flags too just to make sure.
2409 if (si == null || !si.isEnabled() || !si.isAlive()) {
2410 Log.e(TAG, "Shortcut " + shortcutId + " does not exist or disabled");
2413 return si.getIntents();
2418 public void addListener(@NonNull ShortcutChangeListener listener) {
2419 synchronized (mLock) {
2420 mListeners.add(Preconditions.checkNotNull(listener));
2425 public int getShortcutIconResId(int launcherUserId, @NonNull String callingPackage,
2426 @NonNull String packageName, @NonNull String shortcutId, int userId) {
2427 Preconditions.checkNotNull(callingPackage, "callingPackage");
2428 Preconditions.checkNotNull(packageName, "packageName");
2429 Preconditions.checkNotNull(shortcutId, "shortcutId");
2431 synchronized (mLock) {
2432 throwIfUserLockedL(userId);
2433 throwIfUserLockedL(launcherUserId);
2435 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2436 .attemptToRestoreIfNeededAndSave();
2438 final ShortcutPackage p = getUserShortcutsLocked(userId)
2439 .getPackageShortcutsIfExists(packageName);
2444 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
2445 return (shortcutInfo != null && shortcutInfo.hasIconResource())
2446 ? shortcutInfo.getIconResourceId() : 0;
2451 public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
2452 @NonNull String callingPackage, @NonNull String packageName,
2453 @NonNull String shortcutId, int userId) {
2454 Preconditions.checkNotNull(callingPackage, "callingPackage");
2455 Preconditions.checkNotNull(packageName, "packageName");
2456 Preconditions.checkNotNull(shortcutId, "shortcutId");
2458 synchronized (mLock) {
2459 throwIfUserLockedL(userId);
2460 throwIfUserLockedL(launcherUserId);
2462 getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
2463 .attemptToRestoreIfNeededAndSave();
2465 final ShortcutPackage p = getUserShortcutsLocked(userId)
2466 .getPackageShortcutsIfExists(packageName);
2471 final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
2472 if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
2476 if (shortcutInfo.getBitmapPath() == null) {
2477 Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
2480 return ParcelFileDescriptor.open(
2481 new File(shortcutInfo.getBitmapPath()),
2482 ParcelFileDescriptor.MODE_READ_ONLY);
2483 } catch (FileNotFoundException e) {
2484 Slog.e(TAG, "Icon file not found: " + shortcutInfo.getBitmapPath());
2491 public boolean hasShortcutHostPermission(int launcherUserId,
2492 @NonNull String callingPackage) {
2493 return ShortcutService.this.hasShortcutHostPermission(callingPackage, launcherUserId);
2497 final BroadcastReceiver mReceiver = new BroadcastReceiver() {
2499 public void onReceive(Context context, Intent intent) {
2500 if (!mBootCompleted.get()) {
2501 return; // Boot not completed, ignore the broadcast.
2504 if (Intent.ACTION_LOCALE_CHANGED.equals(intent.getAction())) {
2505 handleLocaleChanged();
2507 } catch (Exception e) {
2508 wtf("Exception in mReceiver.onReceive", e);
2513 void handleLocaleChanged() {
2515 Slog.d(TAG, "handleLocaleChanged");
2517 scheduleSaveBaseState();
2519 synchronized (mLock) {
2520 final long token = injectClearCallingIdentity();
2522 forEachLoadedUserLocked(user -> user.detectLocaleChange());
2524 injectRestoreCallingIdentity(token);
2530 * Package event callbacks.
2533 final BroadcastReceiver mPackageMonitor = new BroadcastReceiver() {
2535 public void onReceive(Context context, Intent intent) {
2536 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
2537 if (userId == UserHandle.USER_NULL) {
2538 Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
2542 final String action = intent.getAction();
2544 // This is normally called on Handler, so clearCallingIdentity() isn't needed,
2545 // but we still check it in unit tests.
2546 final long token = injectClearCallingIdentity();
2548 synchronized (mLock) {
2549 if (!isUserUnlockedL(userId)) {
2551 Slog.d(TAG, "Ignoring package broadcast " + action
2552 + " for locked/stopped user " + userId);
2557 // Whenever we get one of those package broadcasts, or get
2558 // ACTION_PREFERRED_ACTIVITY_CHANGED, we purge the default launcher cache.
2559 final ShortcutUser user = getUserShortcutsLocked(userId);
2560 user.clearLauncher();
2562 if (Intent.ACTION_PREFERRED_ACTIVITY_CHANGED.equals(action)) {
2563 // Nothing farther to do.
2567 final Uri intentUri = intent.getData();
2568 final String packageName = (intentUri != null) ? intentUri.getSchemeSpecificPart()
2570 if (packageName == null) {
2571 Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
2575 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2578 case Intent.ACTION_PACKAGE_ADDED:
2580 handlePackageUpdateFinished(packageName, userId);
2582 handlePackageAdded(packageName, userId);
2585 case Intent.ACTION_PACKAGE_REMOVED:
2587 handlePackageRemoved(packageName, userId);
2590 case Intent.ACTION_PACKAGE_CHANGED:
2591 handlePackageChanged(packageName, userId);
2594 case Intent.ACTION_PACKAGE_DATA_CLEARED:
2595 handlePackageDataCleared(packageName, userId);
2598 } catch (Exception e) {
2599 wtf("Exception in mPackageMonitor.onReceive", e);
2601 injectRestoreCallingIdentity(token);
2607 * Called when a user is unlocked.
2608 * - Check all known packages still exist, and otherwise perform cleanup.
2609 * - If a package still exists, check the version code. If it's been updated, may need to
2610 * update timestamps of its shortcuts.
2613 void checkPackageChanges(@UserIdInt int ownerUserId) {
2615 Slog.d(TAG, "checkPackageChanges() ownerUserId=" + ownerUserId);
2617 if (injectIsSafeModeEnabled()) {
2618 Slog.i(TAG, "Safe mode, skipping checkPackageChanges()");
2622 final long start = injectElapsedRealtime();
2624 final ArrayList<PackageWithUser> gonePackages = new ArrayList<>();
2626 synchronized (mLock) {
2627 final ShortcutUser user = getUserShortcutsLocked(ownerUserId);
2629 // Find packages that have been uninstalled.
2630 user.forAllPackageItems(spi -> {
2631 if (spi.getPackageInfo().isShadow()) {
2632 return; // Don't delete shadow information.
2634 if (!isPackageInstalled(spi.getPackageName(), spi.getPackageUserId())) {
2636 Slog.d(TAG, "Uninstalled: " + spi.getPackageName()
2637 + " user " + spi.getPackageUserId());
2639 gonePackages.add(PackageWithUser.of(spi));
2642 if (gonePackages.size() > 0) {
2643 for (int i = gonePackages.size() - 1; i >= 0; i--) {
2644 final PackageWithUser pu = gonePackages.get(i);
2645 cleanUpPackageLocked(pu.packageName, ownerUserId, pu.userId,
2646 /* appStillExists = */ false);
2650 rescanUpdatedPackagesLocked(ownerUserId, user.getLastAppScanTime(),
2651 /* forceRescan=*/ false);
2654 logDurationStat(Stats.CHECK_PACKAGE_CHANGES, start);
2659 private void rescanUpdatedPackagesLocked(@UserIdInt int userId, long lastScanTime,
2660 boolean forceRescan) {
2661 final ShortcutUser user = getUserShortcutsLocked(userId);
2663 // Note after each OTA, we'll need to rescan all system apps, as their lastUpdateTime
2665 final long now = injectCurrentTimeMillis();
2666 final boolean afterOta =
2667 !injectBuildFingerprint().equals(user.getLastAppScanOsFingerprint());
2669 // Then for each installed app, publish manifest shortcuts when needed.
2670 forUpdatedPackages(userId, lastScanTime, afterOta, ai -> {
2671 user.attemptToRestoreIfNeededAndSave(this, ai.packageName, userId);
2672 user.rescanPackageIfNeeded(ai.packageName, forceRescan);
2675 // Write the time just before the scan, because there may be apps that have just
2676 // been updated, and we want to catch them in the next time.
2677 user.setLastAppScanTime(now);
2678 user.setLastAppScanOsFingerprint(injectBuildFingerprint());
2679 scheduleSaveUser(userId);
2682 private void handlePackageAdded(String packageName, @UserIdInt int userId) {
2684 Slog.d(TAG, String.format("handlePackageAdded: %s user=%d", packageName, userId));
2686 synchronized (mLock) {
2687 final ShortcutUser user = getUserShortcutsLocked(userId);
2688 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
2689 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2694 private void handlePackageUpdateFinished(String packageName, @UserIdInt int userId) {
2696 Slog.d(TAG, String.format("handlePackageUpdateFinished: %s user=%d",
2697 packageName, userId));
2699 synchronized (mLock) {
2700 final ShortcutUser user = getUserShortcutsLocked(userId);
2701 user.attemptToRestoreIfNeededAndSave(this, packageName, userId);
2703 if (isPackageInstalled(packageName, userId)) {
2704 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2710 private void handlePackageRemoved(String packageName, @UserIdInt int packageUserId) {
2712 Slog.d(TAG, String.format("handlePackageRemoved: %s user=%d", packageName,
2715 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ false);
2720 private void handlePackageDataCleared(String packageName, int packageUserId) {
2722 Slog.d(TAG, String.format("handlePackageDataCleared: %s user=%d", packageName,
2725 cleanUpPackageForAllLoadedUsers(packageName, packageUserId, /* appStillExists = */ true);
2730 private void handlePackageChanged(String packageName, int packageUserId) {
2732 Slog.d(TAG, String.format("handlePackageChanged: %s user=%d", packageName,
2736 // Activities may be disabled or enabled. Just rescan the package.
2737 synchronized (mLock) {
2738 final ShortcutUser user = getUserShortcutsLocked(packageUserId);
2740 user.rescanPackageIfNeeded(packageName, /* forceRescan=*/ true);
2746 // === PackageManager interaction ===
2749 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2752 final PackageInfo getPackageInfoWithSignatures(String packageName, @UserIdInt int userId) {
2753 return getPackageInfo(packageName, userId, true);
2757 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2760 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId) {
2761 return getPackageInfo(packageName, userId, false);
2764 int injectGetPackageUid(@NonNull String packageName, @UserIdInt int userId) {
2765 final long token = injectClearCallingIdentity();
2767 return mIPackageManager.getPackageUid(packageName, PACKAGE_MATCH_FLAGS, userId);
2768 } catch (RemoteException e) {
2769 // Shouldn't happen.
2770 Slog.wtf(TAG, "RemoteException", e);
2773 injectRestoreCallingIdentity(token);
2778 * Returns {@link PackageInfo} unless it's uninstalled or disabled.
2782 final PackageInfo getPackageInfo(String packageName, @UserIdInt int userId,
2783 boolean getSignatures) {
2784 return isInstalledOrNull(injectPackageInfoWithUninstalled(
2785 packageName, userId, getSignatures));
2789 * Do not use directly; this returns uninstalled packages too.
2793 PackageInfo injectPackageInfoWithUninstalled(String packageName, @UserIdInt int userId,
2794 boolean getSignatures) {
2795 final long start = injectElapsedRealtime();
2796 final long token = injectClearCallingIdentity();
2798 return mIPackageManager.getPackageInfo(
2799 packageName, PACKAGE_MATCH_FLAGS
2800 | (getSignatures ? PackageManager.GET_SIGNATURES : 0), userId);
2801 } catch (RemoteException e) {
2802 // Shouldn't happen.
2803 Slog.wtf(TAG, "RemoteException", e);
2806 injectRestoreCallingIdentity(token);
2809 (getSignatures ? Stats.GET_PACKAGE_INFO_WITH_SIG : Stats.GET_PACKAGE_INFO),
2815 * Returns {@link ApplicationInfo} unless it's uninstalled or disabled.
2819 final ApplicationInfo getApplicationInfo(String packageName, @UserIdInt int userId) {
2820 return isInstalledOrNull(injectApplicationInfoWithUninstalled(packageName, userId));
2824 * Do not use directly; this returns uninstalled packages too.
2828 ApplicationInfo injectApplicationInfoWithUninstalled(
2829 String packageName, @UserIdInt int userId) {
2830 final long start = injectElapsedRealtime();
2831 final long token = injectClearCallingIdentity();
2833 return mIPackageManager.getApplicationInfo(packageName, PACKAGE_MATCH_FLAGS, userId);
2834 } catch (RemoteException e) {
2835 // Shouldn't happen.
2836 Slog.wtf(TAG, "RemoteException", e);
2839 injectRestoreCallingIdentity(token);
2841 logDurationStat(Stats.GET_APPLICATION_INFO, start);
2846 * Returns {@link ActivityInfo} with its metadata unless it's uninstalled or disabled.
2849 final ActivityInfo getActivityInfoWithMetadata(ComponentName activity, @UserIdInt int userId) {
2850 return isInstalledOrNull(injectGetActivityInfoWithMetadataWithUninstalled(
2855 * Do not use directly; this returns uninstalled packages too.
2859 ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled(
2860 ComponentName activity, @UserIdInt int userId) {
2861 final long start = injectElapsedRealtime();
2862 final long token = injectClearCallingIdentity();
2864 return mIPackageManager.getActivityInfo(activity,
2865 (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId);
2866 } catch (RemoteException e) {
2867 // Shouldn't happen.
2868 Slog.wtf(TAG, "RemoteException", e);
2871 injectRestoreCallingIdentity(token);
2873 logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start);
2878 * Return all installed and enabled packages.
2882 final List<PackageInfo> getInstalledPackages(@UserIdInt int userId) {
2883 final long start = injectElapsedRealtime();
2884 final long token = injectClearCallingIdentity();
2886 final List<PackageInfo> all = injectGetPackagesWithUninstalled(userId);
2888 all.removeIf(PACKAGE_NOT_INSTALLED);
2891 } catch (RemoteException e) {
2892 // Shouldn't happen.
2893 Slog.wtf(TAG, "RemoteException", e);
2896 injectRestoreCallingIdentity(token);
2898 logDurationStat(Stats.GET_INSTALLED_PACKAGES, start);
2903 * Do not use directly; this returns uninstalled packages too.
2907 List<PackageInfo> injectGetPackagesWithUninstalled(@UserIdInt int userId)
2908 throws RemoteException {
2909 final ParceledListSlice<PackageInfo> parceledList =
2910 mIPackageManager.getInstalledPackages(PACKAGE_MATCH_FLAGS, userId);
2911 if (parceledList == null) {
2912 return Collections.emptyList();
2914 return parceledList.getList();
2917 private void forUpdatedPackages(@UserIdInt int userId, long lastScanTime, boolean afterOta,
2918 Consumer<ApplicationInfo> callback) {
2920 Slog.d(TAG, "forUpdatedPackages for user " + userId + ", lastScanTime=" + lastScanTime);
2922 final List<PackageInfo> list = getInstalledPackages(userId);
2923 for (int i = list.size() - 1; i >= 0; i--) {
2924 final PackageInfo pi = list.get(i);
2926 // If the package has been updated since the last scan time, then scan it.
2927 // Also if it's a system app with no update, lastUpdateTime is not reliable, so
2929 if (pi.lastUpdateTime >= lastScanTime
2930 || (afterOta && isPureSystemApp(pi.applicationInfo))) {
2932 Slog.d(TAG, "Found updated package " + pi.packageName);
2934 callback.accept(pi.applicationInfo);
2940 * @return true if it's a system app with no updates.
2942 private boolean isPureSystemApp(ApplicationInfo ai) {
2943 return ai.isSystemApp() && !ai.isUpdatedSystemApp();
2946 private boolean isApplicationFlagSet(@NonNull String packageName, int userId, int flags) {
2947 final ApplicationInfo ai = injectApplicationInfoWithUninstalled(packageName, userId);
2948 return (ai != null) && ((ai.flags & flags) == flags);
2951 private static boolean isInstalled(@Nullable ApplicationInfo ai) {
2952 return (ai != null) && (ai.flags & ApplicationInfo.FLAG_INSTALLED) != 0;
2955 private static boolean isInstalled(@Nullable PackageInfo pi) {
2956 return (pi != null) && isInstalled(pi.applicationInfo);
2959 private static boolean isInstalled(@Nullable ActivityInfo ai) {
2960 return (ai != null) && isInstalled(ai.applicationInfo);
2963 private static ApplicationInfo isInstalledOrNull(ApplicationInfo ai) {
2964 return isInstalled(ai) ? ai : null;
2967 private static PackageInfo isInstalledOrNull(PackageInfo pi) {
2968 return isInstalled(pi) ? pi : null;
2971 private static ActivityInfo isInstalledOrNull(ActivityInfo ai) {
2972 return isInstalled(ai) ? ai : null;
2975 boolean isPackageInstalled(String packageName, int userId) {
2976 return getApplicationInfo(packageName, userId) != null;
2980 XmlResourceParser injectXmlMetaData(ActivityInfo activityInfo, String key) {
2981 return activityInfo.loadXmlMetaData(mContext.getPackageManager(), key);
2985 Resources injectGetResourcesForApplicationAsUser(String packageName, int userId) {
2986 final long start = injectElapsedRealtime();
2987 final long token = injectClearCallingIdentity();
2989 return mContext.getPackageManager().getResourcesForApplicationAsUser(
2990 packageName, userId);
2991 } catch (NameNotFoundException e) {
2992 Slog.e(TAG, "Resources for package " + packageName + " not found");
2995 injectRestoreCallingIdentity(token);
2997 logDurationStat(Stats.GET_APPLICATION_RESOURCES, start);
3001 private Intent getMainActivityIntent() {
3002 final Intent intent = new Intent(Intent.ACTION_MAIN);
3003 intent.addCategory(LAUNCHER_INTENT_CATEGORY);
3008 * Same as queryIntentActivitiesAsUser, except it makes sure the package is installed,
3009 * and only returns exported activities.
3013 List<ResolveInfo> queryActivities(@NonNull Intent baseIntent,
3014 @NonNull String packageName, @Nullable ComponentName activity, int userId) {
3016 baseIntent.setPackage(Preconditions.checkNotNull(packageName));
3017 if (activity != null) {
3018 baseIntent.setComponent(activity);
3021 final List<ResolveInfo> resolved =
3022 mContext.getPackageManager().queryIntentActivitiesAsUser(
3023 baseIntent, PACKAGE_MATCH_FLAGS, userId);
3024 if (resolved == null || resolved.size() == 0) {
3025 return EMPTY_RESOLVE_INFO;
3027 // Make sure the package is installed.
3028 if (!isInstalled(resolved.get(0).activityInfo)) {
3029 return EMPTY_RESOLVE_INFO;
3031 resolved.removeIf(ACTIVITY_NOT_EXPORTED);
3036 * Return the main activity that is enabled and exported. If multiple activities are found,
3037 * return the first one.
3040 ComponentName injectGetDefaultMainActivity(@NonNull String packageName, int userId) {
3041 final long start = injectElapsedRealtime();
3042 final long token = injectClearCallingIdentity();
3044 final List<ResolveInfo> resolved =
3045 queryActivities(getMainActivityIntent(), packageName, null, userId);
3046 return resolved.size() == 0 ? null : resolved.get(0).activityInfo.getComponentName();
3048 injectRestoreCallingIdentity(token);
3050 logDurationStat(Stats.GET_LAUNCHER_ACTIVITY, start);
3055 * Return whether an activity is enabled, exported and main.
3057 boolean injectIsMainActivity(@NonNull ComponentName activity, int userId) {
3058 final long start = injectElapsedRealtime();
3059 final long token = injectClearCallingIdentity();
3061 final List<ResolveInfo> resolved =
3062 queryActivities(getMainActivityIntent(), activity.getPackageName(),
3064 return resolved.size() > 0;
3066 injectRestoreCallingIdentity(token);
3068 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3073 * Return all the enabled, exported and main activities from a package.
3076 List<ResolveInfo> injectGetMainActivities(@NonNull String packageName, int userId) {
3077 final long start = injectElapsedRealtime();
3078 final long token = injectClearCallingIdentity();
3080 return queryActivities(getMainActivityIntent(), packageName, null, userId);
3082 injectRestoreCallingIdentity(token);
3084 logDurationStat(Stats.CHECK_LAUNCHER_ACTIVITY, start);
3089 * Return whether an activity is enabled and exported.
3092 boolean injectIsActivityEnabledAndExported(
3093 @NonNull ComponentName activity, @UserIdInt int userId) {
3094 final long start = injectElapsedRealtime();
3095 final long token = injectClearCallingIdentity();
3097 return queryActivities(new Intent(), activity.getPackageName(), activity, userId)
3100 injectRestoreCallingIdentity(token);
3102 logDurationStat(Stats.IS_ACTIVITY_ENABLED, start);
3106 boolean injectIsSafeModeEnabled() {
3107 final long token = injectClearCallingIdentity();
3109 return IWindowManager.Stub
3110 .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE))
3111 .isSafeModeEnabled();
3112 } catch (RemoteException e) {
3113 return false; // Shouldn't happen though.
3115 injectRestoreCallingIdentity(token);
3119 // === Backup & restore ===
3121 boolean shouldBackupApp(String packageName, int userId) {
3122 return isApplicationFlagSet(packageName, userId, ApplicationInfo.FLAG_ALLOW_BACKUP);
3125 boolean shouldBackupApp(PackageInfo pi) {
3126 return (pi.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0;
3130 public byte[] getBackupPayload(@UserIdInt int userId) {
3133 Slog.d(TAG, "Backing up user " + userId);
3135 synchronized (mLock) {
3136 if (!isUserUnlockedL(userId)) {
3137 wtf("Can't backup: user " + userId + " is locked or not running");
3141 final ShortcutUser user = getUserShortcutsLocked(userId);
3143 wtf("Can't backup: user not found: id=" + userId);
3147 user.forAllPackageItems(spi -> spi.refreshPackageInfoAndSave());
3150 final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
3152 saveUserInternalLocked(userId, os, /* forBackup */ true);
3153 } catch (XmlPullParserException | IOException e) {
3154 // Shouldn't happen.
3155 Slog.w(TAG, "Backup failed.", e);
3158 return os.toByteArray();
3163 public void applyRestore(byte[] payload, @UserIdInt int userId) {
3166 Slog.d(TAG, "Restoring user " + userId);
3168 synchronized (mLock) {
3169 if (!isUserUnlockedL(userId)) {
3170 wtf("Can't restore: user " + userId + " is locked or not running");
3173 final ShortcutUser user;
3174 final ByteArrayInputStream is = new ByteArrayInputStream(payload);
3176 user = loadUserInternal(userId, is, /* fromBackup */ true);
3177 } catch (XmlPullParserException | IOException e) {
3178 Slog.w(TAG, "Restoration failed.", e);
3181 mUsers.put(userId, user);
3183 // Rescan all packages to re-publish manifest shortcuts and do other checks.
3184 rescanUpdatedPackagesLocked(userId,
3185 0, // lastScanTime = 0; rescan all packages.
3186 /* forceRescan= */ true);
3188 saveUserLocked(userId);
3195 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3196 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
3197 "can't dump by this caller");
3198 boolean checkin = false;
3199 boolean clear = false;
3201 for (String arg : args) {
3202 if ("-c".equals(arg)) {
3204 } else if ("--checkin".equals(arg)) {
3212 dumpCheckin(pw, clear);
3218 private void dumpInner(PrintWriter pw) {
3219 synchronized (mLock) {
3220 final long now = injectCurrentTimeMillis();
3224 pw.print(formatTime(now));
3226 pw.print(" Raw last reset: [");
3227 pw.print(mRawLastResetTime);
3229 pw.print(formatTime(mRawLastResetTime));
3231 final long last = getLastResetTimeLocked();
3232 pw.print(" Last reset: [");
3235 pw.print(formatTime(last));
3237 final long next = getNextResetTimeLocked();
3238 pw.print(" Next reset: [");
3241 pw.print(formatTime(next));
3243 pw.print(" Config:");
3244 pw.print(" Max icon dim: ");
3245 pw.println(mMaxIconDimension);
3246 pw.print(" Icon format: ");
3247 pw.println(mIconPersistFormat);
3248 pw.print(" Icon quality: ");
3249 pw.println(mIconPersistQuality);
3250 pw.print(" saveDelayMillis: ");
3251 pw.println(mSaveDelayMillis);
3252 pw.print(" resetInterval: ");
3253 pw.println(mResetInterval);
3254 pw.print(" maxUpdatesPerInterval: ");
3255 pw.println(mMaxUpdatesPerInterval);
3256 pw.print(" maxShortcutsPerActivity: ");
3257 pw.println(mMaxShortcuts);
3260 pw.println(" Stats:");
3261 synchronized (mStatLock) {
3262 for (int i = 0; i < Stats.COUNT; i++) {
3263 dumpStatLS(pw, " ", i);
3268 pw.print(" #Failures: ");
3269 pw.println(mWtfCount);
3271 if (mLastWtfStacktrace != null) {
3272 pw.print(" Last failure stack trace: ");
3273 pw.println(Log.getStackTraceString(mLastWtfStacktrace));
3276 for (int i = 0; i < mUsers.size(); i++) {
3278 mUsers.valueAt(i).dump(pw, " ");
3282 pw.println(" UID state:");
3284 for (int i = 0; i < mUidState.size(); i++) {
3285 final int uid = mUidState.keyAt(i);
3286 final int state = mUidState.valueAt(i);
3289 pw.print(" state=");
3291 if (isProcessStateForeground(state)) {
3294 pw.print(" last FG=");
3295 pw.print(mUidLastForegroundElapsedTime.get(uid));
3301 static String formatTime(long time) {
3302 Time tobj = new Time();
3304 return tobj.format("%Y-%m-%d %H:%M:%S");
3307 private void dumpStatLS(PrintWriter pw, String prefix, int statId) {
3309 final int count = mCountStats[statId];
3310 final long dur = mDurationStats[statId];
3311 pw.println(String.format("%s: count=%d, total=%dms, avg=%.1fms",
3312 STAT_LABELS[statId], count, dur,
3313 (count == 0 ? 0 : ((double) dur) / count)));
3317 * Dumpsys for checkin.
3319 * @param clear if true, clear the history information. Some other system services have this
3320 * behavior but shortcut service doesn't for now.
3322 private void dumpCheckin(PrintWriter pw, boolean clear) {
3323 synchronized (mLock) {
3325 final JSONArray users = new JSONArray();
3327 for (int i = 0; i < mUsers.size(); i++) {
3328 users.put(mUsers.valueAt(i).dumpCheckin(clear));
3331 final JSONObject result = new JSONObject();
3333 result.put(KEY_SHORTCUT, users);
3334 result.put(KEY_LOW_RAM, injectIsLowRamDevice());
3335 result.put(KEY_ICON_SIZE, mMaxIconDimension);
3337 pw.println(result.toString(1));
3338 } catch (JSONException e) {
3339 Slog.e(TAG, "Unable to write in json", e);
3344 // === Shell support ===
3347 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
3348 String[] args, ResultReceiver resultReceiver) throws RemoteException {
3352 final long token = injectClearCallingIdentity();
3354 final int status = (new MyShellCommand()).exec(this, in, out, err, args, resultReceiver);
3355 resultReceiver.send(status, null);
3357 injectRestoreCallingIdentity(token);
3361 static class CommandException extends Exception {
3362 public CommandException(String message) {
3368 * Handle "adb shell cmd".
3370 private class MyShellCommand extends ShellCommand {
3372 private int mUserId = UserHandle.USER_SYSTEM;
3374 private void parseOptionsLocked(boolean takeUser)
3375 throws CommandException {
3377 while ((opt = getNextOption()) != null) {
3381 mUserId = UserHandle.parseUserArg(getNextArgRequired());
3382 if (!isUserUnlockedL(mUserId)) {
3383 throw new CommandException(
3384 "User " + mUserId + " is not running or locked");
3390 throw new CommandException("Unknown option: " + opt);
3396 public int onCommand(String cmd) {
3398 return handleDefaultCommands(cmd);
3400 final PrintWriter pw = getOutPrintWriter();
3403 case "reset-throttling":
3404 handleResetThrottling();
3406 case "reset-all-throttling":
3407 handleResetAllThrottling();
3409 case "override-config":
3410 handleOverrideConfig();
3412 case "reset-config":
3413 handleResetConfig();
3415 case "clear-default-launcher":
3416 handleClearDefaultLauncher();
3418 case "get-default-launcher":
3419 handleGetDefaultLauncher();
3424 case "clear-shortcuts":
3425 handleClearShortcuts();
3427 case "verify-states": // hidden command to verify various internal states.
3428 handleVerifyStates();
3431 return handleDefaultCommands(cmd);
3433 } catch (CommandException e) {
3434 pw.println("Error: " + e.getMessage());
3437 pw.println("Success");
3442 public void onHelp() {
3443 final PrintWriter pw = getOutPrintWriter();
3444 pw.println("Usage: cmd shortcut COMMAND [options ...]");
3446 pw.println("cmd shortcut reset-throttling [--user USER_ID]");
3447 pw.println(" Reset throttling for all packages and users");
3449 pw.println("cmd shortcut reset-all-throttling");
3450 pw.println(" Reset the throttling state for all users");
3452 pw.println("cmd shortcut override-config CONFIG");
3453 pw.println(" Override the configuration for testing (will last until reboot)");
3455 pw.println("cmd shortcut reset-config");
3456 pw.println(" Reset the configuration set with \"update-config\"");
3458 pw.println("cmd shortcut clear-default-launcher [--user USER_ID]");
3459 pw.println(" Clear the cached default launcher");
3461 pw.println("cmd shortcut get-default-launcher [--user USER_ID]");
3462 pw.println(" Show the default launcher");
3464 pw.println("cmd shortcut unload-user [--user USER_ID]");
3465 pw.println(" Unload a user from the memory");
3466 pw.println(" (This should not affect any observable behavior)");
3468 pw.println("cmd shortcut clear-shortcuts [--user USER_ID] PACKAGE");
3469 pw.println(" Remove all shortcuts from a package, including pinned shortcuts");
3473 private void handleResetThrottling() throws CommandException {
3474 synchronized (mLock) {
3475 parseOptionsLocked(/* takeUser =*/ true);
3477 Slog.i(TAG, "cmd: handleResetThrottling: user=" + mUserId);
3479 resetThrottlingInner(mUserId);
3483 private void handleResetAllThrottling() {
3484 Slog.i(TAG, "cmd: handleResetAllThrottling");
3486 resetAllThrottlingInner();
3489 private void handleOverrideConfig() throws CommandException {
3490 final String config = getNextArgRequired();
3492 Slog.i(TAG, "cmd: handleOverrideConfig: " + config);
3494 synchronized (mLock) {
3495 if (!updateConfigurationLocked(config)) {
3496 throw new CommandException("override-config failed. See logcat for details.");
3501 private void handleResetConfig() {
3502 Slog.i(TAG, "cmd: handleResetConfig");
3504 synchronized (mLock) {
3505 loadConfigurationLocked();
3509 private void clearLauncher() {
3510 synchronized (mLock) {
3511 getUserShortcutsLocked(mUserId).forceClearLauncher();
3515 private void showLauncher() {
3516 synchronized (mLock) {
3517 // This ensures to set the cached launcher. Package name doesn't matter.
3518 hasShortcutHostPermissionInner("-", mUserId);
3520 getOutPrintWriter().println("Launcher: "
3521 + getUserShortcutsLocked(mUserId).getLastKnownLauncher());
3525 private void handleClearDefaultLauncher() throws CommandException {
3526 synchronized (mLock) {
3527 parseOptionsLocked(/* takeUser =*/ true);
3533 private void handleGetDefaultLauncher() throws CommandException {
3534 synchronized (mLock) {
3535 parseOptionsLocked(/* takeUser =*/ true);
3542 private void handleUnloadUser() throws CommandException {
3543 synchronized (mLock) {
3544 parseOptionsLocked(/* takeUser =*/ true);
3546 Slog.i(TAG, "cmd: handleUnloadUser: user=" + mUserId);
3548 ShortcutService.this.handleCleanupUser(mUserId);
3552 private void handleClearShortcuts() throws CommandException {
3553 synchronized (mLock) {
3554 parseOptionsLocked(/* takeUser =*/ true);
3555 final String packageName = getNextArgRequired();
3557 Slog.i(TAG, "cmd: handleClearShortcuts: user" + mUserId + ", " + packageName);
3559 ShortcutService.this.cleanUpPackageForAllLoadedUsers(packageName, mUserId,
3560 /* appStillExists = */ true);
3564 private void handleVerifyStates() throws CommandException {
3566 verifyStatesForce(); // This will throw when there's an issue.
3567 } catch (Throwable th) {
3568 throw new CommandException(th.getMessage() + "\n" + Log.getStackTraceString(th));
3573 // === Unit test support ===
3577 long injectCurrentTimeMillis() {
3578 return System.currentTimeMillis();
3582 long injectElapsedRealtime() {
3583 return SystemClock.elapsedRealtime();
3588 int injectBinderCallingUid() {
3589 return getCallingUid();
3592 private int getCallingUserId() {
3593 return UserHandle.getUserId(injectBinderCallingUid());
3598 long injectClearCallingIdentity() {
3599 return Binder.clearCallingIdentity();
3604 void injectRestoreCallingIdentity(long token) {
3605 Binder.restoreCallingIdentity(token);
3610 String injectBuildFingerprint() {
3611 return Build.FINGERPRINT;
3614 final void wtf(String message) {
3615 wtf(message, /* exception= */ null);
3619 void wtf(String message, Throwable e) {
3621 e = new RuntimeException("Stacktrace");
3623 synchronized (mLock) {
3625 mLastWtfStacktrace = new Exception("Last failure was logged here:");
3627 Slog.wtf(TAG, message, e);
3631 File injectSystemDataPath() {
3632 return Environment.getDataSystemDirectory();
3636 File injectUserDataPath(@UserIdInt int userId) {
3637 return new File(Environment.getDataSystemCeDirectory(userId), DIRECTORY_PER_USER);
3641 boolean injectIsLowRamDevice() {
3642 return ActivityManager.isLowRamDeviceStatic();
3646 void injectRegisterUidObserver(IUidObserver observer, int which) {
3648 ActivityManagerNative.getDefault().registerUidObserver(observer, which);
3649 } catch (RemoteException shouldntHappen) {
3653 File getUserBitmapFilePath(@UserIdInt int userId) {
3654 return new File(injectUserDataPath(userId), DIRECTORY_BITMAPS);
3658 SparseArray<ShortcutUser> getShortcutsForTest() {
3663 int getMaxShortcutsForTest() {
3664 return mMaxShortcuts;
3668 int getMaxUpdatesPerIntervalForTest() {
3669 return mMaxUpdatesPerInterval;
3673 long getResetIntervalForTest() {
3674 return mResetInterval;
3678 int getMaxIconDimensionForTest() {
3679 return mMaxIconDimension;
3683 CompressFormat getIconPersistFormatForTest() {
3684 return mIconPersistFormat;
3688 int getIconPersistQualityForTest() {
3689 return mIconPersistQuality;
3693 ShortcutPackage getPackageShortcutForTest(String packageName, int userId) {
3694 synchronized (mLock) {
3695 final ShortcutUser user = mUsers.get(userId);
3696 if (user == null) return null;
3698 return user.getAllPackagesForTest().get(packageName);
3703 ShortcutInfo getPackageShortcutForTest(String packageName, String shortcutId, int userId) {
3704 synchronized (mLock) {
3705 final ShortcutPackage pkg = getPackageShortcutForTest(packageName, userId);
3706 if (pkg == null) return null;
3708 return pkg.findShortcutById(shortcutId);
3713 * Control whether {@link #verifyStates} should be performed. We always perform it during unit
3717 boolean injectShouldPerformVerification() {
3722 * Check various internal states and throws if there's any inconsistency.
3723 * This is normally only enabled during unit tests.
3725 final void verifyStates() {
3726 if (injectShouldPerformVerification()) {
3727 verifyStatesInner();
3731 private final void verifyStatesForce() {
3732 verifyStatesInner();
3735 private void verifyStatesInner() {
3736 synchronized (mLock) {
3737 forEachLoadedUserLocked(u -> u.forAllPackageItems(ShortcutPackageItem::verifyStates));