Debian Codegraph @

core/java/android/content/pm/ShortcutInfo.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package android.content.pm;
17
18 import android.annotation.IntDef;
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.annotation.SystemApi;
22 import android.annotation.TestApi;
23 import android.annotation.UserIdInt;
24 import android.app.Notification;
25 import android.app.Person;
26 import android.app.TaskStackBuilder;
27 import android.app.appsearch.GenericDocument;
28 import android.compat.annotation.UnsupportedAppUsage;
29 import android.content.ComponentName;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.LocusId;
33 import android.content.pm.LauncherApps.ShortcutQuery;
34 import android.content.res.Resources;
35 import android.content.res.Resources.NotFoundException;
36 import android.graphics.Bitmap;
37 import android.graphics.drawable.Icon;
38 import android.os.Build;
39 import android.os.Bundle;
40 import android.os.Parcel;
41 import android.os.Parcelable;
42 import android.os.PersistableBundle;
43 import android.os.UserHandle;
44 import android.text.TextUtils;
45 import android.util.ArrayMap;
46 import android.util.ArraySet;
47 import android.util.Log;
48 import android.view.contentcapture.ContentCaptureContext;
49
50 import com.android.internal.annotations.VisibleForTesting;
51 import com.android.internal.util.Preconditions;
52
53 import java.lang.IllegalArgumentException;
54 import java.lang.annotation.Retention;
55 import java.lang.annotation.RetentionPolicy;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58 import java.util.Collections;
59 import java.util.HashMap;
60 import java.util.List;
61 import java.util.Map;
62 import java.util.Objects;
63 import java.util.Set;
64 import java.util.stream.Collectors;
65
66 /**
67 * Represents a shortcut that can be published via {@link ShortcutManager}.
68 *
69 * @see ShortcutManager
70 */
71 public final class ShortcutInfo implements Parcelable {
72 static final String TAG = "Shortcut";
73
74 private static final String RES_TYPE_STRING = "string";
75
76 private static final String ANDROID_PACKAGE_NAME = "android";
77
78 private static final int IMPLICIT_RANK_MASK = 0x7fffffff;
79
80 /** @hide */
81 public static final int RANK_CHANGED_BIT = ~IMPLICIT_RANK_MASK;
82
83 /** @hide */
84 public static final int RANK_NOT_SET = Integer.MAX_VALUE;
85
86 /** @hide */
87 public static final int FLAG_DYNAMIC = 1 << 0;
88
89 /** @hide */
90 public static final int FLAG_PINNED = 1 << 1;
91
92 /** @hide */
93 public static final int FLAG_HAS_ICON_RES = 1 << 2;
94
95 /** @hide */
96 public static final int FLAG_HAS_ICON_FILE = 1 << 3;
97
98 /** @hide */
99 public static final int FLAG_KEY_FIELDS_ONLY = 1 << 4;
100
101 /** @hide */
102 public static final int FLAG_MANIFEST = 1 << 5;
103
104 /** @hide */
105 public static final int FLAG_DISABLED = 1 << 6;
106
107 /** @hide */
108 public static final int FLAG_STRINGS_RESOLVED = 1 << 7;
109
110 /** @hide */
111 public static final int FLAG_IMMUTABLE = 1 << 8;
112
113 /** @hide */
114 public static final int FLAG_ADAPTIVE_BITMAP = 1 << 9;
115
116 /** @hide */
117 public static final int FLAG_RETURNED_BY_SERVICE = 1 << 10;
118
119 /** @hide When this is set, the bitmap icon is waiting to be saved. */
120 public static final int FLAG_ICON_FILE_PENDING_SAVE = 1 << 11;
121
122 /**
123 * "Shadow" shortcuts are the ones that are restored, but the owner package hasn't been
124 * installed yet.
125 * @hide
126 */
127 public static final int FLAG_SHADOW = 1 << 12;
128
129 /** @hide */
130 public static final int FLAG_LONG_LIVED = 1 << 13;
131
132 /**
133 * TODO(b/155135057): This is a quick and temporary fix for b/155135890. ShortcutService doesn't
134 * need to be aware of the outside world. Replace this with a more extensible solution.
135 * @hide
136 */
137 public static final int FLAG_CACHED_NOTIFICATIONS = 1 << 14;
138
139 /** @hide */
140 public static final int FLAG_HAS_ICON_URI = 1 << 15;
141
142 /**
143 * TODO(b/155135057): This is a quick and temporary fix for b/155135890. ShortcutService doesn't
144 * need to be aware of the outside world. Replace this with a more extensible solution.
145 * @hide
146 */
147 public static final int FLAG_CACHED_PEOPLE_TILE = 1 << 29;
148
149 /**
150 * TODO(b/155135057): This is a quick and temporary fix for b/155135890. ShortcutService doesn't
151 * need to be aware of the outside world. Replace this with a more extensible solution.
152 * @hide
153 */
154 public static final int FLAG_CACHED_BUBBLES = 1 << 30;
155
156 /** @hide */
157 public static final int FLAG_CACHED_ALL =
158 FLAG_CACHED_NOTIFICATIONS | FLAG_CACHED_BUBBLES | FLAG_CACHED_PEOPLE_TILE;
159
160 /**
161 * Bitmask-based flags indicating different states associated with the shortcut. Note that if
162 * new value is added here, consider adding also the corresponding string representation and
163 * queries in {@link AppSearchShortcutInfo}.
164 *
165 * @hide
166 */
167 @IntDef(flag = true, prefix = { "FLAG_" }, value = {
168 FLAG_DYNAMIC,
169 FLAG_PINNED,
170 FLAG_HAS_ICON_RES,
171 FLAG_HAS_ICON_FILE,
172 FLAG_KEY_FIELDS_ONLY,
173 FLAG_MANIFEST,
174 FLAG_DISABLED,
175 FLAG_STRINGS_RESOLVED,
176 FLAG_IMMUTABLE,
177 FLAG_ADAPTIVE_BITMAP,
178 FLAG_RETURNED_BY_SERVICE,
179 FLAG_ICON_FILE_PENDING_SAVE,
180 FLAG_SHADOW,
181 FLAG_LONG_LIVED,
182 FLAG_HAS_ICON_URI,
183 FLAG_CACHED_NOTIFICATIONS,
184 FLAG_CACHED_BUBBLES,
185 FLAG_CACHED_PEOPLE_TILE
186 })
187 @Retention(RetentionPolicy.SOURCE)
188 public @interface ShortcutFlags {}
189
190 // Cloning options.
191
192 /** @hide */
193 private static final int CLONE_REMOVE_ICON = 1 << 0;
194
195 /** @hide */
196 private static final int CLONE_REMOVE_INTENT = 1 << 1;
197
198 /** @hide */
199 public static final int CLONE_REMOVE_NON_KEY_INFO = 1 << 2;
200
201 /** @hide */
202 public static final int CLONE_REMOVE_RES_NAMES = 1 << 3;
203
204 /** @hide */
205 public static final int CLONE_REMOVE_PERSON = 1 << 4;
206
207 /** @hide */
208 public static final int CLONE_REMOVE_FOR_CREATOR = CLONE_REMOVE_ICON | CLONE_REMOVE_RES_NAMES;
209
210 /** @hide */
211 public static final int CLONE_REMOVE_FOR_LAUNCHER = CLONE_REMOVE_ICON | CLONE_REMOVE_INTENT
212 | CLONE_REMOVE_RES_NAMES | CLONE_REMOVE_PERSON;
213
214 /** @hide */
215 public static final int CLONE_REMOVE_FOR_LAUNCHER_APPROVAL = CLONE_REMOVE_INTENT
216 | CLONE_REMOVE_RES_NAMES | CLONE_REMOVE_PERSON;
217
218 /** @hide */
219 public static final int CLONE_REMOVE_FOR_APP_PREDICTION = CLONE_REMOVE_ICON
220 | CLONE_REMOVE_RES_NAMES;
221
222 /** @hide */
223 @IntDef(flag = true, prefix = { "CLONE_" }, value = {
224 CLONE_REMOVE_ICON,
225 CLONE_REMOVE_INTENT,
226 CLONE_REMOVE_NON_KEY_INFO,
227 CLONE_REMOVE_RES_NAMES,
228 CLONE_REMOVE_PERSON,
229 CLONE_REMOVE_FOR_CREATOR,
230 CLONE_REMOVE_FOR_LAUNCHER,
231 CLONE_REMOVE_FOR_LAUNCHER_APPROVAL,
232 CLONE_REMOVE_FOR_APP_PREDICTION
233 })
234 @Retention(RetentionPolicy.SOURCE)
235 public @interface CloneFlags {}
236
237 /**
238 * Shortcut is not disabled.
239 */
240 public static final int DISABLED_REASON_NOT_DISABLED = 0;
241
242 /**
243 * Shortcut has been disabled by the publisher app with the
244 * {@link ShortcutManager#disableShortcuts(List)} API.
245 */
246 public static final int DISABLED_REASON_BY_APP = 1;
247
248 /**
249 * Shortcut has been disabled due to changes to the publisher app. (e.g. a manifest shortcut
250 * no longer exists.)
251 */
252 public static final int DISABLED_REASON_APP_CHANGED = 2;
253
254 /**
255 * Shortcut is disabled for an unknown reason.
256 */
257 public static final int DISABLED_REASON_UNKNOWN = 3;
258
259 /**
260 * A disabled reason that's equal to or bigger than this is due to backup and restore issue.
261 * A shortcut with such a reason wil be visible to the launcher, but not to the publisher.
262 * ({@link #isVisibleToPublisher()} will be false.)
263 */
264 private static final int DISABLED_REASON_RESTORE_ISSUE_START = 100;
265
266 /**
267 * Shortcut has been restored from the previous device, but the publisher app on the current
268 * device is of a lower version. The shortcut will not be usable until the app is upgraded to
269 * the same version or higher.
270 */
271 public static final int DISABLED_REASON_VERSION_LOWER = 100;
272
273 /**
274 * Shortcut has not been restored because the publisher app does not support backup and restore.
275 */
276 public static final int DISABLED_REASON_BACKUP_NOT_SUPPORTED = 101;
277
278 /**
279 * Shortcut has not been restored because the publisher app's signature has changed.
280 */
281 public static final int DISABLED_REASON_SIGNATURE_MISMATCH = 102;
282
283 /**
284 * Shortcut has not been restored for unknown reason.
285 */
286 public static final int DISABLED_REASON_OTHER_RESTORE_ISSUE = 103;
287
288 /** @hide */
289 @IntDef(prefix = { "DISABLED_REASON_" }, value = {
290 DISABLED_REASON_NOT_DISABLED,
291 DISABLED_REASON_BY_APP,
292 DISABLED_REASON_APP_CHANGED,
293 DISABLED_REASON_UNKNOWN,
294 DISABLED_REASON_VERSION_LOWER,
295 DISABLED_REASON_BACKUP_NOT_SUPPORTED,
296 DISABLED_REASON_SIGNATURE_MISMATCH,
297 DISABLED_REASON_OTHER_RESTORE_ISSUE,
298 })
299 @Retention(RetentionPolicy.SOURCE)
300 public @interface DisabledReason{}
301
302 /**
303 * Return a label for disabled reasons, which are *not* supposed to be shown to the user.
304 * @hide
305 */
306 public static String getDisabledReasonDebugString(@DisabledReason int disabledReason) {
307 switch (disabledReason) {
308 case DISABLED_REASON_NOT_DISABLED:
309 return "[Not disabled]";
310 case DISABLED_REASON_BY_APP:
311 return "[Disabled: by app]";
312 case DISABLED_REASON_APP_CHANGED:
313 return "[Disabled: app changed]";
314 case DISABLED_REASON_VERSION_LOWER:
315 return "[Disabled: lower version]";
316 case DISABLED_REASON_BACKUP_NOT_SUPPORTED:
317 return "[Disabled: backup not supported]";
318 case DISABLED_REASON_SIGNATURE_MISMATCH:
319 return "[Disabled: signature mismatch]";
320 case DISABLED_REASON_OTHER_RESTORE_ISSUE:
321 return "[Disabled: unknown restore issue]";
322 }
323 return "[Disabled: unknown reason:" + disabledReason + "]";
324 }
325
326 /**
327 * Return a label for a disabled reason for shortcuts that are disabled due to a backup and
328 * restore issue. If the reason is not due to backup & restore, then it'll return null.
329 *
330 * This method returns localized, user-facing strings, which will be returned by
331 * {@link #getDisabledMessage()}.
332 *
333 * @hide
334 */
335 public static String getDisabledReasonForRestoreIssue(Context context,
336 @DisabledReason int disabledReason) {
337 final Resources res = context.getResources();
338
339 switch (disabledReason) {
340 case DISABLED_REASON_VERSION_LOWER:
341 return res.getString(
342 com.android.internal.R.string.shortcut_restored_on_lower_version);
343 case DISABLED_REASON_BACKUP_NOT_SUPPORTED:
344 return res.getString(
345 com.android.internal.R.string.shortcut_restore_not_supported);
346 case DISABLED_REASON_SIGNATURE_MISMATCH:
347 return res.getString(
348 com.android.internal.R.string.shortcut_restore_signature_mismatch);
349 case DISABLED_REASON_OTHER_RESTORE_ISSUE:
350 return res.getString(
351 com.android.internal.R.string.shortcut_restore_unknown_issue);
352 case DISABLED_REASON_UNKNOWN:
353 return res.getString(
354 com.android.internal.R.string.shortcut_disabled_reason_unknown);
355 }
356 return null;
357 }
358
359 /** @hide */
360 public static boolean isDisabledForRestoreIssue(@DisabledReason int disabledReason) {
361 return disabledReason >= DISABLED_REASON_RESTORE_ISSUE_START;
362 }
363
364 /** @hide */
365 @IntDef(flag = true, value = {SURFACE_LAUNCHER})
366 @Retention(RetentionPolicy.SOURCE)
367 public @interface Surface {}
368
369 /**
370 * Indicates system surfaces managed by a launcher app. e.g. Long-Press Menu.
371 */
372 public static final int SURFACE_LAUNCHER = 1 << 0;
373
374 /**
375 * Shortcut category for messaging related actions, such as chat.
376 */
377 public static final String SHORTCUT_CATEGORY_CONVERSATION = "android.shortcut.conversation";
378
379 private final String mId;
380
381 @NonNull
382 private final String mPackageName;
383
384 @Nullable
385 private ComponentName mActivity;
386
387 @Nullable
388 private Icon mIcon;
389
390 private int mTitleResId;
391
392 private String mTitleResName;
393
394 @Nullable
395 private CharSequence mTitle;
396
397 private int mTextResId;
398
399 private String mTextResName;
400
401 @Nullable
402 private CharSequence mText;
403
404 private int mDisabledMessageResId;
405
406 private String mDisabledMessageResName;
407
408 @Nullable
409 private CharSequence mDisabledMessage;
410
411 @Nullable
412 private ArraySet<String> mCategories;
413
414 /**
415 * Intents *with extras removed*.
416 */
417 @Nullable
418 private Intent[] mIntents;
419
420 /**
421 * Extras for the intents.
422 */
423 @Nullable
424 private PersistableBundle[] mIntentPersistableExtrases;
425
426 @Nullable
427 private Person[] mPersons;
428
429 @Nullable
430 private LocusId mLocusId;
431
432 private int mRank;
433
434 /**
435 * Internally used for auto-rank-adjustment.
436 *
437 * RANK_CHANGED_BIT is used to denote that the rank of a shortcut is changing.
438 * The rest of the bits are used to denote the order in which shortcuts are passed to
439 * APIs, which is used to preserve the argument order when ranks are tie.
440 */
441 private int mImplicitRank;
442
443 @Nullable
444 private PersistableBundle mExtras;
445
446 private long mLastChangedTimestamp;
447
448 // Internal use only.
449 @ShortcutFlags
450 private int mFlags;
451
452 // Internal use only.
453 private int mIconResId;
454
455 private String mIconResName;
456
457 // Internal use only.
458 private String mIconUri;
459
460 // Internal use only.
461 @Nullable
462 private String mBitmapPath;
463
464 private final int mUserId;
465
466 /** @hide */
467 public static final int VERSION_CODE_UNKNOWN = -1;
468
469 private int mDisabledReason;
470
471 @Nullable private String mStartingThemeResName;
472
473 private int mExcludedSurfaces;
474
475 @Nullable
476 private Map<String, Map<String, List<String>>> mCapabilityBindings;
477
478 private ShortcutInfo(Builder b) {
479 mUserId = b.mContext.getUserId();
480
481 mId = Preconditions.checkStringNotEmpty(b.mId, "Shortcut ID must be provided");
482
483 // Note we can't do other null checks here because SM.updateShortcuts() takes partial
484 // information.
485 mPackageName = b.mContext.getPackageName();
486 mActivity = b.mActivity;
487 mIcon = b.mIcon;
488 mTitle = b.mTitle;
489 mTitleResId = b.mTitleResId;
490 mText = b.mText;
491 mTextResId = b.mTextResId;
492 mDisabledMessage = b.mDisabledMessage;
493 mDisabledMessageResId = b.mDisabledMessageResId;
494 mCategories = cloneCategories(b.mCategories);
495 mIntents = cloneIntents(b.mIntents);
496 fixUpIntentExtras();
497 mPersons = clonePersons(b.mPersons);
498 if (b.mIsLongLived) {
499 setLongLived();
500 }
501 mExcludedSurfaces = b.mExcludedSurfaces;
502 mRank = b.mRank;
503 mExtras = b.mExtras;
504 mLocusId = b.mLocusId;
505 mCapabilityBindings =
506 cloneCapabilityBindings(b.mCapabilityBindings);
507 mStartingThemeResName = b.mStartingThemeResId != 0
508 ? b.mContext.getResources().getResourceName(b.mStartingThemeResId) : null;
509 updateTimestamp();
510 }
511
512 /**
513 * Extract extras from {@link #mIntents} and set them to {@link #mIntentPersistableExtrases}
514 * as {@link PersistableBundle}, and remove extras from the original intents.
515 */
516 private void fixUpIntentExtras() {
517 if (mIntents == null) {
518 mIntentPersistableExtrases = null;
519 return;
520 }
521 mIntentPersistableExtrases = new PersistableBundle[mIntents.length];
522 for (int i = 0; i < mIntents.length; i++) {
523 final Intent intent = mIntents[i];
524 final Bundle extras = intent.getExtras();
525 if (extras == null) {
526 mIntentPersistableExtrases[i] = null;
527 } else {
528 mIntentPersistableExtrases[i] = new PersistableBundle(extras);
529 intent.replaceExtras((Bundle) null);
530 }
531 }
532 }
533
534 private static ArraySet<String> cloneCategories(Set<String> source) {
535 if (source == null) {
536 return null;
537 }
538 final ArraySet<String> ret = new ArraySet<>(source.size());
539 for (CharSequence s : source) {
540 if (!TextUtils.isEmpty(s)) {
541 ret.add(s.toString().intern());
542 }
543 }
544 return ret;
545 }
546
547 private static Intent[] cloneIntents(Intent[] intents) {
548 if (intents == null) {
549 return null;
550 }
551 final Intent[] ret = new Intent[intents.length];
552 for (int i = 0; i < ret.length; i++) {
553 if (intents[i] != null) {
554 ret[i] = new Intent(intents[i]);
555 }
556 }
557 return ret;
558 }
559
560 private static PersistableBundle[] clonePersistableBundle(PersistableBundle[] bundle) {
561 if (bundle == null) {
562 return null;
563 }
564 final PersistableBundle[] ret = new PersistableBundle[bundle.length];
565 for (int i = 0; i < ret.length; i++) {
566 if (bundle[i] != null) {
567 ret[i] = new PersistableBundle(bundle[i]);
568 }
569 }
570 return ret;
571 }
572
573 private static Person[] clonePersons(Person[] persons) {
574 if (persons == null) {
575 return null;
576 }
577 final Person[] ret = new Person[persons.length];
578 for (int i = 0; i < ret.length; i++) {
579 if (persons[i] != null) {
580 // Don't need to keep the icon, remove it to save space
581 ret[i] = persons[i].toBuilder().setIcon(null).build();
582 }
583 }
584 return ret;
585 }
586
587 /**
588 * Throws if any of the mandatory fields is not set.
589 *
590 * @hide
591 */
592 public void enforceMandatoryFields(boolean forPinned) {
593 Preconditions.checkStringNotEmpty(mId, "Shortcut ID must be provided");
594 if (!forPinned) {
595 Objects.requireNonNull(mActivity, "Activity must be provided");
596 }
597 if (mTitle == null && mTitleResId == 0) {
598 throw new IllegalArgumentException("Short label must be provided");
599 }
600 Objects.requireNonNull(mIntents, "Shortcut Intent must be provided");
601 Preconditions.checkArgument(mIntents.length > 0, "Shortcut Intent must be provided");
602 }
603
604 /**
605 * Copy constructor.
606 */
607 private ShortcutInfo(ShortcutInfo source, @CloneFlags int cloneFlags) {
608 mUserId = source.mUserId;
609 mId = source.mId;
610 mPackageName = source.mPackageName;
611 mActivity = source.mActivity;
612 mFlags = source.mFlags;
613 mLastChangedTimestamp = source.mLastChangedTimestamp;
614 mDisabledReason = source.mDisabledReason;
615 mLocusId = source.mLocusId;
616 mExcludedSurfaces = source.mExcludedSurfaces;
617
618 // Just always keep it since it's cheap.
619 mIconResId = source.mIconResId;
620
621 if ((cloneFlags & CLONE_REMOVE_NON_KEY_INFO) == 0) {
622
623 if ((cloneFlags & CLONE_REMOVE_ICON) == 0) {
624 mIcon = source.mIcon;
625 mBitmapPath = source.mBitmapPath;
626 mIconUri = source.mIconUri;
627 }
628
629 mTitle = source.mTitle;
630 mTitleResId = source.mTitleResId;
631 mText = source.mText;
632 mTextResId = source.mTextResId;
633 mDisabledMessage = source.mDisabledMessage;
634 mDisabledMessageResId = source.mDisabledMessageResId;
635 mCategories = cloneCategories(source.mCategories);
636 if ((cloneFlags & CLONE_REMOVE_PERSON) == 0) {
637 mPersons = clonePersons(source.mPersons);
638 }
639 if ((cloneFlags & CLONE_REMOVE_INTENT) == 0) {
640 mIntents = cloneIntents(source.mIntents);
641 mIntentPersistableExtrases =
642 clonePersistableBundle(source.mIntentPersistableExtrases);
643 }
644 mRank = source.mRank;
645 mExtras = source.mExtras;
646
647 if ((cloneFlags & CLONE_REMOVE_RES_NAMES) == 0) {
648 mTitleResName = source.mTitleResName;
649 mTextResName = source.mTextResName;
650 mDisabledMessageResName = source.mDisabledMessageResName;
651 mIconResName = source.mIconResName;
652 }
653 } else {
654 // Set this bit.
655 mFlags |= FLAG_KEY_FIELDS_ONLY;
656 }
657 mCapabilityBindings = cloneCapabilityBindings(
658 source.mCapabilityBindings);
659 mStartingThemeResName = source.mStartingThemeResName;
660 }
661
662 /**
663 * Convert a {@link GenericDocument} into a ShortcutInfo.
664 *
665 * @param context Client context
666 * @param document An instance of {@link GenericDocument} that represents the shortcut.
667 */
668 @NonNull
669 public static ShortcutInfo createFromGenericDocument(@NonNull final Context context,
670 @NonNull final GenericDocument document) {
671 Objects.requireNonNull(context);
672 Objects.requireNonNull(document);
673 return createFromGenericDocument(context.getUserId(), document);
674 }
675
676 /**
677 * @hide
678 */
679 public static ShortcutInfo createFromGenericDocument(
680 final int userId, @NonNull final GenericDocument document) {
681 return new AppSearchShortcutInfo(document).toShortcutInfo(userId);
682 }
683
684 /**
685 * Load a string resource from the publisher app.
686 *
687 * @param resId resource ID
688 * @param defValue default value to be returned when the specified resource isn't found.
689 */
690 private CharSequence getResourceString(Resources res, int resId, CharSequence defValue) {
691 try {
692 return res.getString(resId);
693 } catch (NotFoundException e) {
694 Log.e(TAG, "Resource for ID=" + resId + " not found in package " + mPackageName);
695 return defValue;
696 }
697 }
698
699 /**
700 * Load the string resources for the text fields and set them to the actual value fields.
701 * This will set {@link #FLAG_STRINGS_RESOLVED}.
702 *
703 * @param res {@link Resources} for the publisher. Must have been loaded with
704 * {@link PackageManager#getResourcesForApplication(String)}.
705 *
706 * @hide
707 */
708 public void resolveResourceStrings(@NonNull Resources res) {
709 mFlags |= FLAG_STRINGS_RESOLVED;
710
711 if ((mTitleResId == 0) && (mTextResId == 0) && (mDisabledMessageResId == 0)) {
712 return; // Bail early.
713 }
714
715 if (mTitleResId != 0) {
716 mTitle = getResourceString(res, mTitleResId, mTitle);
717 }
718 if (mTextResId != 0) {
719 mText = getResourceString(res, mTextResId, mText);
720 }
721 if (mDisabledMessageResId != 0) {
722 mDisabledMessage = getResourceString(res, mDisabledMessageResId, mDisabledMessage);
723 }
724 }
725
726 /**
727 * Look up resource name for a given resource ID.
728 *
729 * @return a simple resource name (e.g. "text_1") when {@code withType} is false, or with the
730 * type (e.g. "string/text_1").
731 *
732 * @hide
733 */
734 @VisibleForTesting
735 public static String lookUpResourceName(@NonNull Resources res, int resId, boolean withType,
736 @NonNull String packageName) {
737 if (resId == 0) {
738 return null;
739 }
740 try {
741 final String fullName = res.getResourceName(resId);
742
743 if (ANDROID_PACKAGE_NAME.equals(getResourcePackageName(fullName))) {
744 // If it's a framework resource, the value won't change, so just return the ID
745 // value as a string.
746 return String.valueOf(resId);
747 }
748 return withType ? getResourceTypeAndEntryName(fullName)
749 : getResourceEntryName(fullName);
750 } catch (NotFoundException e) {
751 Log.e(TAG, "Resource name for ID=" + resId + " not found in package " + packageName
752 + ". Resource IDs may change when the application is upgraded, and the system"
753 + " may not be able to find the correct resource.");
754 return null;
755 }
756 }
757
758 /**
759 * Extract the package name from a fully-donated resource name.
760 * e.g. "com.android.app1:drawable/icon1" -> "com.android.app1"
761 * @hide
762 */
763 @VisibleForTesting
764 public static String getResourcePackageName(@NonNull String fullResourceName) {
765 final int p1 = fullResourceName.indexOf(':');
766 if (p1 < 0) {
767 return null;
768 }
769 return fullResourceName.substring(0, p1);
770 }
771
772 /**
773 * Extract the type name from a fully-donated resource name.
774 * e.g. "com.android.app1:drawable/icon1" -> "drawable"
775 * @hide
776 */
777 @VisibleForTesting
778 public static String getResourceTypeName(@NonNull String fullResourceName) {
779 final int p1 = fullResourceName.indexOf(':');
780 if (p1 < 0) {
781 return null;
782 }
783 final int p2 = fullResourceName.indexOf('/', p1 + 1);
784 if (p2 < 0) {
785 return null;
786 }
787 return fullResourceName.substring(p1 + 1, p2);
788 }
789
790 /**
791 * Extract the type name + the entry name from a fully-donated resource name.
792 * e.g. "com.android.app1:drawable/icon1" -> "drawable/icon1"
793 * @hide
794 */
795 @VisibleForTesting
796 public static String getResourceTypeAndEntryName(@NonNull String fullResourceName) {
797 final int p1 = fullResourceName.indexOf(':');
798 if (p1 < 0) {
799 return null;
800 }
801 return fullResourceName.substring(p1 + 1);
802 }
803
804 /**
805 * Extract the entry name from a fully-donated resource name.
806 * e.g. "com.android.app1:drawable/icon1" -> "icon1"
807 * @hide
808 */
809 @VisibleForTesting
810 public static String getResourceEntryName(@NonNull String fullResourceName) {
811 final int p1 = fullResourceName.indexOf('/');
812 if (p1 < 0) {
813 return null;
814 }
815 return fullResourceName.substring(p1 + 1);
816 }
817
818 /**
819 * Return the resource ID for a given resource ID.
820 *
821 * Basically its' a wrapper over {@link Resources#getIdentifier(String, String, String)}, except
822 * if {@code resourceName} is an integer then it'll just return its value. (Which also the
823 * aforementioned method would do internally, but not documented, so doing here explicitly.)
824 *
825 * @param res {@link Resources} for the publisher. Must have been loaded with
826 * {@link PackageManager#getResourcesForApplication(String)}.
827 *
828 * @hide
829 */
830 @VisibleForTesting
831 public static int lookUpResourceId(@NonNull Resources res, @Nullable String resourceName,
832 @Nullable String resourceType, String packageName) {
833 if (resourceName == null) {
834 return 0;
835 }
836 try {
837 try {
838 // It the name can be parsed as an integer, just use it.
839 return Integer.parseInt(resourceName);
840 } catch (NumberFormatException ignore) {
841 }
842
843 return res.getIdentifier(resourceName, resourceType, packageName);
844 } catch (NotFoundException e) {
845 Log.e(TAG, "Resource ID for name=" + resourceName + " not found in package "
846 + packageName);
847 return 0;
848 }
849 }
850
851 /**
852 * Look up resource names from the resource IDs for the icon res and the text fields, and fill
853 * in the resource name fields.
854 *
855 * @param res {@link Resources} for the publisher. Must have been loaded with
856 * {@link PackageManager#getResourcesForApplication(String)}.
857 *
858 * @hide
859 */
860 public void lookupAndFillInResourceNames(@NonNull Resources res) {
861 if ((mTitleResId == 0) && (mTextResId == 0) && (mDisabledMessageResId == 0)
862 && (mIconResId == 0)) {
863 return; // Bail early.
864 }
865
866 // We don't need types for strings because their types are always "string".
867 mTitleResName = lookUpResourceName(res, mTitleResId, /*withType=*/ false, mPackageName);
868 mTextResName = lookUpResourceName(res, mTextResId, /*withType=*/ false, mPackageName);
869 mDisabledMessageResName = lookUpResourceName(res, mDisabledMessageResId,
870 /*withType=*/ false, mPackageName);
871
872 // But icons have multiple possible types, so include the type.
873 mIconResName = lookUpResourceName(res, mIconResId, /*withType=*/ true, mPackageName);
874 }
875
876 /**
877 * Look up resource IDs from the resource names for the icon res and the text fields, and fill
878 * in the resource ID fields.
879 *
880 * This is called when an app is updated.
881 *
882 * @hide
883 */
884 public void lookupAndFillInResourceIds(@NonNull Resources res) {
885 if ((mTitleResName == null) && (mTextResName == null) && (mDisabledMessageResName == null)
886 && (mIconResName == null)) {
887 return; // Bail early.
888 }
889
890 mTitleResId = lookUpResourceId(res, mTitleResName, RES_TYPE_STRING, mPackageName);
891 mTextResId = lookUpResourceId(res, mTextResName, RES_TYPE_STRING, mPackageName);
892 mDisabledMessageResId = lookUpResourceId(res, mDisabledMessageResName, RES_TYPE_STRING,
893 mPackageName);
894
895 // mIconResName already contains the type, so the third argument is not needed.
896 mIconResId = lookUpResourceId(res, mIconResName, null, mPackageName);
897 }
898
899 /**
900 * Copy a {@link ShortcutInfo}, optionally removing fields.
901 * @hide
902 */
903 public ShortcutInfo clone(@CloneFlags int cloneFlags) {
904 return new ShortcutInfo(this, cloneFlags);
905 }
906
907 /**
908 * @hide
909 *
910 * @isUpdating set true if it's "update", as opposed to "replace".
911 */
912 public void ensureUpdatableWith(ShortcutInfo source, boolean isUpdating) {
913 if (isUpdating) {
914 Preconditions.checkState(isVisibleToPublisher(),
915 "[Framework BUG] Invisible shortcuts can't be updated");
916 }
917 Preconditions.checkState(mUserId == source.mUserId, "Owner User ID must match");
918 Preconditions.checkState(mId.equals(source.mId), "ID must match");
919 Preconditions.checkState(mPackageName.equals(source.mPackageName),
920 "Package name must match");
921
922 if (isVisibleToPublisher()) {
923 // Don't do this check for restore-blocked shortcuts.
924 Preconditions.checkState(!isImmutable(), "Target ShortcutInfo is immutable");
925 }
926 }
927
928 /**
929 * Copy non-null/zero fields from another {@link ShortcutInfo}. Only "public" information
930 * will be overwritten. The timestamp will *not* be updated to be consistent with other
931 * setters (and also the clock is not injectable in this file).
932 *
933 * - Flags will not change
934 * - mBitmapPath will not change
935 * - Current time will be set to timestamp
936 *
937 * @throws IllegalStateException if source is not compatible.
938 *
939 * @hide
940 */
941 public void copyNonNullFieldsFrom(ShortcutInfo source) {
942 ensureUpdatableWith(source, /*isUpdating=*/ true);
943
944 if (source.mActivity != null) {
945 mActivity = source.mActivity;
946 }
947
948 if (source.mIcon != null) {
949 mIcon = source.mIcon;
950
951 mIconResId = 0;
952 mIconResName = null;
953 mBitmapPath = null;
954 mIconUri = null;
955 }
956 if (source.mTitle != null) {
957 mTitle = source.mTitle;
958 mTitleResId = 0;
959 mTitleResName = null;
960 } else if (source.mTitleResId != 0) {
961 mTitle = null;
962 mTitleResId = source.mTitleResId;
963 mTitleResName = null;
964 }
965
966 if (source.mText != null) {
967 mText = source.mText;
968 mTextResId = 0;
969 mTextResName = null;
970 } else if (source.mTextResId != 0) {
971 mText = null;
972 mTextResId = source.mTextResId;
973 mTextResName = null;
974 }
975 if (source.mDisabledMessage != null) {
976 mDisabledMessage = source.mDisabledMessage;
977 mDisabledMessageResId = 0;
978 mDisabledMessageResName = null;
979 } else if (source.mDisabledMessageResId != 0) {
980 mDisabledMessage = null;
981 mDisabledMessageResId = source.mDisabledMessageResId;
982 mDisabledMessageResName = null;
983 }
984 if (source.mCategories != null) {
985 mCategories = cloneCategories(source.mCategories);
986 }
987 if (source.mPersons != null) {
988 mPersons = clonePersons(source.mPersons);
989 }
990 if (source.mIntents != null) {
991 mIntents = cloneIntents(source.mIntents);
992 mIntentPersistableExtrases =
993 clonePersistableBundle(source.mIntentPersistableExtrases);
994 }
995 if (source.mRank != RANK_NOT_SET) {
996 mRank = source.mRank;
997 }
998 if (source.mExtras != null) {
999 mExtras = source.mExtras;
1000 }
1001
1002 if (source.mLocusId != null) {
1003 mLocusId = source.mLocusId;
1004 }
1005 if (source.mStartingThemeResName != null && !source.mStartingThemeResName.isEmpty()) {
1006 mStartingThemeResName = source.mStartingThemeResName;
1007 }
1008 if (source.mCapabilityBindings != null) {
1009 mCapabilityBindings =
1010 cloneCapabilityBindings(source.mCapabilityBindings);
1011 }
1012 }
1013
1014 /**
1015 * @hide
1016 */
1017 public static Icon validateIcon(Icon icon) {
1018 switch (icon.getType()) {
1019 case Icon.TYPE_RESOURCE:
1020 case Icon.TYPE_BITMAP:
1021 case Icon.TYPE_ADAPTIVE_BITMAP:
1022 case Icon.TYPE_URI:
1023 case Icon.TYPE_URI_ADAPTIVE_BITMAP:
1024 break; // OK
1025 default:
1026 throw getInvalidIconException();
1027 }
1028 if (icon.hasTint()) {
1029 throw new IllegalArgumentException("Icons with tints are not supported");
1030 }
1031
1032 return icon;
1033 }
1034
1035 /** @hide */
1036 public static IllegalArgumentException getInvalidIconException() {
1037 return new IllegalArgumentException("Unsupported icon type:"
1038 +" only the bitmap and resource types are supported");
1039 }
1040
1041 /**
1042 * Builder class for {@link ShortcutInfo} objects.
1043 *
1044 * @see ShortcutManager
1045 */
1046 public static class Builder {
1047 private final Context mContext;
1048
1049 private String mId;
1050
1051 private ComponentName mActivity;
1052
1053 private Icon mIcon;
1054
1055 private int mTitleResId;
1056
1057 private CharSequence mTitle;
1058
1059 private int mTextResId;
1060
1061 private CharSequence mText;
1062
1063 private int mDisabledMessageResId;
1064
1065 private CharSequence mDisabledMessage;
1066
1067 private Set<String> mCategories;
1068
1069 private Intent[] mIntents;
1070
1071 private Person[] mPersons;
1072
1073 private boolean mIsLongLived;
1074
1075 private int mRank = RANK_NOT_SET;
1076
1077 private PersistableBundle mExtras;
1078
1079 private LocusId mLocusId;
1080
1081 private int mStartingThemeResId;
1082
1083 @Nullable
1084 private Map<String, Map<String, List<String>>> mCapabilityBindings;
1085
1086 private int mExcludedSurfaces;
1087
1088 /**
1089 * Old style constructor.
1090 * @hide
1091 */
1092 @Deprecated
1093 public Builder(Context context) {
1094 mContext = context;
1095 }
1096
1097 /**
1098 * Used with the old style constructor, kept for unit tests.
1099 * @hide
1100 */
1101 @NonNull
1102 @Deprecated
1103 public Builder setId(@NonNull String id) {
1104 mId = Preconditions.checkStringNotEmpty(id, "id cannot be empty");
1105 return this;
1106 }
1107
1108 /**
1109 * Constructor.
1110 *
1111 * @param context Client context.
1112 * @param id ID of the shortcut.
1113 */
1114 public Builder(Context context, String id) {
1115 mContext = context;
1116 mId = Preconditions.checkStringNotEmpty(id, "id cannot be empty");
1117 }
1118
1119 /**
1120 * Sets the {@link LocusId} associated with this shortcut.
1121 *
1122 * <p>This method should be called when the {@link LocusId} is used in other places (such
1123 * as {@link Notification} and {@link ContentCaptureContext}) so the device's intelligence
1124 * services can correlate them.
1125 */
1126 @NonNull
1127 public Builder setLocusId(@NonNull LocusId locusId) {
1128 mLocusId = Objects.requireNonNull(locusId, "locusId cannot be null");
1129 return this;
1130 }
1131
1132 /**
1133 * Sets the target activity. A shortcut will be shown along with this activity's icon
1134 * on the launcher.
1135 *
1136 * When selecting a target activity, keep the following in mind:
1137 * <ul>
1138 * <li>All dynamic shortcuts must have a target activity. When a shortcut with no target
1139 * activity is published using
1140 * {@link ShortcutManager#addDynamicShortcuts(List)} or
1141 * {@link ShortcutManager#setDynamicShortcuts(List)},
1142 * the first main activity defined in the app's <code>AndroidManifest.xml</code>
1143 * file is used.
1144 *
1145 * <li>Only "main" activities&mdash;ones that define the {@link Intent#ACTION_MAIN}
1146 * and {@link Intent#CATEGORY_LAUNCHER} intent filters&mdash;can be target
1147 * activities.
1148 *
1149 * <li>By default, the first main activity defined in the app's manifest is
1150 * the target activity.
1151 *
1152 * <li>A target activity must belong to the publisher app.
1153 * </ul>
1154 *
1155 * @see ShortcutInfo#getActivity()
1156 */
1157 @NonNull
1158 public Builder setActivity(@NonNull ComponentName activity) {
1159 mActivity = Objects.requireNonNull(activity, "activity cannot be null");
1160 return this;
1161 }
1162
1163 /**
1164 * Sets an icon of a shortcut.
1165 *
1166 * <p>Icons are not available on {@link ShortcutInfo} instances
1167 * returned by {@link ShortcutManager} or {@link LauncherApps}. The default launcher
1168 * app can use {@link LauncherApps#getShortcutIconDrawable(ShortcutInfo, int)}
1169 * or {@link LauncherApps#getShortcutBadgedIconDrawable(ShortcutInfo, int)} to fetch
1170 * shortcut icons.
1171 *
1172 * <p>Tints set with {@link Icon#setTint} or {@link Icon#setTintList} are not supported
1173 * and will be ignored.
1174 *
1175 * <p>Only icons created with {@link Icon#createWithBitmap(Bitmap)},
1176 * {@link Icon#createWithAdaptiveBitmap(Bitmap)}
1177 * and {@link Icon#createWithResource} are supported.
1178 * Other types, such as URI-based icons, are not supported.
1179 *
1180 * @see LauncherApps#getShortcutIconDrawable(ShortcutInfo, int)
1181 * @see LauncherApps#getShortcutBadgedIconDrawable(ShortcutInfo, int)
1182 */
1183 @NonNull
1184 public Builder setIcon(Icon icon) {
1185 mIcon = validateIcon(icon);
1186 return this;
1187 }
1188
1189 /**
1190 * Sets a theme resource id for the splash screen.
1191 */
1192 @NonNull
1193 public Builder setStartingTheme(int themeResId) {
1194 mStartingThemeResId = themeResId;
1195 return this;
1196 }
1197
1198 /**
1199 * @hide We don't support resource strings for dynamic shortcuts for now. (But unit tests
1200 * use it.)
1201 */
1202 @Deprecated
1203 public Builder setShortLabelResId(int shortLabelResId) {
1204 Preconditions.checkState(mTitle == null, "shortLabel already set");
1205 mTitleResId = shortLabelResId;
1206 return this;
1207 }
1208
1209 /**
1210 * Sets the short title of a shortcut.
1211 *
1212 * <p>This is a mandatory field when publishing a new shortcut with
1213 * {@link ShortcutManager#addDynamicShortcuts(List)} or
1214 * {@link ShortcutManager#setDynamicShortcuts(List)}.
1215 *
1216 * <p>This field is intended to be a concise description of a shortcut.
1217 *
1218 * <p>The recommended maximum length is 10 characters.
1219 *
1220 * @see ShortcutInfo#getShortLabel()
1221 */
1222 @NonNull
1223 public Builder setShortLabel(@NonNull CharSequence shortLabel) {
1224 Preconditions.checkState(mTitleResId == 0, "shortLabelResId already set");
1225 mTitle = Preconditions.checkStringNotEmpty(shortLabel, "shortLabel cannot be empty");
1226 return this;
1227 }
1228
1229 /**
1230 * @hide We don't support resource strings for dynamic shortcuts for now. (But unit tests
1231 * use it.)
1232 */
1233 @Deprecated
1234 public Builder setLongLabelResId(int longLabelResId) {
1235 Preconditions.checkState(mText == null, "longLabel already set");
1236 mTextResId = longLabelResId;
1237 return this;
1238 }
1239
1240 /**
1241 * Sets the text of a shortcut.
1242 *
1243 * <p>This field is intended to be more descriptive than the shortcut title. The launcher
1244 * shows this instead of the short title when it has enough space.
1245 *
1246 * <p>The recommend maximum length is 25 characters.
1247 *
1248 * @see ShortcutInfo#getLongLabel()
1249 */
1250 @NonNull
1251 public Builder setLongLabel(@NonNull CharSequence longLabel) {
1252 Preconditions.checkState(mTextResId == 0, "longLabelResId already set");
1253 mText = Preconditions.checkStringNotEmpty(longLabel, "longLabel cannot be empty");
1254 return this;
1255 }
1256
1257 /** @hide -- old signature, the internal code still uses it. */
1258 @Deprecated
1259 public Builder setTitle(@NonNull CharSequence value) {
1260 return setShortLabel(value);
1261 }
1262
1263 /** @hide -- old signature, the internal code still uses it. */
1264 @Deprecated
1265 public Builder setTitleResId(int value) {
1266 return setShortLabelResId(value);
1267 }
1268
1269 /** @hide -- old signature, the internal code still uses it. */
1270 @Deprecated
1271 public Builder setText(@NonNull CharSequence value) {
1272 return setLongLabel(value);
1273 }
1274
1275 /** @hide -- old signature, the internal code still uses it. */
1276 @Deprecated
1277 public Builder setTextResId(int value) {
1278 return setLongLabelResId(value);
1279 }
1280
1281 /**
1282 * @hide We don't support resource strings for dynamic shortcuts for now. (But unit tests
1283 * use it.)
1284 */
1285 @Deprecated
1286 public Builder setDisabledMessageResId(int disabledMessageResId) {
1287 Preconditions.checkState(mDisabledMessage == null, "disabledMessage already set");
1288 mDisabledMessageResId = disabledMessageResId;
1289 return this;
1290 }
1291
1292 /**
1293 * Sets the message that should be shown when the user attempts to start a shortcut that
1294 * is disabled.
1295 *
1296 * @see ShortcutInfo#getDisabledMessage()
1297 */
1298 @NonNull
1299 public Builder setDisabledMessage(@NonNull CharSequence disabledMessage) {
1300 Preconditions.checkState(
1301 mDisabledMessageResId == 0, "disabledMessageResId already set");
1302 mDisabledMessage =
1303 Preconditions.checkStringNotEmpty(disabledMessage,
1304 "disabledMessage cannot be empty");
1305 return this;
1306 }
1307
1308 /**
1309 * Sets categories for a shortcut.
1310 * <ul>
1311 * <li>Launcher apps may use this information to categorize shortcuts
1312 * <li> Used by the system to associate a published Sharing Shortcut with supported
1313 * mimeTypes. Required for published Sharing Shortcuts with a matching category
1314 * declared in share targets, defined in the app's manifest linked shortcuts xml file.
1315 * </ul>
1316 *
1317 * @see #SHORTCUT_CATEGORY_CONVERSATION
1318 * @see ShortcutInfo#getCategories()
1319 */
1320 @NonNull
1321 public Builder setCategories(Set<String> categories) {
1322 mCategories = categories;
1323 return this;
1324 }
1325
1326 /**
1327 * Sets the intent of a shortcut. Alternatively, {@link #setIntents(Intent[])} can be used
1328 * to launch an activity with other activities in the back stack.
1329 *
1330 * <p>This is a mandatory field when publishing a new shortcut with
1331 * {@link ShortcutManager#addDynamicShortcuts(List)} or
1332 * {@link ShortcutManager#setDynamicShortcuts(List)}.
1333 *
1334 * <p>A shortcut can launch any intent that the publisher app has permission to
1335 * launch. For example, a shortcut can launch an unexported activity within the publisher
1336 * app. A shortcut intent doesn't have to point at the target activity.
1337 *
1338 * <p>The given {@code intent} can contain extras, but these extras must contain values
1339 * of primitive types in order for the system to persist these values.
1340 *
1341 * @see ShortcutInfo#getIntent()
1342 * @see #setIntents(Intent[])
1343 */
1344 @NonNull
1345 public Builder setIntent(@NonNull Intent intent) {
1346 return setIntents(new Intent[]{intent});
1347 }
1348
1349 /**
1350 * Sets multiple intents instead of a single intent, in order to launch an activity with
1351 * other activities in back stack. Use {@link TaskStackBuilder} to build intents. The
1352 * last element in the list represents the only intent that doesn't place an activity on
1353 * the back stack.
1354 * See the {@link ShortcutManager} javadoc for details.
1355 *
1356 * @see Builder#setIntent(Intent)
1357 * @see ShortcutInfo#getIntents()
1358 * @see Context#startActivities(Intent[])
1359 * @see TaskStackBuilder
1360 */
1361 @NonNull
1362 public Builder setIntents(@NonNull Intent[] intents) {
1363 Objects.requireNonNull(intents, "intents cannot be null");
1364 if (intents.length == 0) {
1365 throw new IllegalArgumentException("intents cannot be empty");
1366 }
1367 for (Intent intent : intents) {
1368 Objects.requireNonNull(intent, "intents cannot contain null");
1369 Objects.requireNonNull(intent.getAction(), "intent's action must be set");
1370 }
1371 // Make sure always clone incoming intents.
1372 mIntents = cloneIntents(intents);
1373 return this;
1374 }
1375
1376 /**
1377 * Add a person that is relevant to this shortcut. Alternatively,
1378 * {@link #setPersons(Person[])} can be used to add multiple persons to a shortcut.
1379 *
1380 * <p> This is an optional field, but the addition of person may cause this shortcut to
1381 * appear more prominently in the user interface (e.g. ShareSheet).
1382 *
1383 * <p> A person should usually contain a uri in order to benefit from the ranking boost.
1384 * However, even if no uri is provided, it's beneficial to provide people in the shortcut,
1385 * such that listeners and voice only devices can announce and handle them properly.
1386 *
1387 * @see Person
1388 * @see #setPersons(Person[])
1389 */
1390 @NonNull
1391 public Builder setPerson(@NonNull Person person) {
1392 return setPersons(new Person[]{person});
1393 }
1394
1395 /**
1396 * Sets multiple persons instead of a single person.
1397 *
1398 * @see Person
1399 * @see #setPerson(Person)
1400 */
1401 @NonNull
1402 public Builder setPersons(@NonNull Person[] persons) {
1403 Objects.requireNonNull(persons, "persons cannot be null");
1404 if (persons.length == 0) {
1405 throw new IllegalArgumentException("persons cannot be empty");
1406 }
1407 for (Person person : persons) {
1408 Objects.requireNonNull(person, "persons cannot contain null");
1409 }
1410 mPersons = clonePersons(persons);
1411 return this;
1412 }
1413
1414 /**
1415 * Sets if a shortcut would be valid even if it has been unpublished/invisible by the app
1416 * (as a dynamic or pinned shortcut). If it is long lived, it can be cached by various
1417 * system services even after it has been unpublished as a dynamic shortcut.
1418 */
1419 @NonNull
1420 public Builder setLongLived(boolean longLived) {
1421 mIsLongLived = longLived;
1422 return this;
1423 }
1424
1425 /**
1426 * "Rank" of a shortcut, which is a non-negative value that's used by the launcher app
1427 * to sort shortcuts.
1428 *
1429 * See {@link ShortcutInfo#getRank()} for details.
1430 */
1431 @NonNull
1432 public Builder setRank(int rank) {
1433 Preconditions.checkArgument((0 <= rank),
1434 "Rank cannot be negative or bigger than MAX_RANK");
1435 mRank = rank;
1436 return this;
1437 }
1438
1439 /**
1440 * Extras that the app can set for any purpose.
1441 *
1442 * <p>Apps can store arbitrary shortcut metadata in extras and retrieve the
1443 * metadata later using {@link ShortcutInfo#getExtras()}.
1444 */
1445 @NonNull
1446 public Builder setExtras(@NonNull PersistableBundle extras) {
1447 mExtras = extras;
1448 return this;
1449 }
1450
1451 /**
1452 * Associates a shortcut with a capability, and a parameter of that capability. Used when
1453 * the shortcut is an instance of a capability.
1454 *
1455 * <P>This method can be called multiple times to add multiple parameters to the same
1456 * capability.
1457 *
1458 * @param capability {@link Capability} associated with the shortcut.
1459 * @param capabilityParams Optional {@link CapabilityParams} associated with given
1460 * capability.
1461 */
1462 @NonNull
1463 public Builder addCapabilityBinding(@NonNull final Capability capability,
1464 @Nullable final CapabilityParams capabilityParams) {
1465 Objects.requireNonNull(capability);
1466 if (mCapabilityBindings == null) {
1467 mCapabilityBindings = new ArrayMap<>(1);
1468 }
1469 if (!mCapabilityBindings.containsKey(capability.getName())) {
1470 mCapabilityBindings.put(capability.getName(), new ArrayMap<>(0));
1471 }
1472 if (capabilityParams == null) {
1473 return this;
1474 }
1475 final Map<String, List<String>> params = mCapabilityBindings.get(capability.getName());
1476 params.put(capabilityParams.getName(), capabilityParams.getValues());
1477 return this;
1478 }
1479
1480 /**
1481 * Sets which surfaces a shortcut will be excluded from.
1482 *
1483 * If the shortcut is set to be excluded from {@link #SURFACE_LAUNCHER}, shortcuts will be
1484 * excluded from the search result of {@link android.content.pm.LauncherApps#getShortcuts(
1485 * android.content.pm.LauncherApps.ShortcutQuery, UserHandle)} nor
1486 * {@link android.content.pm.ShortcutManager#getShortcuts(int)}. This generally means the
1487 * shortcut would not be displayed by a launcher app (e.g. in Long-Press menu), while
1488 * remain visible in other surfaces such as assistant or on-device-intelligence.
1489 */
1490 @NonNull
1491 public Builder setExcludedFromSurfaces(final int surfaces) {
1492 mExcludedSurfaces = surfaces;
1493 return this;
1494 }
1495
1496 /**
1497 * Creates a {@link ShortcutInfo} instance.
1498 */
1499 @NonNull
1500 public ShortcutInfo build() {
1501 return new ShortcutInfo(this);
1502 }
1503 }
1504
1505 /**
1506 * Returns the ID of a shortcut.
1507 *
1508 * <p>Shortcut IDs are unique within each publisher app and must be stable across
1509 * devices so that shortcuts will still be valid when restored on a different device.
1510 * See {@link ShortcutManager} for details.
1511 */
1512 @NonNull
1513 public String getId() {
1514 return mId;
1515 }
1516
1517 /**
1518 * Gets the {@link LocusId} associated with this shortcut.
1519 *
1520 * <p>Used by the device's intelligence services to correlate objects (such as
1521 * {@link Notification} and {@link ContentCaptureContext}) that are correlated.
1522 */
1523 @Nullable
1524 public LocusId getLocusId() {
1525 return mLocusId;
1526 }
1527
1528 /**
1529 * Return the package name of the publisher app.
1530 */
1531 @NonNull
1532 public String getPackage() {
1533 return mPackageName;
1534 }
1535
1536 /**
1537 * Return the target activity.
1538 *
1539 * <p>This has nothing to do with the activity that this shortcut will launch.
1540 * Launcher apps should show the launcher icon for the returned activity alongside
1541 * this shortcut.
1542 *
1543 * @see Builder#setActivity
1544 */
1545 @Nullable
1546 public ComponentName getActivity() {
1547 return mActivity;
1548 }
1549
1550 /** @hide */
1551 public void setActivity(ComponentName activity) {
1552 mActivity = activity;
1553 }
1554
1555 /**
1556 * Returns the shortcut icon.
1557 *
1558 * @hide
1559 */
1560 @Nullable
1561 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
1562 public Icon getIcon() {
1563 return mIcon;
1564 }
1565
1566 /**
1567 * Returns the theme resource name used for the splash screen.
1568 * @hide
1569 */
1570 @Nullable
1571 public String getStartingThemeResName() {
1572 return mStartingThemeResName;
1573 }
1574
1575 /** @hide -- old signature, the internal code still uses it. */
1576 @Nullable
1577 @Deprecated
1578 public CharSequence getTitle() {
1579 return mTitle;
1580 }
1581
1582 /** @hide -- old signature, the internal code still uses it. */
1583 @Deprecated
1584 public int getTitleResId() {
1585 return mTitleResId;
1586 }
1587
1588 /** @hide -- old signature, the internal code still uses it. */
1589 @Nullable
1590 @Deprecated
1591 public CharSequence getText() {
1592 return mText;
1593 }
1594
1595 /** @hide -- old signature, the internal code still uses it. */
1596 @Deprecated
1597 public int getTextResId() {
1598 return mTextResId;
1599 }
1600
1601 /**
1602 * Return the short description of a shortcut.
1603 *
1604 * @see Builder#setShortLabel(CharSequence)
1605 */
1606 @Nullable
1607 public CharSequence getShortLabel() {
1608 return mTitle;
1609 }
1610
1611 /** @hide */
1612 public int getShortLabelResourceId() {
1613 return mTitleResId;
1614 }
1615
1616 /**
1617 * Return the long description of a shortcut.
1618 *
1619 * @see Builder#setLongLabel(CharSequence)
1620 */
1621 @Nullable
1622 public CharSequence getLongLabel() {
1623 return mText;
1624 }
1625
1626 /**
1627 * Returns the {@link #getLongLabel()} if it's populated, and if not, the
1628 * {@link #getShortLabel()}.
1629 * @hide
1630 */
1631 @Nullable
1632 public CharSequence getLabel() {
1633 CharSequence label = getLongLabel();
1634 if (TextUtils.isEmpty(label)) {
1635 label = getShortLabel();
1636 }
1637
1638 return label;
1639 }
1640
1641 /** @hide */
1642 public int getLongLabelResourceId() {
1643 return mTextResId;
1644 }
1645
1646 /**
1647 * Return the message that should be shown when the user attempts to start a shortcut
1648 * that is disabled.
1649 *
1650 * @see Builder#setDisabledMessage(CharSequence)
1651 */
1652 @Nullable
1653 public CharSequence getDisabledMessage() {
1654 return mDisabledMessage;
1655 }
1656
1657 /** @hide */
1658 public int getDisabledMessageResourceId() {
1659 return mDisabledMessageResId;
1660 }
1661
1662 /** @hide */
1663 public void setDisabledReason(@DisabledReason int reason) {
1664 mDisabledReason = reason;
1665 }
1666
1667 /**
1668 * Returns why a shortcut has been disabled.
1669 */
1670 @DisabledReason
1671 public int getDisabledReason() {
1672 return mDisabledReason;
1673 }
1674
1675 /**
1676 * Return the shortcut's categories.
1677 *
1678 * @see Builder#setCategories(Set)
1679 */
1680 @Nullable
1681 public Set<String> getCategories() {
1682 return mCategories;
1683 }
1684
1685 /**
1686 * Returns the intent that is executed when the user selects this shortcut.
1687 * If setIntents() was used, then return the last intent in the array.
1688 *
1689 * <p>Launcher apps <b>cannot</b> see the intent. If a {@link ShortcutInfo} is
1690 * obtained via {@link LauncherApps}, then this method will always return null.
1691 * Launchers can only start a shortcut intent with {@link LauncherApps#startShortcut}.
1692 *
1693 * @see Builder#setIntent(Intent)
1694 */
1695 @Nullable
1696 public Intent getIntent() {
1697 if (mIntents == null || mIntents.length == 0) {
1698 return null;
1699 }
1700 final int last = mIntents.length - 1;
1701 final Intent intent = new Intent(mIntents[last]);
1702 return setIntentExtras(intent, mIntentPersistableExtrases[last]);
1703 }
1704
1705 /**
1706 * Return the intent set with {@link Builder#setIntents(Intent[])}.
1707 *
1708 * <p>Launcher apps <b>cannot</b> see the intents. If a {@link ShortcutInfo} is
1709 * obtained via {@link LauncherApps}, then this method will always return null.
1710 * Launchers can only start a shortcut intent with {@link LauncherApps#startShortcut}.
1711 *
1712 * @see Builder#setIntents(Intent[])
1713 */
1714 @Nullable
1715 public Intent[] getIntents() {
1716 if (mIntents == null) {
1717 return null;
1718 }
1719 final Intent[] ret = new Intent[mIntents.length];
1720
1721 for (int i = 0; i < ret.length; i++) {
1722 ret[i] = new Intent(mIntents[i]);
1723 setIntentExtras(ret[i], mIntentPersistableExtrases[i]);
1724 }
1725
1726 return ret;
1727 }
1728
1729 /**
1730 * Return "raw" intents, which is the original intents without the extras.
1731 * @hide
1732 */
1733 @Nullable
1734 public Intent[] getIntentsNoExtras() {
1735 return mIntents;
1736 }
1737
1738 /**
1739 * Return the Persons set with {@link Builder#setPersons(Person[])}.
1740 *
1741 * @hide
1742 */
1743 @Nullable
1744 @SystemApi
1745 public Person[] getPersons() {
1746 return clonePersons(mPersons);
1747 }
1748
1749 /**
1750 * The extras in the intents. We convert extras into {@link PersistableBundle} so we can
1751 * persist them.
1752 * @hide
1753 */
1754 @Nullable
1755 public PersistableBundle[] getIntentPersistableExtrases() {
1756 return mIntentPersistableExtrases;
1757 }
1758
1759 /**
1760 * "Rank" of a shortcut, which is a non-negative, sequential value that's unique for each
1761 * {@link #getActivity} for each of the two types of shortcuts (static and dynamic).
1762 *
1763 * <p><em>Floating shortcuts</em>, or shortcuts that are neither static nor dynamic, will all
1764 * have rank 0, because they aren't sorted.
1765 *
1766 * See the {@link ShortcutManager}'s class javadoc for details.
1767 *
1768 * @see Builder#setRank(int)
1769 */
1770 public int getRank() {
1771 return mRank;
1772 }
1773
1774 /** @hide */
1775 public boolean hasRank() {
1776 return mRank != RANK_NOT_SET;
1777 }
1778
1779 /** @hide */
1780 public void setRank(int rank) {
1781 mRank = rank;
1782 }
1783
1784 /** @hide */
1785 public void clearImplicitRankAndRankChangedFlag() {
1786 mImplicitRank = 0;
1787 }
1788
1789 /** @hide */
1790 public void setImplicitRank(int rank) {
1791 // Make sure to keep RANK_CHANGED_BIT.
1792 mImplicitRank = (mImplicitRank & RANK_CHANGED_BIT) | (rank & IMPLICIT_RANK_MASK);
1793 }
1794
1795 /** @hide */
1796 public int getImplicitRank() {
1797 return mImplicitRank & IMPLICIT_RANK_MASK;
1798 }
1799
1800 /** @hide */
1801 public void setRankChanged() {
1802 mImplicitRank |= RANK_CHANGED_BIT;
1803 }
1804
1805 /** @hide */
1806 public boolean isRankChanged() {
1807 return (mImplicitRank & RANK_CHANGED_BIT) != 0;
1808 }
1809
1810 /**
1811 * Extras that the app can set for any purpose.
1812 *
1813 * @see Builder#setExtras(PersistableBundle)
1814 */
1815 @Nullable
1816 public PersistableBundle getExtras() {
1817 return mExtras;
1818 }
1819
1820 /** @hide */
1821 public int getUserId() {
1822 return mUserId;
1823 }
1824
1825 /**
1826 * {@link UserHandle} on which the publisher created this shortcut.
1827 */
1828 public UserHandle getUserHandle() {
1829 return UserHandle.of(mUserId);
1830 }
1831
1832 /**
1833 * Last time when any of the fields was updated.
1834 */
1835 public long getLastChangedTimestamp() {
1836 return mLastChangedTimestamp;
1837 }
1838
1839 /** @hide */
1840 @ShortcutFlags
1841 public int getFlags() {
1842 return mFlags;
1843 }
1844
1845 /** @hide*/
1846 public void replaceFlags(@ShortcutFlags int flags) {
1847 mFlags = flags;
1848 }
1849
1850 /** @hide*/
1851 public void addFlags(@ShortcutFlags int flags) {
1852 mFlags |= flags;
1853 }
1854
1855 /** @hide*/
1856 public void clearFlags(@ShortcutFlags int flags) {
1857 mFlags &= ~flags;
1858 }
1859
1860 /** @hide*/
1861 public boolean hasFlags(@ShortcutFlags int flags) {
1862 return (mFlags & flags) == flags;
1863 }
1864
1865 /** @hide */
1866 public boolean isReturnedByServer() {
1867 return hasFlags(FLAG_RETURNED_BY_SERVICE);
1868 }
1869
1870 /** @hide */
1871 public void setReturnedByServer() {
1872 addFlags(FLAG_RETURNED_BY_SERVICE);
1873 }
1874
1875 /** @hide */
1876 public boolean isLongLived() {
1877 return hasFlags(FLAG_LONG_LIVED);
1878 }
1879
1880 /** @hide */
1881 public void setLongLived() {
1882 addFlags(FLAG_LONG_LIVED);
1883 }
1884
1885 /** @hide */
1886 public void setCached(@ShortcutFlags int cacheFlag) {
1887 addFlags(cacheFlag);
1888 }
1889
1890 /** Return whether a shortcut is cached. */
1891 public boolean isCached() {
1892 return (getFlags() & FLAG_CACHED_ALL) != 0;
1893 }
1894
1895 /** Return whether a shortcut is dynamic. */
1896 public boolean isDynamic() {
1897 return hasFlags(FLAG_DYNAMIC);
1898 }
1899
1900 /** Return whether a shortcut is pinned. */
1901 public boolean isPinned() {
1902 return hasFlags(FLAG_PINNED);
1903 }
1904
1905 /**
1906 * Return whether a shortcut is static; that is, whether a shortcut is
1907 * published from AndroidManifest.xml. If {@code true}, the shortcut is
1908 * also {@link #isImmutable()}.
1909 *
1910 * <p>When an app is upgraded and a shortcut is no longer published from AndroidManifest.xml,
1911 * this will be set to {@code false}. If the shortcut is not pinned, then it'll disappear.
1912 * However, if it's pinned, it will still be visible, {@link #isEnabled()} will be
1913 * {@code false} and {@link #isImmutable()} will be {@code true}.
1914 */
1915 public boolean isDeclaredInManifest() {
1916 return hasFlags(FLAG_MANIFEST);
1917 }
1918
1919 /** @hide kept for unit tests */
1920 @Deprecated
1921 public boolean isManifestShortcut() {
1922 return isDeclaredInManifest();
1923 }
1924
1925 /**
1926 * @return true if pinned or cached, but neither static nor dynamic.
1927 * @hide
1928 */
1929 public boolean isFloating() {
1930 return (isPinned() || isCached()) && !(isDynamic() || isManifestShortcut());
1931 }
1932
1933 /** @hide */
1934 public boolean isOriginallyFromManifest() {
1935 return hasFlags(FLAG_IMMUTABLE);
1936 }
1937
1938 /** @hide */
1939 public boolean isDynamicVisible() {
1940 return isDynamic() && isVisibleToPublisher();
1941 }
1942
1943 /** @hide */
1944 public boolean isPinnedVisible() {
1945 return isPinned() && isVisibleToPublisher();
1946 }
1947
1948 /** @hide */
1949 public boolean isManifestVisible() {
1950 return isDeclaredInManifest() && isVisibleToPublisher();
1951 }
1952
1953 /** @hide */
1954 public boolean isNonManifestVisible() {
1955 return !isDeclaredInManifest() && isVisibleToPublisher()
1956 && (isPinned() || isCached() || isDynamic());
1957 }
1958
1959 /**
1960 * Return if a shortcut is immutable, in which case it cannot be modified with any of
1961 * {@link ShortcutManager} APIs.
1962 *
1963 * <p>All static shortcuts are immutable. When a static shortcut is pinned and is then
1964 * disabled because it doesn't appear in AndroidManifest.xml for a newer version of the
1965 * app, {@link #isDeclaredInManifest()} returns {@code false}, but the shortcut
1966 * is still immutable.
1967 *
1968 * <p>All shortcuts originally published via the {@link ShortcutManager} APIs
1969 * are all mutable.
1970 */
1971 public boolean isImmutable() {
1972 return hasFlags(FLAG_IMMUTABLE);
1973 }
1974
1975 /**
1976 * Returns {@code false} if a shortcut is disabled with
1977 * {@link ShortcutManager#disableShortcuts}.
1978 */
1979 public boolean isEnabled() {
1980 return !hasFlags(FLAG_DISABLED);
1981 }
1982
1983 /** @hide */
1984 public boolean isAlive() {
1985 return hasFlags(FLAG_PINNED) || hasFlags(FLAG_DYNAMIC) || hasFlags(FLAG_MANIFEST)
1986 || isCached();
1987 }
1988
1989 /** @hide */
1990 public boolean usesQuota() {
1991 return hasFlags(FLAG_DYNAMIC) || hasFlags(FLAG_MANIFEST);
1992 }
1993
1994 /**
1995 * Return whether a shortcut's icon is a resource in the owning package.
1996 *
1997 * @hide internal/unit tests only
1998 */
1999 public boolean hasIconResource() {
2000 return hasFlags(FLAG_HAS_ICON_RES);
2001 }
2002
2003 /**
2004 * Return whether a shortcut's icon is provided via a URI.
2005 *
2006 * @hide internal/unit tests only
2007 */
2008 public boolean hasIconUri() {
2009 return hasFlags(FLAG_HAS_ICON_URI);
2010 }
2011
2012 /** @hide */
2013 public boolean hasStringResources() {
2014 return (mTitleResId != 0) || (mTextResId != 0) || (mDisabledMessageResId != 0);
2015 }
2016
2017 /** @hide */
2018 public boolean hasAnyResources() {
2019 return hasIconResource() || hasStringResources();
2020 }
2021
2022 /**
2023 * Return whether a shortcut's icon is stored as a file.
2024 *
2025 * @hide internal/unit tests only
2026 */
2027 public boolean hasIconFile() {
2028 return hasFlags(FLAG_HAS_ICON_FILE);
2029 }
2030
2031 /**
2032 * Return whether a shortcut's icon is adaptive bitmap following design guideline
2033 * defined in {@link android.graphics.drawable.AdaptiveIconDrawable}.
2034 *
2035 * @hide internal/unit tests only
2036 */
2037 public boolean hasAdaptiveBitmap() {
2038 return hasFlags(FLAG_ADAPTIVE_BITMAP);
2039 }
2040
2041 /** @hide */
2042 public boolean isIconPendingSave() {
2043 return hasFlags(FLAG_ICON_FILE_PENDING_SAVE);
2044 }
2045
2046 /** @hide */
2047 public void setIconPendingSave() {
2048 addFlags(FLAG_ICON_FILE_PENDING_SAVE);
2049 }
2050
2051 /** @hide */
2052 public void clearIconPendingSave() {
2053 clearFlags(FLAG_ICON_FILE_PENDING_SAVE);
2054 }
2055
2056 /**
2057 * When the system wasn't able to restore a shortcut, it'll still be registered to the system
2058 * but disabled, and such shortcuts will not be visible to the publisher. They're still visible
2059 * to launchers though.
2060 *
2061 * @hide
2062 */
2063 @TestApi
2064 public boolean isVisibleToPublisher() {
2065 return !isDisabledForRestoreIssue(mDisabledReason);
2066 }
2067
2068 /**
2069 * Return whether a shortcut only contains "key" information only or not. If true, only the
2070 * following fields are available.
2071 * <ul>
2072 * <li>{@link #getId()}
2073 * <li>{@link #getPackage()}
2074 * <li>{@link #getActivity()}
2075 * <li>{@link #getLastChangedTimestamp()}
2076 * <li>{@link #isDynamic()}
2077 * <li>{@link #isPinned()}
2078 * <li>{@link #isDeclaredInManifest()}
2079 * <li>{@link #isImmutable()}
2080 * <li>{@link #isEnabled()}
2081 * <li>{@link #getUserHandle()}
2082 * </ul>
2083 *
2084 * <p>For performance reasons, shortcuts passed to
2085 * {@link LauncherApps.Callback#onShortcutsChanged(String, List, UserHandle)} as well as those
2086 * returned from {@link LauncherApps#getShortcuts(ShortcutQuery, UserHandle)}
2087 * while using the {@link ShortcutQuery#FLAG_GET_KEY_FIELDS_ONLY} option contain only key
2088 * information.
2089 */
2090 public boolean hasKeyFieldsOnly() {
2091 return hasFlags(FLAG_KEY_FIELDS_ONLY);
2092 }
2093
2094 /** @hide */
2095 public boolean hasStringResourcesResolved() {
2096 return hasFlags(FLAG_STRINGS_RESOLVED);
2097 }
2098
2099 /** @hide */
2100 public void updateTimestamp() {
2101 mLastChangedTimestamp = System.currentTimeMillis();
2102 }
2103
2104 /** @hide */
2105 // VisibleForTesting
2106 public void setTimestamp(long value) {
2107 mLastChangedTimestamp = value;
2108 }
2109
2110 /** @hide */
2111 public void clearIcon() {
2112 mIcon = null;
2113 }
2114
2115 /** @hide */
2116 public void setIconResourceId(int iconResourceId) {
2117 if (mIconResId != iconResourceId) {
2118 mIconResName = null;
2119 }
2120 mIconResId = iconResourceId;
2121 }
2122
2123 /**
2124 * Get the resource ID for the icon, valid only when {@link #hasIconResource()} } is true.
2125 * @hide internal / tests only.
2126 */
2127 public int getIconResourceId() {
2128 return mIconResId;
2129 }
2130
2131 /** @hide */
2132 public void setIconUri(String iconUri) {
2133 mIconUri = iconUri;
2134 }
2135
2136 /**
2137 * Get the Uri for the icon, valid only when {@link #hasIconUri()} } is true.
2138 * @hide internal / tests only.
2139 */
2140 public String getIconUri() {
2141 return mIconUri;
2142 }
2143
2144 /**
2145 * Bitmap path. Note this will be null even if {@link #hasIconFile()} is set when the save
2146 * is pending. Use {@link #isIconPendingSave()} to check it.
2147 *
2148 * @hide
2149 */
2150 public String getBitmapPath() {
2151 return mBitmapPath;
2152 }
2153
2154 /** @hide */
2155 public void setBitmapPath(String bitmapPath) {
2156 mBitmapPath = bitmapPath;
2157 }
2158
2159 /** @hide */
2160 public void setDisabledMessageResId(int disabledMessageResId) {
2161 if (mDisabledMessageResId != disabledMessageResId) {
2162 mDisabledMessageResName = null;
2163 }
2164 mDisabledMessageResId = disabledMessageResId;
2165 mDisabledMessage = null;
2166 }
2167
2168 /** @hide */
2169 public void setDisabledMessage(String disabledMessage) {
2170 mDisabledMessage = disabledMessage;
2171 mDisabledMessageResId = 0;
2172 mDisabledMessageResName = null;
2173 }
2174
2175 /** @hide */
2176 public String getTitleResName() {
2177 return mTitleResName;
2178 }
2179
2180 /** @hide */
2181 public void setTitleResName(String titleResName) {
2182 mTitleResName = titleResName;
2183 }
2184
2185 /** @hide */
2186 public String getTextResName() {
2187 return mTextResName;
2188 }
2189
2190 /** @hide */
2191 public void setTextResName(String textResName) {
2192 mTextResName = textResName;
2193 }
2194
2195 /** @hide */
2196 public String getDisabledMessageResName() {
2197 return mDisabledMessageResName;
2198 }
2199
2200 /** @hide */
2201 public void setDisabledMessageResName(String disabledMessageResName) {
2202 mDisabledMessageResName = disabledMessageResName;
2203 }
2204
2205 /** @hide */
2206 public String getIconResName() {
2207 return mIconResName;
2208 }
2209
2210 /** @hide */
2211 public void setIconResName(String iconResName) {
2212 mIconResName = iconResName;
2213 }
2214
2215 /**
2216 * Replaces the intent.
2217 *
2218 * @throws IllegalArgumentException when extra is not compatible with {@link PersistableBundle}.
2219 *
2220 * @hide
2221 */
2222 public void setIntents(Intent[] intents) throws IllegalArgumentException {
2223 Objects.requireNonNull(intents);
2224 Preconditions.checkArgument(intents.length > 0);
2225
2226 mIntents = cloneIntents(intents);
2227 fixUpIntentExtras();
2228 }
2229
2230 /** @hide */
2231 public static Intent setIntentExtras(Intent intent, PersistableBundle extras) {
2232 if (extras == null) {
2233 intent.replaceExtras((Bundle) null);
2234 } else {
2235 intent.replaceExtras(new Bundle(extras));
2236 }
2237 return intent;
2238 }
2239
2240 /**
2241 * Replaces the categories.
2242 *
2243 * @hide
2244 */
2245 public void setCategories(Set<String> categories) {
2246 mCategories = cloneCategories(categories);
2247 }
2248
2249 /**
2250 * Return true if the shortcut is excluded from specified surface.
2251 */
2252 public boolean isExcludedFromSurfaces(@Surface int surface) {
2253 return (mExcludedSurfaces & surface) != 0;
2254 }
2255
2256 /**
2257 * Returns a bitmask of all surfaces this shortcut is excluded from.
2258 *
2259 * @see ShortcutInfo.Builder#setExcludedFromSurfaces(int)
2260 */
2261 @Surface
2262 public int getExcludedFromSurfaces() {
2263 return mExcludedSurfaces;
2264 }
2265
2266 /**
2267 * Returns an immutable copy of the capability bindings using internal data structure.
2268 * @hide
2269 */
2270 @Nullable
2271 public Map<String, Map<String, List<String>>> getCapabilityBindingsInternal() {
2272 return cloneCapabilityBindings(mCapabilityBindings);
2273 }
2274
2275 @Nullable
2276 private static Map<String, Map<String, List<String>>> cloneCapabilityBindings(
2277 @Nullable final Map<String, Map<String, List<String>>> orig) {
2278 if (orig == null) {
2279 return null;
2280 }
2281 final Map<String, Map<String, List<String>>> ret = new ArrayMap<>();
2282 for (String capability : orig.keySet()) {
2283 final Map<String, List<String>> params = orig.get(capability);
2284 final Map<String, List<String>> clone;
2285 if (params == null) {
2286 clone = null;
2287 } else {
2288 clone = new ArrayMap<>(params.size());
2289 for (String paramName : params.keySet()) {
2290 final List<String> paramValues = params.get(paramName);
2291 clone.put(paramName, Collections.unmodifiableList(paramValues));
2292 }
2293 }
2294 ret.put(capability, Collections.unmodifiableMap(clone));
2295 }
2296 return Collections.unmodifiableMap(ret);
2297 }
2298
2299 /**
2300 * Return a list of {@link Capability} associated with the shortcut.
2301 */
2302 @NonNull
2303 public List<Capability> getCapabilities() {
2304 if (mCapabilityBindings == null) {
2305 return new ArrayList<>(0);
2306 }
2307 return mCapabilityBindings.keySet().stream().map(Capability::new)
2308 .collect(Collectors.toList());
2309 }
2310
2311 /**
2312 * Returns the {@link CapabilityParams} in associated with given capability.
2313 *
2314 * @param capability {@link Capability} associated with the shortcut.
2315 */
2316 @NonNull
2317 public List<CapabilityParams> getCapabilityParams(@NonNull final Capability capability) {
2318 Objects.requireNonNull(capability);
2319 if (mCapabilityBindings == null) {
2320 return new ArrayList<>(0);
2321 }
2322 final Map<String, List<String>> param = mCapabilityBindings.get(capability.getName());
2323 if (param == null) {
2324 return new ArrayList<>(0);
2325 }
2326 final List<CapabilityParams> ret = new ArrayList<>(param.size());
2327 for (String key : param.keySet()) {
2328 final List<String> values = param.get(key);
2329 final String primaryValue = values.get(0);
2330 final List<String> aliases = values.size() == 1
2331 ? Collections.emptyList() : values.subList(1, values.size());
2332 CapabilityParams.Builder builder = new CapabilityParams.Builder(key, primaryValue);
2333 for (String alias : aliases) {
2334 builder = builder.addAlias(alias);
2335 }
2336 ret.add(builder.build());
2337 }
2338 return ret;
2339 }
2340
2341 private ShortcutInfo(Parcel source) {
2342 final ClassLoader cl = getClass().getClassLoader();
2343
2344 mUserId = source.readInt();
2345 mId = source.readString8();
2346 mPackageName = source.readString8();
2347 mActivity = source.readParcelable(cl, android.content.ComponentName.class);
2348 mFlags = source.readInt();
2349 mIconResId = source.readInt();
2350 mLastChangedTimestamp = source.readLong();
2351 mDisabledReason = source.readInt();
2352
2353 if (source.readInt() == 0) {
2354 return; // key information only.
2355 }
2356
2357 mIcon = source.readParcelable(cl, android.graphics.drawable.Icon.class);
2358 mTitle = source.readCharSequence();
2359 mTitleResId = source.readInt();
2360 mText = source.readCharSequence();
2361 mTextResId = source.readInt();
2362 mDisabledMessage = source.readCharSequence();
2363 mDisabledMessageResId = source.readInt();
2364 mIntents = source.readParcelableArray(cl, Intent.class);
2365 mIntentPersistableExtrases = source.readParcelableArray(cl, PersistableBundle.class);
2366 mRank = source.readInt();
2367 mExtras = source.readParcelable(cl, android.os.PersistableBundle.class);
2368 mBitmapPath = source.readString8();
2369
2370 mIconResName = source.readString8();
2371 mTitleResName = source.readString8();
2372 mTextResName = source.readString8();
2373 mDisabledMessageResName = source.readString8();
2374
2375 int N = source.readInt();
2376 if (N == 0) {
2377 mCategories = null;
2378 } else {
2379 mCategories = new ArraySet<>(N);
2380 for (int i = 0; i < N; i++) {
2381 mCategories.add(source.readString8().intern());
2382 }
2383 }
2384
2385 mPersons = source.readParcelableArray(cl, Person.class);
2386 mLocusId = source.readParcelable(cl, android.content.LocusId.class);
2387 mIconUri = source.readString8();
2388 mStartingThemeResName = source.readString8();
2389 mExcludedSurfaces = source.readInt();
2390
2391 final Map<String, Map> rawCapabilityBindings = source.readHashMap(
2392 /*loader*/ null, /*clazzKey*/ String.class, /*clazzValue*/ HashMap.class);
2393 if (rawCapabilityBindings != null && !rawCapabilityBindings.isEmpty()) {
2394 final Map<String, Map<String, List<String>>> capabilityBindings =
2395 new ArrayMap<>(rawCapabilityBindings.size());
2396 rawCapabilityBindings.forEach(capabilityBindings::put);
2397 mCapabilityBindings = cloneCapabilityBindings(capabilityBindings);
2398 }
2399 }
2400
2401 @Override
2402 public void writeToParcel(Parcel dest, int flags) {
2403 dest.writeInt(mUserId);
2404 dest.writeString8(mId);
2405 dest.writeString8(mPackageName);
2406 dest.writeParcelable(mActivity, flags);
2407 dest.writeInt(mFlags);
2408 dest.writeInt(mIconResId);
2409 dest.writeLong(mLastChangedTimestamp);
2410 dest.writeInt(mDisabledReason);
2411
2412 if (hasKeyFieldsOnly()) {
2413 dest.writeInt(0);
2414 return;
2415 }
2416 dest.writeInt(1);
2417
2418 dest.writeParcelable(mIcon, flags);
2419 dest.writeCharSequence(mTitle);
2420 dest.writeInt(mTitleResId);
2421 dest.writeCharSequence(mText);
2422 dest.writeInt(mTextResId);
2423 dest.writeCharSequence(mDisabledMessage);
2424 dest.writeInt(mDisabledMessageResId);
2425
2426 dest.writeParcelableArray(mIntents, flags);
2427 dest.writeParcelableArray(mIntentPersistableExtrases, flags);
2428 dest.writeInt(mRank);
2429 dest.writeParcelable(mExtras, flags);
2430 dest.writeString8(mBitmapPath);
2431
2432 dest.writeString8(mIconResName);
2433 dest.writeString8(mTitleResName);
2434 dest.writeString8(mTextResName);
2435 dest.writeString8(mDisabledMessageResName);
2436
2437 if (mCategories != null) {
2438 final int N = mCategories.size();
2439 dest.writeInt(N);
2440 for (int i = 0; i < N; i++) {
2441 dest.writeString8(mCategories.valueAt(i));
2442 }
2443 } else {
2444 dest.writeInt(0);
2445 }
2446
2447 dest.writeParcelableArray(mPersons, flags);
2448 dest.writeParcelable(mLocusId, flags);
2449 dest.writeString8(mIconUri);
2450 dest.writeString8(mStartingThemeResName);
2451 dest.writeInt(mExcludedSurfaces);
2452 dest.writeMap(mCapabilityBindings);
2453 }
2454
2455 public static final @NonNull Creator<ShortcutInfo> CREATOR =
2456 new Creator<ShortcutInfo>() {
2457 public ShortcutInfo createFromParcel(Parcel source) {
2458 return new ShortcutInfo(source);
2459 }
2460 public ShortcutInfo[] newArray(int size) {
2461 return new ShortcutInfo[size];
2462 }
2463 };
2464
2465 @Override
2466 public int describeContents() {
2467 return 0;
2468 }
2469
2470
2471 /**
2472 * Return a string representation, intended for logging. Some fields will be retracted.
2473 */
2474 @Override
2475 public String toString() {
2476 return toStringInner(/* secure =*/ true, /* includeInternalData =*/ false,
2477 /*indent=*/ null);
2478 }
2479
2480 /** @hide */
2481 public String toInsecureString() {
2482 return toStringInner(/* secure =*/ false, /* includeInternalData =*/ true,
2483 /*indent=*/ null);
2484 }
2485
2486 /** @hide */
2487 public String toDumpString(String indent) {
2488 return toStringInner(/* secure =*/ false, /* includeInternalData =*/ true, indent);
2489 }
2490
2491 private void addIndentOrComma(StringBuilder sb, String indent) {
2492 if (indent != null) {
2493 sb.append("\n ");
2494 sb.append(indent);
2495 } else {
2496 sb.append(", ");
2497 }
2498 }
2499
2500 private String toStringInner(boolean secure, boolean includeInternalData, String indent) {
2501 final StringBuilder sb = new StringBuilder();
2502
2503 if (indent != null) {
2504 sb.append(indent);
2505 }
2506
2507 sb.append("ShortcutInfo {");
2508
2509 sb.append("id=");
2510 sb.append(secure ? "***" : mId);
2511
2512 sb.append(", flags=0x");
2513 sb.append(Integer.toHexString(mFlags));
2514 sb.append(" [");
2515 if ((mFlags & FLAG_SHADOW) != 0) {
2516 // Note the shadow flag isn't actually used anywhere and it's just for dumpsys, so
2517 // we don't have an isXxx for this.
2518 sb.append("Sdw");
2519 }
2520 if (!isEnabled()) {
2521 sb.append("Dis");
2522 }
2523 if (isImmutable()) {
2524 sb.append("Im");
2525 }
2526 if (isManifestShortcut()) {
2527 sb.append("Man");
2528 }
2529 if (isDynamic()) {
2530 sb.append("Dyn");
2531 }
2532 if (isPinned()) {
2533 sb.append("Pin");
2534 }
2535 if (hasIconFile()) {
2536 sb.append("Ic-f");
2537 }
2538 if (isIconPendingSave()) {
2539 sb.append("Pens");
2540 }
2541 if (hasIconResource()) {
2542 sb.append("Ic-r");
2543 }
2544 if (hasIconUri()) {
2545 sb.append("Ic-u");
2546 }
2547 if (hasAdaptiveBitmap()) {
2548 sb.append("Ic-a");
2549 }
2550 if (hasKeyFieldsOnly()) {
2551 sb.append("Key");
2552 }
2553 if (hasStringResourcesResolved()) {
2554 sb.append("Str");
2555 }
2556 if (isReturnedByServer()) {
2557 sb.append("Rets");
2558 }
2559 if (isLongLived()) {
2560 sb.append("Liv");
2561 }
2562 if (isExcludedFromSurfaces(SURFACE_LAUNCHER)) {
2563 sb.append("Hid-L");
2564 }
2565 sb.append("]");
2566
2567 addIndentOrComma(sb, indent);
2568
2569 sb.append("packageName=");
2570 sb.append(mPackageName);
2571
2572 addIndentOrComma(sb, indent);
2573
2574 sb.append("activity=");
2575 sb.append(mActivity);
2576
2577 addIndentOrComma(sb, indent);
2578
2579 sb.append("shortLabel=");
2580 sb.append(secure ? "***" : mTitle);
2581 sb.append(", resId=");
2582 sb.append(mTitleResId);
2583 sb.append("[");
2584 sb.append(mTitleResName);
2585 sb.append("]");
2586
2587 addIndentOrComma(sb, indent);
2588
2589 sb.append("longLabel=");
2590 sb.append(secure ? "***" : mText);
2591 sb.append(", resId=");
2592 sb.append(mTextResId);
2593 sb.append("[");
2594 sb.append(mTextResName);
2595 sb.append("]");
2596
2597 addIndentOrComma(sb, indent);
2598
2599 sb.append("disabledMessage=");
2600 sb.append(secure ? "***" : mDisabledMessage);
2601 sb.append(", resId=");
2602 sb.append(mDisabledMessageResId);
2603 sb.append("[");
2604 sb.append(mDisabledMessageResName);
2605 sb.append("]");
2606
2607 addIndentOrComma(sb, indent);
2608
2609 sb.append("disabledReason=");
2610 sb.append(getDisabledReasonDebugString(mDisabledReason));
2611
2612 if (mStartingThemeResName != null && !mStartingThemeResName.isEmpty()) {
2613 addIndentOrComma(sb, indent);
2614 sb.append("SplashScreenThemeResName=");
2615 sb.append(mStartingThemeResName);
2616 }
2617
2618 addIndentOrComma(sb, indent);
2619
2620 sb.append("categories=");
2621 sb.append(mCategories);
2622
2623 addIndentOrComma(sb, indent);
2624
2625 sb.append("persons=");
2626 sb.append(Arrays.toString(mPersons));
2627
2628 addIndentOrComma(sb, indent);
2629
2630 sb.append("icon=");
2631 sb.append(mIcon);
2632
2633 addIndentOrComma(sb, indent);
2634
2635 sb.append("rank=");
2636 sb.append(mRank);
2637
2638 sb.append(", timestamp=");
2639 sb.append(mLastChangedTimestamp);
2640
2641 addIndentOrComma(sb, indent);
2642
2643 sb.append("intents=");
2644 if (mIntents == null) {
2645 sb.append("null");
2646 } else {
2647 if (secure) {
2648 sb.append("size:");
2649 sb.append(mIntents.length);
2650 } else {
2651 final int size = mIntents.length;
2652 sb.append("[");
2653 String sep = "";
2654 for (int i = 0; i < size; i++) {
2655 sb.append(sep);
2656 sep = ", ";
2657 sb.append(mIntents[i]);
2658 sb.append("/");
2659 sb.append(mIntentPersistableExtrases[i]);
2660 }
2661 sb.append("]");
2662 }
2663 }
2664
2665 addIndentOrComma(sb, indent);
2666
2667 sb.append("extras=");
2668 sb.append(mExtras);
2669
2670 if (includeInternalData) {
2671 addIndentOrComma(sb, indent);
2672
2673 sb.append("iconRes=");
2674 sb.append(mIconResId);
2675 sb.append("[");
2676 sb.append(mIconResName);
2677 sb.append("]");
2678
2679 sb.append(", bitmapPath=");
2680 sb.append(mBitmapPath);
2681
2682 sb.append(", iconUri=");
2683 sb.append(mIconUri);
2684 }
2685
2686 if (mLocusId != null) {
2687 sb.append("locusId="); sb.append(mLocusId); // LocusId.toString() is PII-safe.
2688 }
2689
2690 sb.append("}");
2691 return sb.toString();
2692 }
2693
2694 /** @hide */
2695 public ShortcutInfo(
2696 @UserIdInt int userId, String id, String packageName, ComponentName activity,
2697 Icon icon, CharSequence title, int titleResId, String titleResName,
2698 CharSequence text, int textResId, String textResName,
2699 CharSequence disabledMessage, int disabledMessageResId, String disabledMessageResName,
2700 Set<String> categories, Intent[] intentsWithExtras, int rank, PersistableBundle extras,
2701 long lastChangedTimestamp,
2702 int flags, int iconResId, String iconResName, String bitmapPath, String iconUri,
2703 int disabledReason, Person[] persons, LocusId locusId,
2704 @Nullable String startingThemeResName,
2705 @Nullable Map<String, Map<String, List<String>>> capabilityBindings) {
2706 mUserId = userId;
2707 mId = id;
2708 mPackageName = packageName;
2709 mActivity = activity;
2710 mIcon = icon;
2711 mTitle = title;
2712 mTitleResId = titleResId;
2713 mTitleResName = titleResName;
2714 mText = text;
2715 mTextResId = textResId;
2716 mTextResName = textResName;
2717 mDisabledMessage = disabledMessage;
2718 mDisabledMessageResId = disabledMessageResId;
2719 mDisabledMessageResName = disabledMessageResName;
2720 mCategories = cloneCategories(categories);
2721 mIntents = cloneIntents(intentsWithExtras);
2722 fixUpIntentExtras();
2723 mRank = rank;
2724 mExtras = extras;
2725 mLastChangedTimestamp = lastChangedTimestamp;
2726 mFlags = flags;
2727 mIconResId = iconResId;
2728 mIconResName = iconResName;
2729 mBitmapPath = bitmapPath;
2730 mIconUri = iconUri;
2731 mDisabledReason = disabledReason;
2732 mPersons = persons;
2733 mLocusId = locusId;
2734 mStartingThemeResName = startingThemeResName;
2735 mCapabilityBindings = cloneCapabilityBindings(capabilityBindings);
2736 }
2737 }