Debian Codegraph @

core/java/android/widget/RemoteViews.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2007 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
17 package android.widget;
18
19 import android.annotation.AttrRes;
20 import android.annotation.ColorInt;
21 import android.annotation.ColorRes;
22 import android.annotation.DimenRes;
23 import android.annotation.DrawableRes;
24 import android.annotation.IdRes;
25 import android.annotation.IntDef;
26 import android.annotation.LayoutRes;
27 import android.annotation.NonNull;
28 import android.annotation.Nullable;
29 import android.annotation.Px;
30 import android.annotation.StringRes;
31 import android.annotation.StyleRes;
32 import android.annotation.SuppressLint;
33 import android.app.Activity;
34 import android.app.ActivityOptions;
35 import android.app.ActivityThread;
36 import android.app.Application;
37 import android.app.LoadedApk;
38 import android.app.PendingIntent;
39 import android.app.RemoteInput;
40 import android.appwidget.AppWidgetHostView;
41 import android.compat.annotation.UnsupportedAppUsage;
42 import android.content.Context;
43 import android.content.ContextWrapper;
44 import android.content.Intent;
45 import android.content.IntentSender;
46 import android.content.pm.ApplicationInfo;
47 import android.content.pm.PackageManager.NameNotFoundException;
48 import android.content.res.ColorStateList;
49 import android.content.res.Configuration;
50 import android.content.res.Resources;
51 import android.content.res.TypedArray;
52 import android.content.res.loader.ResourcesLoader;
53 import android.content.res.loader.ResourcesProvider;
54 import android.graphics.Bitmap;
55 import android.graphics.BlendMode;
56 import android.graphics.Outline;
57 import android.graphics.PorterDuff;
58 import android.graphics.Rect;
59 import android.graphics.drawable.Drawable;
60 import android.graphics.drawable.Icon;
61 import android.graphics.drawable.RippleDrawable;
62 import android.net.Uri;
63 import android.os.AsyncTask;
64 import android.os.Binder;
65 import android.os.Build;
66 import android.os.Bundle;
67 import android.os.CancellationSignal;
68 import android.os.Parcel;
69 import android.os.ParcelFileDescriptor;
70 import android.os.Parcelable;
71 import android.os.Process;
72 import android.os.StrictMode;
73 import android.os.UserHandle;
74 import android.system.Os;
75 import android.text.TextUtils;
76 import android.util.ArrayMap;
77 import android.util.DisplayMetrics;
78 import android.util.IntArray;
79 import android.util.Log;
80 import android.util.LongArray;
81 import android.util.Pair;
82 import android.util.SizeF;
83 import android.util.SparseIntArray;
84 import android.util.TypedValue;
85 import android.util.TypedValue.ComplexDimensionUnit;
86 import android.view.ContextThemeWrapper;
87 import android.view.LayoutInflater;
88 import android.view.LayoutInflater.Filter;
89 import android.view.RemotableViewMethod;
90 import android.view.View;
91 import android.view.ViewGroup;
92 import android.view.ViewGroup.MarginLayoutParams;
93 import android.view.ViewManager;
94 import android.view.ViewOutlineProvider;
95 import android.view.ViewParent;
96 import android.view.ViewStub;
97 import android.widget.AdapterView.OnItemClickListener;
98 import android.widget.CompoundButton.OnCheckedChangeListener;
99
100 import com.android.internal.R;
101 import com.android.internal.util.ContrastColorUtil;
102 import com.android.internal.util.Preconditions;
103
104 import java.io.ByteArrayOutputStream;
105 import java.io.FileDescriptor;
106 import java.io.FileOutputStream;
107 import java.io.IOException;
108 import java.io.InputStream;
109 import java.io.OutputStream;
110 import java.lang.annotation.ElementType;
111 import java.lang.annotation.Retention;
112 import java.lang.annotation.RetentionPolicy;
113 import java.lang.annotation.Target;
114 import java.lang.invoke.MethodHandle;
115 import java.lang.invoke.MethodHandles;
116 import java.lang.invoke.MethodType;
117 import java.lang.reflect.Method;
118 import java.util.ArrayDeque;
119 import java.util.ArrayList;
120 import java.util.Arrays;
121 import java.util.HashMap;
122 import java.util.Iterator;
123 import java.util.List;
124 import java.util.Map;
125 import java.util.Objects;
126 import java.util.Stack;
127 import java.util.concurrent.Executor;
128 import java.util.function.Consumer;
129 import java.util.function.Predicate;
130
131 /**
132 * A class that describes a view hierarchy that can be displayed in
133 * another process. The hierarchy is inflated from a layout resource
134 * file, and this class provides some basic operations for modifying
135 * the content of the inflated hierarchy.
136 *
137 * <p>{@code RemoteViews} is limited to support for the following layouts:</p>
138 * <ul>
139 * <li>{@link android.widget.AdapterViewFlipper}</li>
140 * <li>{@link android.widget.FrameLayout}</li>
141 * <li>{@link android.widget.GridLayout}</li>
142 * <li>{@link android.widget.GridView}</li>
143 * <li>{@link android.widget.LinearLayout}</li>
144 * <li>{@link android.widget.ListView}</li>
145 * <li>{@link android.widget.RelativeLayout}</li>
146 * <li>{@link android.widget.StackView}</li>
147 * <li>{@link android.widget.ViewFlipper}</li>
148 * </ul>
149 * <p>And the following widgets:</p>
150 * <ul>
151 * <li>{@link android.widget.AnalogClock}</li>
152 * <li>{@link android.widget.Button}</li>
153 * <li>{@link android.widget.Chronometer}</li>
154 * <li>{@link android.widget.ImageButton}</li>
155 * <li>{@link android.widget.ImageView}</li>
156 * <li>{@link android.widget.ProgressBar}</li>
157 * <li>{@link android.widget.TextClock}</li>
158 * <li>{@link android.widget.TextView}</li>
159 * </ul>
160 * <p>As of API 31, the following widgets and layouts may also be used:</p>
161 * <ul>
162 * <li>{@link android.widget.CheckBox}</li>
163 * <li>{@link android.widget.RadioButton}</li>
164 * <li>{@link android.widget.RadioGroup}</li>
165 * <li>{@link android.widget.Switch}</li>
166 * </ul>
167 * <p>Descendants of these classes are not supported.</p>
168 */
169 public class RemoteViews implements Parcelable, Filter {
170
171 private static final String LOG_TAG = "RemoteViews";
172
173 /** The intent extra for whether the view whose checked state changed is currently checked. */
174 public static final String EXTRA_CHECKED = "android.widget.extra.CHECKED";
175
176 /**
177 * The intent extra that contains the appWidgetId.
178 * @hide
179 */
180 static final String EXTRA_REMOTEADAPTER_APPWIDGET_ID = "remoteAdapterAppWidgetId";
181
182 /**
183 * The intent extra that contains {@code true} if inflating as dak text theme.
184 * @hide
185 */
186 static final String EXTRA_REMOTEADAPTER_ON_LIGHT_BACKGROUND = "remoteAdapterOnLightBackground";
187
188 /**
189 * The intent extra that contains the bounds for all shared elements.
190 */
191 public static final String EXTRA_SHARED_ELEMENT_BOUNDS =
192 "android.widget.extra.SHARED_ELEMENT_BOUNDS";
193
194 /**
195 * Maximum depth of nested views calls from {@link #addView(int, RemoteViews)} and
196 * {@link #RemoteViews(RemoteViews, RemoteViews)}.
197 */
198 private static final int MAX_NESTED_VIEWS = 10;
199
200 /**
201 * Maximum number of RemoteViews that can be specified in constructor.
202 */
203 private static final int MAX_INIT_VIEW_COUNT = 16;
204
205 // The unique identifiers for each custom {@link Action}.
206 private static final int SET_ON_CLICK_RESPONSE_TAG = 1;
207 private static final int REFLECTION_ACTION_TAG = 2;
208 private static final int SET_DRAWABLE_TINT_TAG = 3;
209 private static final int VIEW_GROUP_ACTION_ADD_TAG = 4;
210 private static final int VIEW_CONTENT_NAVIGATION_TAG = 5;
211 private static final int SET_EMPTY_VIEW_ACTION_TAG = 6;
212 private static final int VIEW_GROUP_ACTION_REMOVE_TAG = 7;
213 private static final int SET_PENDING_INTENT_TEMPLATE_TAG = 8;
214 private static final int SET_REMOTE_VIEW_ADAPTER_INTENT_TAG = 10;
215 private static final int TEXT_VIEW_DRAWABLE_ACTION_TAG = 11;
216 private static final int BITMAP_REFLECTION_ACTION_TAG = 12;
217 private static final int TEXT_VIEW_SIZE_ACTION_TAG = 13;
218 private static final int VIEW_PADDING_ACTION_TAG = 14;
219 private static final int SET_REMOTE_VIEW_ADAPTER_LIST_TAG = 15;
220 private static final int SET_REMOTE_INPUTS_ACTION_TAG = 18;
221 private static final int LAYOUT_PARAM_ACTION_TAG = 19;
222 private static final int OVERRIDE_TEXT_COLORS_TAG = 20;
223 private static final int SET_RIPPLE_DRAWABLE_COLOR_TAG = 21;
224 private static final int SET_INT_TAG_TAG = 22;
225 private static final int REMOVE_FROM_PARENT_ACTION_TAG = 23;
226 private static final int RESOURCE_REFLECTION_ACTION_TAG = 24;
227 private static final int COMPLEX_UNIT_DIMENSION_REFLECTION_ACTION_TAG = 25;
228 private static final int SET_COMPOUND_BUTTON_CHECKED_TAG = 26;
229 private static final int SET_RADIO_GROUP_CHECKED = 27;
230 private static final int SET_VIEW_OUTLINE_RADIUS_TAG = 28;
231 private static final int SET_ON_CHECKED_CHANGE_RESPONSE_TAG = 29;
232 private static final int NIGHT_MODE_REFLECTION_ACTION_TAG = 30;
233 private static final int SET_REMOTE_COLLECTION_ITEMS_ADAPTER_TAG = 31;
234 private static final int ATTRIBUTE_REFLECTION_ACTION_TAG = 32;
235
236 /** @hide **/
237 @IntDef(prefix = "MARGIN_", value = {
238 MARGIN_LEFT,
239 MARGIN_TOP,
240 MARGIN_RIGHT,
241 MARGIN_BOTTOM,
242 MARGIN_START,
243 MARGIN_END
244 })
245 @Retention(RetentionPolicy.SOURCE)
246 public @interface MarginType {}
247 /** The value will apply to the marginLeft. */
248 public static final int MARGIN_LEFT = 0;
249 /** The value will apply to the marginTop. */
250 public static final int MARGIN_TOP = 1;
251 /** The value will apply to the marginRight. */
252 public static final int MARGIN_RIGHT = 2;
253 /** The value will apply to the marginBottom. */
254 public static final int MARGIN_BOTTOM = 3;
255 /** The value will apply to the marginStart. */
256 public static final int MARGIN_START = 4;
257 /** The value will apply to the marginEnd. */
258 public static final int MARGIN_END = 5;
259
260 @IntDef(prefix = "VALUE_TYPE_", value = {
261 VALUE_TYPE_RAW,
262 VALUE_TYPE_COMPLEX_UNIT,
263 VALUE_TYPE_RESOURCE,
264 VALUE_TYPE_ATTRIBUTE
265 })
266 @Retention(RetentionPolicy.SOURCE)
267 @interface ValueType {}
268 static final int VALUE_TYPE_RAW = 1;
269 static final int VALUE_TYPE_COMPLEX_UNIT = 2;
270 static final int VALUE_TYPE_RESOURCE = 3;
271 static final int VALUE_TYPE_ATTRIBUTE = 4;
272
273 /** @hide **/
274 @IntDef(flag = true, value = {
275 FLAG_REAPPLY_DISALLOWED,
276 FLAG_WIDGET_IS_COLLECTION_CHILD,
277 FLAG_USE_LIGHT_BACKGROUND_LAYOUT
278 })
279 @Retention(RetentionPolicy.SOURCE)
280 public @interface ApplyFlags {}
281 /**
282 * Whether reapply is disallowed on this remoteview. This maybe be true if some actions modify
283 * the layout in a way that isn't recoverable, since views are being removed.
284 * @hide
285 */
286 public static final int FLAG_REAPPLY_DISALLOWED = 1;
287 /**
288 * This flag indicates whether this RemoteViews object is being created from a
289 * RemoteViewsService for use as a child of a widget collection. This flag is used
290 * to determine whether or not certain features are available, in particular,
291 * setting on click extras and setting on click pending intents. The former is enabled,
292 * and the latter disabled when this flag is true.
293 * @hide
294 */
295 public static final int FLAG_WIDGET_IS_COLLECTION_CHILD = 2;
296 /**
297 * When this flag is set, the views is inflated with {@link #mLightBackgroundLayoutId} instead
298 * of {link #mLayoutId}
299 * @hide
300 */
301 public static final int FLAG_USE_LIGHT_BACKGROUND_LAYOUT = 4;
302
303 /**
304 * This mask determines which flags are propagated to nested RemoteViews (either added by
305 * addView, or set as portrait/landscape/sized RemoteViews).
306 */
307 static final int FLAG_MASK_TO_PROPAGATE =
308 FLAG_WIDGET_IS_COLLECTION_CHILD | FLAG_USE_LIGHT_BACKGROUND_LAYOUT;
309
310 /**
311 * A ReadWriteHelper which has the same behavior as ReadWriteHelper.DEFAULT, but which is
312 * intentionally a different instance in order to trick Bundle reader so that it doesn't allow
313 * lazy initialization.
314 */
315 private static final Parcel.ReadWriteHelper ALTERNATIVE_DEFAULT = new Parcel.ReadWriteHelper();
316
317 /**
318 * Used to restrict the views which can be inflated
319 *
320 * @see android.view.LayoutInflater.Filter#onLoadClass(java.lang.Class)
321 */
322 private static final LayoutInflater.Filter INFLATER_FILTER =
323 (clazz) -> clazz.isAnnotationPresent(RemoteViews.RemoteView.class);
324
325 /**
326 * Application that hosts the remote views.
327 *
328 * @hide
329 */
330 @UnsupportedAppUsage
331 public ApplicationInfo mApplication;
332
333 /**
334 * The resource ID of the layout file. (Added to the parcel)
335 */
336 @UnsupportedAppUsage
337 private int mLayoutId;
338
339 /**
340 * The resource ID of the layout file in dark text mode. (Added to the parcel)
341 */
342 private int mLightBackgroundLayoutId = 0;
343
344 /**
345 * An array of actions to perform on the view tree once it has been
346 * inflated
347 */
348 @UnsupportedAppUsage
349 private ArrayList<Action> mActions;
350
351 /**
352 * Maps bitmaps to unique indicies to avoid Bitmap duplication.
353 */
354 @UnsupportedAppUsage
355 private BitmapCache mBitmapCache = new BitmapCache();
356
357 /** Cache of ApplicationInfos used by collection items. */
358 private ApplicationInfoCache mApplicationInfoCache = new ApplicationInfoCache();
359
360 /**
361 * Indicates whether or not this RemoteViews object is contained as a child of any other
362 * RemoteViews.
363 */
364 private boolean mIsRoot = true;
365
366 /**
367 * Constants to whether or not this RemoteViews is composed of a landscape and portrait
368 * RemoteViews.
369 */
370 private static final int MODE_NORMAL = 0;
371 private static final int MODE_HAS_LANDSCAPE_AND_PORTRAIT = 1;
372 private static final int MODE_HAS_SIZED_REMOTEVIEWS = 2;
373
374 /**
375 * Used in conjunction with the special constructor
376 * {@link #RemoteViews(RemoteViews, RemoteViews)} to keep track of the landscape and portrait
377 * RemoteViews.
378 */
379 private RemoteViews mLandscape = null;
380 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
381 private RemoteViews mPortrait = null;
382 /**
383 * List of RemoteViews with their ideal size. There must be at least two if the map is not null.
384 *
385 * The smallest remote view is always the last element in the list.
386 */
387 private List<RemoteViews> mSizedRemoteViews = null;
388
389 /**
390 * Ideal size for this RemoteViews.
391 *
392 * Only to be used on children views used in a {@link RemoteViews} with
393 * {@link RemoteViews#hasSizedRemoteViews()}.
394 */
395 private SizeF mIdealSize = null;
396
397 @ApplyFlags
398 private int mApplyFlags = 0;
399
400 /**
401 * Id to use to override the ID of the top-level view in this RemoteViews.
402 *
403 * Only used if this RemoteViews is defined from a XML layout value.
404 */
405 private int mViewId = View.NO_ID;
406
407 /**
408 * Id used to uniquely identify a {@link RemoteViews} instance coming from a given provider.
409 */
410 private long mProviderInstanceId = -1;
411
412 /** Class cookies of the Parcel this instance was read from. */
413 private Map<Class, Object> mClassCookies;
414
415 private static final InteractionHandler DEFAULT_INTERACTION_HANDLER =
416 (view, pendingIntent, response) ->
417 startPendingIntent(view, pendingIntent, response.getLaunchOptions(view));
418
419 private static final ArrayMap<MethodKey, MethodArgs> sMethods = new ArrayMap<>();
420
421 /**
422 * This key is used to perform lookups in sMethods without causing allocations.
423 */
424 private static final MethodKey sLookupKey = new MethodKey();
425
426 /**
427 * @hide
428 */
429 public void setRemoteInputs(@IdRes int viewId, RemoteInput[] remoteInputs) {
430 mActions.add(new SetRemoteInputsAction(viewId, remoteInputs));
431 }
432
433 /**
434 * Reduces all images and ensures that they are all below the given sizes.
435 *
436 * @param maxWidth the maximum width allowed
437 * @param maxHeight the maximum height allowed
438 *
439 * @hide
440 */
441 public void reduceImageSizes(int maxWidth, int maxHeight) {
442 ArrayList<Bitmap> cache = mBitmapCache.mBitmaps;
443 for (int i = 0; i < cache.size(); i++) {
444 Bitmap bitmap = cache.get(i);
445 cache.set(i, Icon.scaleDownIfNecessary(bitmap, maxWidth, maxHeight));
446 }
447 }
448
449 /**
450 * Override all text colors in this layout and replace them by the given text color.
451 *
452 * @param textColor The color to use.
453 *
454 * @hide
455 */
456 public void overrideTextColors(int textColor) {
457 addAction(new OverrideTextColorsAction(textColor));
458 }
459
460 /**
461 * Sets an integer tag to the view.
462 *
463 * @hide
464 */
465 public void setIntTag(@IdRes int viewId, @IdRes int key, int tag) {
466 addAction(new SetIntTagAction(viewId, key, tag));
467 }
468
469 /**
470 * Set that it is disallowed to reapply another remoteview with the same layout as this view.
471 * This should be done if an action is destroying the view tree of the base layout.
472 *
473 * @hide
474 */
475 public void addFlags(@ApplyFlags int flags) {
476 mApplyFlags = mApplyFlags | flags;
477
478 int flagsToPropagate = flags & FLAG_MASK_TO_PROPAGATE;
479 if (flagsToPropagate != 0) {
480 if (hasSizedRemoteViews()) {
481 for (RemoteViews remoteView : mSizedRemoteViews) {
482 remoteView.addFlags(flagsToPropagate);
483 }
484 } else if (hasLandscapeAndPortraitLayouts()) {
485 mLandscape.addFlags(flagsToPropagate);
486 mPortrait.addFlags(flagsToPropagate);
487 }
488 }
489 }
490
491 /**
492 * @hide
493 */
494 public boolean hasFlags(@ApplyFlags int flag) {
495 return (mApplyFlags & flag) == flag;
496 }
497
498 /**
499 * Stores information related to reflection method lookup.
500 */
501 static class MethodKey {
502 public Class targetClass;
503 public Class paramClass;
504 public String methodName;
505
506 @Override
507 public boolean equals(@Nullable Object o) {
508 if (!(o instanceof MethodKey)) {
509 return false;
510 }
511 MethodKey p = (MethodKey) o;
512 return Objects.equals(p.targetClass, targetClass)
513 && Objects.equals(p.paramClass, paramClass)
514 && Objects.equals(p.methodName, methodName);
515 }
516
517 @Override
518 public int hashCode() {
519 return Objects.hashCode(targetClass) ^ Objects.hashCode(paramClass)
520 ^ Objects.hashCode(methodName);
521 }
522
523 public void set(Class targetClass, Class paramClass, String methodName) {
524 this.targetClass = targetClass;
525 this.paramClass = paramClass;
526 this.methodName = methodName;
527 }
528 }
529
530
531 /**
532 * Stores information related to reflection method lookup result.
533 */
534 static class MethodArgs {
535 public MethodHandle syncMethod;
536 public MethodHandle asyncMethod;
537 public String asyncMethodName;
538 }
539
540 /**
541 * This annotation indicates that a subclass of View is allowed to be used
542 * with the {@link RemoteViews} mechanism.
543 */
544 @Target({ ElementType.TYPE })
545 @Retention(RetentionPolicy.RUNTIME)
546 public @interface RemoteView {
547 }
548
549 /**
550 * Exception to send when something goes wrong executing an action
551 *
552 */
553 public static class ActionException extends RuntimeException {
554 public ActionException(Exception ex) {
555 super(ex);
556 }
557 public ActionException(String message) {
558 super(message);
559 }
560 /**
561 * @hide
562 */
563 public ActionException(Throwable t) {
564 super(t);
565 }
566 }
567
568 /**
569 * Handler for view interactions (such as clicks) within a RemoteViews.
570 *
571 * @hide
572 */
573 public interface InteractionHandler {
574 /**
575 * Invoked when the user performs an interaction on the View.
576 *
577 * @param view the View with which the user interacted
578 * @param pendingIntent the base PendingIntent associated with the view
579 * @param response the response to the interaction, which knows how to fill in the
580 * attached PendingIntent
581 *
582 * @hide
583 */
584 boolean onInteraction(
585 View view,
586 PendingIntent pendingIntent,
587 RemoteResponse response);
588 }
589
590 /**
591 * Base class for all actions that can be performed on an
592 * inflated view.
593 *
594 * SUBCLASSES MUST BE IMMUTABLE SO CLONE WORKS!!!!!
595 */
596 private abstract static class Action implements Parcelable {
597 public abstract void apply(View root, ViewGroup rootParent, ActionApplyParams params)
598 throws ActionException;
599
600 public static final int MERGE_REPLACE = 0;
601 public static final int MERGE_APPEND = 1;
602 public static final int MERGE_IGNORE = 2;
603
604 public int describeContents() {
605 return 0;
606 }
607
608 public void setHierarchyRootData(HierarchyRootData root) {
609 // Do nothing
610 }
611
612 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
613 public int mergeBehavior() {
614 return MERGE_REPLACE;
615 }
616
617 public abstract int getActionTag();
618
619 public String getUniqueKey() {
620 return (getActionTag() + "_" + viewId);
621 }
622
623 /**
624 * This is called on the background thread. It should perform any non-ui computations
625 * and return the final action which will run on the UI thread.
626 * Override this if some of the tasks can be performed async.
627 */
628 public Action initActionAsync(ViewTree root, ViewGroup rootParent,
629 ActionApplyParams params) {
630 return this;
631 }
632
633 public boolean prefersAsyncApply() {
634 return false;
635 }
636
637 public void visitUris(@NonNull Consumer<Uri> visitor) {
638 // Nothing to visit by default
639 }
640
641 @IdRes
642 @UnsupportedAppUsage
643 int viewId;
644 }
645
646 /**
647 * Action class used during async inflation of RemoteViews. Subclasses are not parcelable.
648 */
649 private static abstract class RuntimeAction extends Action {
650 @Override
651 public final int getActionTag() {
652 return 0;
653 }
654
655 @Override
656 public final void writeToParcel(Parcel dest, int flags) {
657 throw new UnsupportedOperationException();
658 }
659 }
660
661 // Constant used during async execution. It is not parcelable.
662 private static final Action ACTION_NOOP = new RuntimeAction() {
663 @Override
664 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) { }
665 };
666
667 /**
668 * Merges the passed RemoteViews actions with this RemoteViews actions according to
669 * action-specific merge rules.
670 *
671 * @param newRv
672 *
673 * @hide
674 */
675 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
676 public void mergeRemoteViews(RemoteViews newRv) {
677 if (newRv == null) return;
678 // We first copy the new RemoteViews, as the process of merging modifies the way the actions
679 // reference the bitmap cache. We don't want to modify the object as it may need to
680 // be merged and applied multiple times.
681 RemoteViews copy = new RemoteViews(newRv);
682
683 HashMap<String, Action> map = new HashMap<String, Action>();
684 if (mActions == null) {
685 mActions = new ArrayList<Action>();
686 }
687
688 int count = mActions.size();
689 for (int i = 0; i < count; i++) {
690 Action a = mActions.get(i);
691 map.put(a.getUniqueKey(), a);
692 }
693
694 ArrayList<Action> newActions = copy.mActions;
695 if (newActions == null) return;
696 count = newActions.size();
697 for (int i = 0; i < count; i++) {
698 Action a = newActions.get(i);
699 String key = newActions.get(i).getUniqueKey();
700 int mergeBehavior = newActions.get(i).mergeBehavior();
701 if (map.containsKey(key) && mergeBehavior == Action.MERGE_REPLACE) {
702 mActions.remove(map.get(key));
703 map.remove(key);
704 }
705
706 // If the merge behavior is ignore, we don't bother keeping the extra action
707 if (mergeBehavior == Action.MERGE_REPLACE || mergeBehavior == Action.MERGE_APPEND) {
708 mActions.add(a);
709 }
710 }
711
712 // Because pruning can remove the need for bitmaps, we reconstruct the caches.
713 reconstructCaches();
714 }
715
716 /**
717 * Note all {@link Uri} that are referenced internally, with the expectation
718 * that Uri permission grants will need to be issued to ensure the recipient
719 * of this object is able to render its contents.
720 *
721 * @hide
722 */
723 public void visitUris(@NonNull Consumer<Uri> visitor) {
724 if (mActions != null) {
725 for (int i = 0; i < mActions.size(); i++) {
726 mActions.get(i).visitUris(visitor);
727 }
728 }
729 }
730
731 private static void visitIconUri(Icon icon, @NonNull Consumer<Uri> visitor) {
732 if (icon != null && (icon.getType() == Icon.TYPE_URI
733 || icon.getType() == Icon.TYPE_URI_ADAPTIVE_BITMAP)) {
734 visitor.accept(icon.getUri());
735 }
736 }
737
738 private static class RemoteViewsContextWrapper extends ContextWrapper {
739 private final Context mContextForResources;
740
741 RemoteViewsContextWrapper(Context context, Context contextForResources) {
742 super(context);
743 mContextForResources = contextForResources;
744 }
745
746 @Override
747 public Resources getResources() {
748 return mContextForResources.getResources();
749 }
750
751 @Override
752 public Resources.Theme getTheme() {
753 return mContextForResources.getTheme();
754 }
755
756 @Override
757 public String getPackageName() {
758 return mContextForResources.getPackageName();
759 }
760
761 @Override
762 public UserHandle getUser() {
763 return mContextForResources.getUser();
764 }
765
766 @Override
767 public int getUserId() {
768 return mContextForResources.getUserId();
769 }
770
771 @Override
772 public boolean isRestricted() {
773 // Override isRestricted and direct to resource's implementation. The isRestricted is
774 // used for determining the risky resources loading, e.g. fonts, thus direct to context
775 // for resource.
776 return mContextForResources.isRestricted();
777 }
778 }
779
780 private class SetEmptyView extends Action {
781 int emptyViewId;
782
783 SetEmptyView(@IdRes int viewId, @IdRes int emptyViewId) {
784 this.viewId = viewId;
785 this.emptyViewId = emptyViewId;
786 }
787
788 SetEmptyView(Parcel in) {
789 this.viewId = in.readInt();
790 this.emptyViewId = in.readInt();
791 }
792
793 public void writeToParcel(Parcel out, int flags) {
794 out.writeInt(this.viewId);
795 out.writeInt(this.emptyViewId);
796 }
797
798 @Override
799 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
800 final View view = root.findViewById(viewId);
801 if (!(view instanceof AdapterView<?>)) return;
802
803 AdapterView<?> adapterView = (AdapterView<?>) view;
804
805 final View emptyView = root.findViewById(emptyViewId);
806 if (emptyView == null) return;
807
808 adapterView.setEmptyView(emptyView);
809 }
810
811 @Override
812 public int getActionTag() {
813 return SET_EMPTY_VIEW_ACTION_TAG;
814 }
815 }
816
817 private class SetPendingIntentTemplate extends Action {
818 public SetPendingIntentTemplate(@IdRes int id, PendingIntent pendingIntentTemplate) {
819 this.viewId = id;
820 this.pendingIntentTemplate = pendingIntentTemplate;
821 }
822
823 public SetPendingIntentTemplate(Parcel parcel) {
824 viewId = parcel.readInt();
825 pendingIntentTemplate = PendingIntent.readPendingIntentOrNullFromParcel(parcel);
826 }
827
828 public void writeToParcel(Parcel dest, int flags) {
829 dest.writeInt(viewId);
830 PendingIntent.writePendingIntentOrNullToParcel(pendingIntentTemplate, dest);
831 }
832
833 @Override
834 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
835 final View target = root.findViewById(viewId);
836 if (target == null) return;
837
838 // If the view isn't an AdapterView, setting a PendingIntent template doesn't make sense
839 if (target instanceof AdapterView<?>) {
840 AdapterView<?> av = (AdapterView<?>) target;
841 // The PendingIntent template is stored in the view's tag.
842 OnItemClickListener listener = (parent, view, position, id) -> {
843 RemoteResponse response = findRemoteResponseTag(view);
844 if (response != null) {
845 response.handleViewInteraction(view, params.handler);
846 }
847 };
848 av.setOnItemClickListener(listener);
849 av.setTag(pendingIntentTemplate);
850 } else {
851 Log.e(LOG_TAG, "Cannot setPendingIntentTemplate on a view which is not" +
852 "an AdapterView (id: " + viewId + ")");
853 return;
854 }
855 }
856
857 @Nullable
858 private RemoteResponse findRemoteResponseTag(@Nullable View rootView) {
859 if (rootView == null) return null;
860
861 ArrayDeque<View> viewsToCheck = new ArrayDeque<>();
862 viewsToCheck.addLast(rootView);
863
864 while (!viewsToCheck.isEmpty()) {
865 View view = viewsToCheck.removeFirst();
866 Object tag = view.getTag(R.id.fillInIntent);
867 if (tag instanceof RemoteResponse) return (RemoteResponse) tag;
868 if (!(view instanceof ViewGroup)) continue;
869
870 ViewGroup viewGroup = (ViewGroup) view;
871 for (int i = 0; i < viewGroup.getChildCount(); i++) {
872 viewsToCheck.addLast(viewGroup.getChildAt(i));
873 }
874 }
875
876 return null;
877 }
878
879 @Override
880 public int getActionTag() {
881 return SET_PENDING_INTENT_TEMPLATE_TAG;
882 }
883
884 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
885 PendingIntent pendingIntentTemplate;
886 }
887
888 private class SetRemoteViewsAdapterList extends Action {
889 public SetRemoteViewsAdapterList(@IdRes int id, ArrayList<RemoteViews> list,
890 int viewTypeCount) {
891 this.viewId = id;
892 this.list = list;
893 this.viewTypeCount = viewTypeCount;
894 }
895
896 public SetRemoteViewsAdapterList(Parcel parcel) {
897 viewId = parcel.readInt();
898 viewTypeCount = parcel.readInt();
899 list = parcel.createTypedArrayList(RemoteViews.CREATOR);
900 }
901
902 public void writeToParcel(Parcel dest, int flags) {
903 dest.writeInt(viewId);
904 dest.writeInt(viewTypeCount);
905 dest.writeTypedList(list, flags);
906 }
907
908 @Override
909 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
910 final View target = root.findViewById(viewId);
911 if (target == null) return;
912
913 // Ensure that we are applying to an AppWidget root
914 if (!(rootParent instanceof AppWidgetHostView)) {
915 Log.e(LOG_TAG, "SetRemoteViewsAdapterIntent action can only be used for " +
916 "AppWidgets (root id: " + viewId + ")");
917 return;
918 }
919 // Ensure that we are calling setRemoteAdapter on an AdapterView that supports it
920 if (!(target instanceof AbsListView) && !(target instanceof AdapterViewAnimator)) {
921 Log.e(LOG_TAG, "Cannot setRemoteViewsAdapter on a view which is not " +
922 "an AbsListView or AdapterViewAnimator (id: " + viewId + ")");
923 return;
924 }
925
926 if (target instanceof AbsListView) {
927 AbsListView v = (AbsListView) target;
928 Adapter a = v.getAdapter();
929 if (a instanceof RemoteViewsListAdapter && viewTypeCount <= a.getViewTypeCount()) {
930 ((RemoteViewsListAdapter) a).setViewsList(list);
931 } else {
932 v.setAdapter(new RemoteViewsListAdapter(v.getContext(), list, viewTypeCount,
933 params.colorResources));
934 }
935 } else if (target instanceof AdapterViewAnimator) {
936 AdapterViewAnimator v = (AdapterViewAnimator) target;
937 Adapter a = v.getAdapter();
938 if (a instanceof RemoteViewsListAdapter && viewTypeCount <= a.getViewTypeCount()) {
939 ((RemoteViewsListAdapter) a).setViewsList(list);
940 } else {
941 v.setAdapter(new RemoteViewsListAdapter(v.getContext(), list, viewTypeCount,
942 params.colorResources));
943 }
944 }
945 }
946
947 @Override
948 public int getActionTag() {
949 return SET_REMOTE_VIEW_ADAPTER_LIST_TAG;
950 }
951
952 int viewTypeCount;
953 ArrayList<RemoteViews> list;
954 }
955
956 /**
957 * Cache of {@link ApplicationInfo}s that can be used to ensure that the same
958 * {@link ApplicationInfo} instance is used throughout the RemoteViews.
959 */
960 private static class ApplicationInfoCache {
961 private final Map<Pair<String, Integer>, ApplicationInfo> mPackageUserToApplicationInfo;
962
963 ApplicationInfoCache() {
964 mPackageUserToApplicationInfo = new ArrayMap<>();
965 }
966
967 /**
968 * Adds the {@link ApplicationInfo} to the cache if it's not present. Returns either the
969 * provided {@code applicationInfo} or a previously added value with the same package name
970 * and uid.
971 */
972 @Nullable
973 ApplicationInfo getOrPut(@Nullable ApplicationInfo applicationInfo) {
974 Pair<String, Integer> key = getPackageUserKey(applicationInfo);
975 if (key == null) return null;
976 return mPackageUserToApplicationInfo.computeIfAbsent(key, ignored -> applicationInfo);
977 }
978
979 /** Puts the {@link ApplicationInfo} in the cache, replacing any previously stored value. */
980 void put(@Nullable ApplicationInfo applicationInfo) {
981 Pair<String, Integer> key = getPackageUserKey(applicationInfo);
982 if (key == null) return;
983 mPackageUserToApplicationInfo.put(key, applicationInfo);
984 }
985
986 /**
987 * Returns the currently stored {@link ApplicationInfo} from the cache matching
988 * {@code applicationInfo}, or null if there wasn't any.
989 */
990 @Nullable ApplicationInfo get(@Nullable ApplicationInfo applicationInfo) {
991 Pair<String, Integer> key = getPackageUserKey(applicationInfo);
992 if (key == null) return null;
993 return mPackageUserToApplicationInfo.get(key);
994 }
995 }
996
997 private class SetRemoteCollectionItemListAdapterAction extends Action {
998 private final RemoteCollectionItems mItems;
999
1000 SetRemoteCollectionItemListAdapterAction(@IdRes int id, RemoteCollectionItems items) {
1001 viewId = id;
1002 mItems = items;
1003 mItems.setHierarchyRootData(getHierarchyRootData());
1004 }
1005
1006 SetRemoteCollectionItemListAdapterAction(Parcel parcel) {
1007 viewId = parcel.readInt();
1008 mItems = new RemoteCollectionItems(parcel, getHierarchyRootData());
1009 }
1010
1011 @Override
1012 public void setHierarchyRootData(HierarchyRootData rootData) {
1013 mItems.setHierarchyRootData(rootData);
1014 }
1015
1016 @Override
1017 public void writeToParcel(Parcel dest, int flags) {
1018 dest.writeInt(viewId);
1019 mItems.writeToParcel(dest, flags, /* attached= */ true);
1020 }
1021
1022 @Override
1023 public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
1024 throws ActionException {
1025 View target = root.findViewById(viewId);
1026 if (target == null) return;
1027
1028 // Ensure that we are applying to an AppWidget root
1029 if (!(rootParent instanceof AppWidgetHostView)) {
1030 Log.e(LOG_TAG, "setRemoteAdapter can only be used for "
1031 + "AppWidgets (root id: " + viewId + ")");
1032 return;
1033 }
1034
1035 if (!(target instanceof AdapterView)) {
1036 Log.e(LOG_TAG, "Cannot call setRemoteAdapter on a view which is not "
1037 + "an AdapterView (id: " + viewId + ")");
1038 return;
1039 }
1040
1041 AdapterView adapterView = (AdapterView) target;
1042 Adapter adapter = adapterView.getAdapter();
1043 // We can reuse the adapter if it's a RemoteCollectionItemsAdapter and the view type
1044 // count hasn't increased. Note that AbsListView allocates a fixed size array for view
1045 // recycling in setAdapter, so we must call setAdapter again if the number of view types
1046 // increases.
1047 if (adapter instanceof RemoteCollectionItemsAdapter
1048 && adapter.getViewTypeCount() >= mItems.getViewTypeCount()) {
1049 try {
1050 ((RemoteCollectionItemsAdapter) adapter).setData(
1051 mItems, params.handler, params.colorResources);
1052 } catch (Throwable throwable) {
1053 // setData should never failed with the validation in the items builder, but if
1054 // it does, catch and rethrow.
1055 throw new ActionException(throwable);
1056 }
1057 return;
1058 }
1059
1060 try {
1061 adapterView.setAdapter(new RemoteCollectionItemsAdapter(mItems,
1062 params.handler, params.colorResources));
1063 } catch (Throwable throwable) {
1064 // This could throw if the AdapterView somehow doesn't accept BaseAdapter due to
1065 // a type error.
1066 throw new ActionException(throwable);
1067 }
1068 }
1069
1070 @Override
1071 public int getActionTag() {
1072 return SET_REMOTE_COLLECTION_ITEMS_ADAPTER_TAG;
1073 }
1074 }
1075
1076 private class SetRemoteViewsAdapterIntent extends Action {
1077 public SetRemoteViewsAdapterIntent(@IdRes int id, Intent intent) {
1078 this.viewId = id;
1079 this.intent = intent;
1080 }
1081
1082 public SetRemoteViewsAdapterIntent(Parcel parcel) {
1083 viewId = parcel.readInt();
1084 intent = parcel.readTypedObject(Intent.CREATOR);
1085 }
1086
1087 public void writeToParcel(Parcel dest, int flags) {
1088 dest.writeInt(viewId);
1089 dest.writeTypedObject(intent, flags);
1090 }
1091
1092 @Override
1093 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
1094 final View target = root.findViewById(viewId);
1095 if (target == null) return;
1096
1097 // Ensure that we are applying to an AppWidget root
1098 if (!(rootParent instanceof AppWidgetHostView)) {
1099 Log.e(LOG_TAG, "setRemoteAdapter can only be used for "
1100 + "AppWidgets (root id: " + viewId + ")");
1101 return;
1102 }
1103
1104 // Ensure that we are calling setRemoteAdapter on an AdapterView that supports it
1105 if (!(target instanceof AbsListView) && !(target instanceof AdapterViewAnimator)) {
1106 Log.e(LOG_TAG, "Cannot setRemoteAdapter on a view which is not "
1107 + "an AbsListView or AdapterViewAnimator (id: " + viewId + ")");
1108 return;
1109 }
1110
1111 // Embed the AppWidget Id for use in RemoteViewsAdapter when connecting to the intent
1112 // RemoteViewsService
1113 AppWidgetHostView host = (AppWidgetHostView) rootParent;
1114 intent.putExtra(EXTRA_REMOTEADAPTER_APPWIDGET_ID, host.getAppWidgetId())
1115 .putExtra(EXTRA_REMOTEADAPTER_ON_LIGHT_BACKGROUND,
1116 hasFlags(FLAG_USE_LIGHT_BACKGROUND_LAYOUT));
1117
1118 if (target instanceof AbsListView) {
1119 AbsListView v = (AbsListView) target;
1120 v.setRemoteViewsAdapter(intent, isAsync);
1121 v.setRemoteViewsInteractionHandler(params.handler);
1122 } else if (target instanceof AdapterViewAnimator) {
1123 AdapterViewAnimator v = (AdapterViewAnimator) target;
1124 v.setRemoteViewsAdapter(intent, isAsync);
1125 v.setRemoteViewsOnClickHandler(params.handler);
1126 }
1127 }
1128
1129 @Override
1130 public Action initActionAsync(ViewTree root, ViewGroup rootParent,
1131 ActionApplyParams params) {
1132 SetRemoteViewsAdapterIntent copy = new SetRemoteViewsAdapterIntent(viewId, intent);
1133 copy.isAsync = true;
1134 return copy;
1135 }
1136
1137 @Override
1138 public int getActionTag() {
1139 return SET_REMOTE_VIEW_ADAPTER_INTENT_TAG;
1140 }
1141
1142 Intent intent;
1143 boolean isAsync = false;
1144 }
1145
1146 /**
1147 * Equivalent to calling
1148 * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)}
1149 * to launch the provided {@link PendingIntent}.
1150 */
1151 private class SetOnClickResponse extends Action {
1152
1153 SetOnClickResponse(@IdRes int id, RemoteResponse response) {
1154 this.viewId = id;
1155 this.mResponse = response;
1156 }
1157
1158 SetOnClickResponse(Parcel parcel) {
1159 viewId = parcel.readInt();
1160 mResponse = new RemoteResponse();
1161 mResponse.readFromParcel(parcel);
1162 }
1163
1164 public void writeToParcel(Parcel dest, int flags) {
1165 dest.writeInt(viewId);
1166 mResponse.writeToParcel(dest, flags);
1167 }
1168
1169 @Override
1170 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
1171 final View target = root.findViewById(viewId);
1172 if (target == null) return;
1173
1174 if (mResponse.mPendingIntent != null) {
1175 // If the view is an AdapterView, setting a PendingIntent on click doesn't make
1176 // much sense, do they mean to set a PendingIntent template for the
1177 // AdapterView's children?
1178 if (hasFlags(FLAG_WIDGET_IS_COLLECTION_CHILD)) {
1179 Log.w(LOG_TAG, "Cannot SetOnClickResponse for collection item "
1180 + "(id: " + viewId + ")");
1181 ApplicationInfo appInfo = root.getContext().getApplicationInfo();
1182
1183 // We let this slide for HC and ICS so as to not break compatibility. It should
1184 // have been disabled from the outset, but was left open by accident.
1185 if (appInfo != null
1186 && appInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
1187 return;
1188 }
1189 }
1190 target.setTagInternal(R.id.pending_intent_tag, mResponse.mPendingIntent);
1191 } else if (mResponse.mFillIntent != null) {
1192 if (!hasFlags(FLAG_WIDGET_IS_COLLECTION_CHILD)) {
1193 Log.e(LOG_TAG, "The method setOnClickFillInIntent is available "
1194 + "only from RemoteViewsFactory (ie. on collection items).");
1195 return;
1196 }
1197 if (target == root) {
1198 // Target is a root node of an AdapterView child. Set the response in the tag.
1199 // Actual click handling is done by OnItemClickListener in
1200 // SetPendingIntentTemplate, which uses this tag information.
1201 target.setTagInternal(com.android.internal.R.id.fillInIntent, mResponse);
1202 return;
1203 }
1204 } else {
1205 // No intent to apply, clear the listener and any tags that were previously set.
1206 target.setOnClickListener(null);
1207 target.setTagInternal(R.id.pending_intent_tag, null);
1208 target.setTagInternal(com.android.internal.R.id.fillInIntent, null);
1209 return;
1210 }
1211 target.setOnClickListener(v -> mResponse.handleViewInteraction(v, params.handler));
1212 }
1213
1214 @Override
1215 public int getActionTag() {
1216 return SET_ON_CLICK_RESPONSE_TAG;
1217 }
1218
1219 final RemoteResponse mResponse;
1220 }
1221
1222 /**
1223 * Equivalent to calling
1224 * {@link android.widget.CompoundButton#setOnCheckedChangeListener(
1225 * android.widget.CompoundButton.OnCheckedChangeListener)}
1226 * to launch the provided {@link PendingIntent}.
1227 */
1228 private class SetOnCheckedChangeResponse extends Action {
1229
1230 private final RemoteResponse mResponse;
1231
1232 SetOnCheckedChangeResponse(@IdRes int id, RemoteResponse response) {
1233 this.viewId = id;
1234 this.mResponse = response;
1235 }
1236
1237 SetOnCheckedChangeResponse(Parcel parcel) {
1238 viewId = parcel.readInt();
1239 mResponse = new RemoteResponse();
1240 mResponse.readFromParcel(parcel);
1241 }
1242
1243 public void writeToParcel(Parcel dest, int flags) {
1244 dest.writeInt(viewId);
1245 mResponse.writeToParcel(dest, flags);
1246 }
1247
1248 @Override
1249 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
1250 final View target = root.findViewById(viewId);
1251 if (target == null) return;
1252 if (!(target instanceof CompoundButton)) {
1253 Log.w(LOG_TAG, "setOnCheckedChange methods cannot be used on "
1254 + "non-CompoundButton child (id: " + viewId + ")");
1255 return;
1256 }
1257 CompoundButton button = (CompoundButton) target;
1258
1259 if (mResponse.mPendingIntent != null) {
1260 // setOnCheckedChangePendingIntent cannot be used with collection children, which
1261 // must use setOnCheckedChangeFillInIntent instead.
1262 if (hasFlags(FLAG_WIDGET_IS_COLLECTION_CHILD)) {
1263 Log.w(LOG_TAG, "Cannot setOnCheckedChangePendingIntent for collection item "
1264 + "(id: " + viewId + ")");
1265 return;
1266 }
1267 target.setTagInternal(R.id.pending_intent_tag, mResponse.mPendingIntent);
1268 } else if (mResponse.mFillIntent != null) {
1269 if (!hasFlags(FLAG_WIDGET_IS_COLLECTION_CHILD)) {
1270 Log.e(LOG_TAG, "The method setOnCheckedChangeFillInIntent is available "
1271 + "only from RemoteViewsFactory (ie. on collection items).");
1272 return;
1273 }
1274 } else {
1275 // No intent to apply, clear any existing listener or tag.
1276 button.setOnCheckedChangeListener(null);
1277 button.setTagInternal(R.id.remote_checked_change_listener_tag, null);
1278 return;
1279 }
1280
1281 OnCheckedChangeListener onCheckedChangeListener =
1282 (v, isChecked) -> mResponse.handleViewInteraction(v, params.handler);
1283 button.setTagInternal(R.id.remote_checked_change_listener_tag, onCheckedChangeListener);
1284 button.setOnCheckedChangeListener(onCheckedChangeListener);
1285 }
1286
1287 @Override
1288 public int getActionTag() {
1289 return SET_ON_CHECKED_CHANGE_RESPONSE_TAG;
1290 }
1291 }
1292
1293 /** @hide **/
1294 public static Rect getSourceBounds(View v) {
1295 final float appScale = v.getContext().getResources()
1296 .getCompatibilityInfo().applicationScale;
1297 final int[] pos = new int[2];
1298 v.getLocationOnScreen(pos);
1299
1300 final Rect rect = new Rect();
1301 rect.left = (int) (pos[0] * appScale + 0.5f);
1302 rect.top = (int) (pos[1] * appScale + 0.5f);
1303 rect.right = (int) ((pos[0] + v.getWidth()) * appScale + 0.5f);
1304 rect.bottom = (int) ((pos[1] + v.getHeight()) * appScale + 0.5f);
1305 return rect;
1306 }
1307
1308 @Nullable
1309 private static Class<?> getParameterType(int type) {
1310 switch (type) {
1311 case BaseReflectionAction.BOOLEAN:
1312 return boolean.class;
1313 case BaseReflectionAction.BYTE:
1314 return byte.class;
1315 case BaseReflectionAction.SHORT:
1316 return short.class;
1317 case BaseReflectionAction.INT:
1318 return int.class;
1319 case BaseReflectionAction.LONG:
1320 return long.class;
1321 case BaseReflectionAction.FLOAT:
1322 return float.class;
1323 case BaseReflectionAction.DOUBLE:
1324 return double.class;
1325 case BaseReflectionAction.CHAR:
1326 return char.class;
1327 case BaseReflectionAction.STRING:
1328 return String.class;
1329 case BaseReflectionAction.CHAR_SEQUENCE:
1330 return CharSequence.class;
1331 case BaseReflectionAction.URI:
1332 return Uri.class;
1333 case BaseReflectionAction.BITMAP:
1334 return Bitmap.class;
1335 case BaseReflectionAction.BUNDLE:
1336 return Bundle.class;
1337 case BaseReflectionAction.INTENT:
1338 return Intent.class;
1339 case BaseReflectionAction.COLOR_STATE_LIST:
1340 return ColorStateList.class;
1341 case BaseReflectionAction.ICON:
1342 return Icon.class;
1343 case BaseReflectionAction.BLEND_MODE:
1344 return BlendMode.class;
1345 default:
1346 return null;
1347 }
1348 }
1349
1350 @Nullable
1351 private MethodHandle getMethod(View view, String methodName, Class<?> paramType,
1352 boolean async) {
1353 MethodArgs result;
1354 Class<? extends View> klass = view.getClass();
1355
1356 synchronized (sMethods) {
1357 // The key is defined by the view class, param class and method name.
1358 sLookupKey.set(klass, paramType, methodName);
1359 result = sMethods.get(sLookupKey);
1360
1361 if (result == null) {
1362 Method method;
1363 try {
1364 if (paramType == null) {
1365 method = klass.getMethod(methodName);
1366 } else {
1367 method = klass.getMethod(methodName, paramType);
1368 }
1369 if (!method.isAnnotationPresent(RemotableViewMethod.class)) {
1370 throw new ActionException("view: " + klass.getName()
1371 + " can't use method with RemoteViews: "
1372 + methodName + getParameters(paramType));
1373 }
1374
1375 result = new MethodArgs();
1376 result.syncMethod = MethodHandles.publicLookup().unreflect(method);
1377 result.asyncMethodName =
1378 method.getAnnotation(RemotableViewMethod.class).asyncImpl();
1379 } catch (NoSuchMethodException | IllegalAccessException ex) {
1380 throw new ActionException("view: " + klass.getName() + " doesn't have method: "
1381 + methodName + getParameters(paramType));
1382 }
1383
1384 MethodKey key = new MethodKey();
1385 key.set(klass, paramType, methodName);
1386 sMethods.put(key, result);
1387 }
1388
1389 if (!async) {
1390 return result.syncMethod;
1391 }
1392 // Check this so see if async method is implemented or not.
1393 if (result.asyncMethodName.isEmpty()) {
1394 return null;
1395 }
1396 // Async method is lazily loaded. If it is not yet loaded, load now.
1397 if (result.asyncMethod == null) {
1398 MethodType asyncType = result.syncMethod.type()
1399 .dropParameterTypes(0, 1).changeReturnType(Runnable.class);
1400 try {
1401 result.asyncMethod = MethodHandles.publicLookup().findVirtual(
1402 klass, result.asyncMethodName, asyncType);
1403 } catch (NoSuchMethodException | IllegalAccessException ex) {
1404 throw new ActionException("Async implementation declared as "
1405 + result.asyncMethodName + " but not defined for " + methodName
1406 + ": public Runnable " + result.asyncMethodName + " ("
1407 + TextUtils.join(",", asyncType.parameterArray()) + ")");
1408 }
1409 }
1410 return result.asyncMethod;
1411 }
1412 }
1413
1414 private static String getParameters(Class<?> paramType) {
1415 if (paramType == null) return "()";
1416 return "(" + paramType + ")";
1417 }
1418
1419 /**
1420 * Equivalent to calling
1421 * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)},
1422 * on the {@link Drawable} of a given view.
1423 * <p>
1424 * The operation will be performed on the {@link Drawable} returned by the
1425 * target {@link View#getBackground()} by default. If targetBackground is false,
1426 * we assume the target is an {@link ImageView} and try applying the operations
1427 * to {@link ImageView#getDrawable()}.
1428 * <p>
1429 */
1430 private class SetDrawableTint extends Action {
1431 SetDrawableTint(@IdRes int id, boolean targetBackground,
1432 @ColorInt int colorFilter, @NonNull PorterDuff.Mode mode) {
1433 this.viewId = id;
1434 this.targetBackground = targetBackground;
1435 this.colorFilter = colorFilter;
1436 this.filterMode = mode;
1437 }
1438
1439 SetDrawableTint(Parcel parcel) {
1440 viewId = parcel.readInt();
1441 targetBackground = parcel.readInt() != 0;
1442 colorFilter = parcel.readInt();
1443 filterMode = PorterDuff.intToMode(parcel.readInt());
1444 }
1445
1446 public void writeToParcel(Parcel dest, int flags) {
1447 dest.writeInt(viewId);
1448 dest.writeInt(targetBackground ? 1 : 0);
1449 dest.writeInt(colorFilter);
1450 dest.writeInt(PorterDuff.modeToInt(filterMode));
1451 }
1452
1453 @Override
1454 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
1455 final View target = root.findViewById(viewId);
1456 if (target == null) return;
1457
1458 // Pick the correct drawable to modify for this view
1459 Drawable targetDrawable = null;
1460 if (targetBackground) {
1461 targetDrawable = target.getBackground();
1462 } else if (target instanceof ImageView) {
1463 ImageView imageView = (ImageView) target;
1464 targetDrawable = imageView.getDrawable();
1465 }
1466
1467 if (targetDrawable != null) {
1468 targetDrawable.mutate().setColorFilter(colorFilter, filterMode);
1469 }
1470 }
1471
1472 @Override
1473 public int getActionTag() {
1474 return SET_DRAWABLE_TINT_TAG;
1475 }
1476
1477 boolean targetBackground;
1478 @ColorInt int colorFilter;
1479 PorterDuff.Mode filterMode;
1480 }
1481
1482 /**
1483 * Equivalent to calling
1484 * {@link RippleDrawable#setColor(ColorStateList)},
1485 * on the {@link Drawable} of a given view.
1486 * <p>
1487 * The operation will be performed on the {@link Drawable} returned by the
1488 * target {@link View#getBackground()}.
1489 * <p>
1490 */
1491 private class SetRippleDrawableColor extends Action {
1492
1493 ColorStateList mColorStateList;
1494
1495 SetRippleDrawableColor(@IdRes int id, ColorStateList colorStateList) {
1496 this.viewId = id;
1497 this.mColorStateList = colorStateList;
1498 }
1499
1500 SetRippleDrawableColor(Parcel parcel) {
1501 viewId = parcel.readInt();
1502 mColorStateList = parcel.readParcelable(null, android.content.res.ColorStateList.class);
1503 }
1504
1505 public void writeToParcel(Parcel dest, int flags) {
1506 dest.writeInt(viewId);
1507 dest.writeParcelable(mColorStateList, 0);
1508 }
1509
1510 @Override
1511 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
1512 final View target = root.findViewById(viewId);
1513 if (target == null) return;
1514
1515 // Pick the correct drawable to modify for this view
1516 Drawable targetDrawable = target.getBackground();
1517
1518 if (targetDrawable instanceof RippleDrawable) {
1519 ((RippleDrawable) targetDrawable.mutate()).setColor(mColorStateList);
1520 }
1521 }
1522
1523 @Override
1524 public int getActionTag() {
1525 return SET_RIPPLE_DRAWABLE_COLOR_TAG;
1526 }
1527 }
1528
1529 /**
1530 * @deprecated As RemoteViews may be reapplied frequently, it is preferable to call
1531 * {@link #setDisplayedChild(int, int)} to ensure that the adapter index does not change
1532 * unexpectedly.
1533 */
1534 @Deprecated
1535 private final class ViewContentNavigation extends Action {
1536 final boolean mNext;
1537
1538 ViewContentNavigation(@IdRes int viewId, boolean next) {
1539 this.viewId = viewId;
1540 this.mNext = next;
1541 }
1542
1543 ViewContentNavigation(Parcel in) {
1544 this.viewId = in.readInt();
1545 this.mNext = in.readBoolean();
1546 }
1547
1548 public void writeToParcel(Parcel out, int flags) {
1549 out.writeInt(this.viewId);
1550 out.writeBoolean(this.mNext);
1551 }
1552
1553 @Override
1554 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
1555 final View view = root.findViewById(viewId);
1556 if (view == null) return;
1557
1558 try {
1559 getMethod(view,
1560 mNext ? "showNext" : "showPrevious", null, false /* async */).invoke(view);
1561 } catch (Throwable ex) {
1562 throw new ActionException(ex);
1563 }
1564 }
1565
1566 public int mergeBehavior() {
1567 return MERGE_IGNORE;
1568 }
1569
1570 @Override
1571 public int getActionTag() {
1572 return VIEW_CONTENT_NAVIGATION_TAG;
1573 }
1574 }
1575
1576 private static class BitmapCache {
1577
1578 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1579 ArrayList<Bitmap> mBitmaps;
1580 SparseIntArray mBitmapHashes;
1581 int mBitmapMemory = -1;
1582
1583 public BitmapCache() {
1584 mBitmaps = new ArrayList<>();
1585 mBitmapHashes = new SparseIntArray();
1586 }
1587
1588 public BitmapCache(Parcel source) {
1589 mBitmaps = source.createTypedArrayList(Bitmap.CREATOR);
1590 mBitmapHashes = new SparseIntArray();
1591 for (int i = 0; i < mBitmaps.size(); i++) {
1592 Bitmap b = mBitmaps.get(i);
1593 if (b != null) {
1594 mBitmapHashes.put(b.hashCode(), i);
1595 }
1596 }
1597 }
1598
1599 public int getBitmapId(Bitmap b) {
1600 if (b == null) {
1601 return -1;
1602 } else {
1603 int hash = b.hashCode();
1604 int hashId = mBitmapHashes.get(hash, -1);
1605 if (hashId != -1) {
1606 return hashId;
1607 } else {
1608 if (b.isMutable()) {
1609 b = b.asShared();
1610 }
1611 mBitmaps.add(b);
1612 mBitmapHashes.put(hash, mBitmaps.size() - 1);
1613 mBitmapMemory = -1;
1614 return (mBitmaps.size() - 1);
1615 }
1616 }
1617 }
1618
1619 @Nullable
1620 public Bitmap getBitmapForId(int id) {
1621 if (id == -1 || id >= mBitmaps.size()) {
1622 return null;
1623 }
1624 return mBitmaps.get(id);
1625 }
1626
1627 public void writeBitmapsToParcel(Parcel dest, int flags) {
1628 dest.writeTypedList(mBitmaps, flags);
1629 }
1630
1631 public int getBitmapMemory() {
1632 if (mBitmapMemory < 0) {
1633 mBitmapMemory = 0;
1634 int count = mBitmaps.size();
1635 for (int i = 0; i < count; i++) {
1636 mBitmapMemory += mBitmaps.get(i).getAllocationByteCount();
1637 }
1638 }
1639 return mBitmapMemory;
1640 }
1641 }
1642
1643 private class BitmapReflectionAction extends Action {
1644 int bitmapId;
1645 @UnsupportedAppUsage
1646 Bitmap bitmap;
1647 @UnsupportedAppUsage
1648 String methodName;
1649
1650 BitmapReflectionAction(@IdRes int viewId, String methodName, Bitmap bitmap) {
1651 this.bitmap = bitmap;
1652 this.viewId = viewId;
1653 this.methodName = methodName;
1654 bitmapId = mBitmapCache.getBitmapId(bitmap);
1655 }
1656
1657 BitmapReflectionAction(Parcel in) {
1658 viewId = in.readInt();
1659 methodName = in.readString8();
1660 bitmapId = in.readInt();
1661 bitmap = mBitmapCache.getBitmapForId(bitmapId);
1662 }
1663
1664 @Override
1665 public void writeToParcel(Parcel dest, int flags) {
1666 dest.writeInt(viewId);
1667 dest.writeString8(methodName);
1668 dest.writeInt(bitmapId);
1669 }
1670
1671 @Override
1672 public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
1673 throws ActionException {
1674 ReflectionAction ra = new ReflectionAction(viewId, methodName,
1675 BaseReflectionAction.BITMAP,
1676 bitmap);
1677 ra.apply(root, rootParent, params);
1678 }
1679
1680 @Override
1681 public void setHierarchyRootData(HierarchyRootData rootData) {
1682 bitmapId = rootData.mBitmapCache.getBitmapId(bitmap);
1683 }
1684
1685 @Override
1686 public int getActionTag() {
1687 return BITMAP_REFLECTION_ACTION_TAG;
1688 }
1689 }
1690
1691 /**
1692 * Base class for the reflection actions.
1693 */
1694 private abstract class BaseReflectionAction extends Action {
1695 static final int BOOLEAN = 1;
1696 static final int BYTE = 2;
1697 static final int SHORT = 3;
1698 static final int INT = 4;
1699 static final int LONG = 5;
1700 static final int FLOAT = 6;
1701 static final int DOUBLE = 7;
1702 static final int CHAR = 8;
1703 static final int STRING = 9;
1704 static final int CHAR_SEQUENCE = 10;
1705 static final int URI = 11;
1706 // BITMAP actions are never stored in the list of actions. They are only used locally
1707 // to implement BitmapReflectionAction, which eliminates duplicates using BitmapCache.
1708 static final int BITMAP = 12;
1709 static final int BUNDLE = 13;
1710 static final int INTENT = 14;
1711 static final int COLOR_STATE_LIST = 15;
1712 static final int ICON = 16;
1713 static final int BLEND_MODE = 17;
1714
1715 @UnsupportedAppUsage
1716 String methodName;
1717 int type;
1718
1719 BaseReflectionAction(@IdRes int viewId, String methodName, int type) {
1720 this.viewId = viewId;
1721 this.methodName = methodName;
1722 this.type = type;
1723 }
1724
1725 BaseReflectionAction(Parcel in) {
1726 this.viewId = in.readInt();
1727 this.methodName = in.readString8();
1728 this.type = in.readInt();
1729 //noinspection ConstantIfStatement
1730 if (false) {
1731 Log.d(LOG_TAG, "read viewId=0x" + Integer.toHexString(this.viewId)
1732 + " methodName=" + this.methodName + " type=" + this.type);
1733 }
1734 }
1735
1736 public void writeToParcel(Parcel out, int flags) {
1737 out.writeInt(this.viewId);
1738 out.writeString8(this.methodName);
1739 out.writeInt(this.type);
1740 }
1741
1742 /**
1743 * Returns the value to use as parameter for the method.
1744 *
1745 * The view might be passed as {@code null} if the parameter value is requested outside of
1746 * inflation. If the parameter cannot be determined at that time, the method should return
1747 * {@code null} but not raise any exception.
1748 */
1749 @Nullable
1750 protected abstract Object getParameterValue(@Nullable View view) throws ActionException;
1751
1752 @Override
1753 public final void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
1754 final View view = root.findViewById(viewId);
1755 if (view == null) return;
1756
1757 Class<?> param = getParameterType(this.type);
1758 if (param == null) {
1759 throw new ActionException("bad type: " + this.type);
1760 }
1761 Object value = getParameterValue(view);
1762 try {
1763 getMethod(view, this.methodName, param, false /* async */).invoke(view, value);
1764 } catch (Throwable ex) {
1765 throw new ActionException(ex);
1766 }
1767 }
1768
1769 @Override
1770 public final Action initActionAsync(ViewTree root, ViewGroup rootParent,
1771 ActionApplyParams params) {
1772 final View view = root.findViewById(viewId);
1773 if (view == null) return ACTION_NOOP;
1774
1775 Class<?> param = getParameterType(this.type);
1776 if (param == null) {
1777 throw new ActionException("bad type: " + this.type);
1778 }
1779
1780 Object value = getParameterValue(view);
1781 try {
1782 MethodHandle method = getMethod(view, this.methodName, param, true /* async */);
1783
1784 if (method != null) {
1785 Runnable endAction = (Runnable) method.invoke(view, value);
1786 if (endAction == null) {
1787 return ACTION_NOOP;
1788 }
1789 // Special case view stub
1790 if (endAction instanceof ViewStub.ViewReplaceRunnable) {
1791 root.createTree();
1792 // Replace child tree
1793 root.findViewTreeById(viewId).replaceView(
1794 ((ViewStub.ViewReplaceRunnable) endAction).view);
1795 }
1796 return new RunnableAction(endAction);
1797 }
1798 } catch (Throwable ex) {
1799 throw new ActionException(ex);
1800 }
1801
1802 return this;
1803 }
1804
1805 public final int mergeBehavior() {
1806 // smoothScrollBy is cumulative, everything else overwites.
1807 if (methodName.equals("smoothScrollBy")) {
1808 return MERGE_APPEND;
1809 } else {
1810 return MERGE_REPLACE;
1811 }
1812 }
1813
1814 @Override
1815 public final String getUniqueKey() {
1816 // Each type of reflection action corresponds to a setter, so each should be seen as
1817 // unique from the standpoint of merging.
1818 return super.getUniqueKey() + this.methodName + this.type;
1819 }
1820
1821 @Override
1822 public final boolean prefersAsyncApply() {
1823 return this.type == URI || this.type == ICON;
1824 }
1825
1826 @Override
1827 public final void visitUris(@NonNull Consumer<Uri> visitor) {
1828 switch (this.type) {
1829 case URI:
1830 final Uri uri = (Uri) getParameterValue(null);
1831 if (uri != null) visitor.accept(uri);
1832 break;
1833 case ICON:
1834 final Icon icon = (Icon) getParameterValue(null);
1835 if (icon != null) visitIconUri(icon, visitor);
1836 break;
1837 }
1838 }
1839 }
1840
1841 /** Class for the reflection actions. */
1842 private final class ReflectionAction extends BaseReflectionAction {
1843 @UnsupportedAppUsage
1844 Object value;
1845
1846 ReflectionAction(@IdRes int viewId, String methodName, int type, Object value) {
1847 super(viewId, methodName, type);
1848 this.value = value;
1849 }
1850
1851 ReflectionAction(Parcel in) {
1852 super(in);
1853 // For some values that may have been null, we first check a flag to see if they were
1854 // written to the parcel.
1855 switch (this.type) {
1856 case BOOLEAN:
1857 this.value = in.readBoolean();
1858 break;
1859 case BYTE:
1860 this.value = in.readByte();
1861 break;
1862 case SHORT:
1863 this.value = (short) in.readInt();
1864 break;
1865 case INT:
1866 this.value = in.readInt();
1867 break;
1868 case LONG:
1869 this.value = in.readLong();
1870 break;
1871 case FLOAT:
1872 this.value = in.readFloat();
1873 break;
1874 case DOUBLE:
1875 this.value = in.readDouble();
1876 break;
1877 case CHAR:
1878 this.value = (char) in.readInt();
1879 break;
1880 case STRING:
1881 this.value = in.readString8();
1882 break;
1883 case CHAR_SEQUENCE:
1884 this.value = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
1885 break;
1886 case URI:
1887 this.value = in.readTypedObject(Uri.CREATOR);
1888 break;
1889 case BITMAP:
1890 this.value = in.readTypedObject(Bitmap.CREATOR);
1891 break;
1892 case BUNDLE:
1893 // Because we use Parcel.allowSquashing() when writing, and that affects
1894 // how the contents of Bundles are written, we need to ensure the bundle is
1895 // unparceled immediately, not lazily. Setting a custom ReadWriteHelper
1896 // just happens to have that effect on Bundle.readFromParcel().
1897 // TODO(b/212731590): build this state tracking into Bundle
1898 if (in.hasReadWriteHelper()) {
1899 this.value = in.readBundle();
1900 } else {
1901 in.setReadWriteHelper(ALTERNATIVE_DEFAULT);
1902 this.value = in.readBundle();
1903 in.setReadWriteHelper(null);
1904 }
1905 break;
1906 case INTENT:
1907 this.value = in.readTypedObject(Intent.CREATOR);
1908 break;
1909 case COLOR_STATE_LIST:
1910 this.value = in.readTypedObject(ColorStateList.CREATOR);
1911 break;
1912 case ICON:
1913 this.value = in.readTypedObject(Icon.CREATOR);
1914 break;
1915 case BLEND_MODE:
1916 this.value = BlendMode.fromValue(in.readInt());
1917 break;
1918 default:
1919 break;
1920 }
1921 }
1922
1923 public void writeToParcel(Parcel out, int flags) {
1924 super.writeToParcel(out, flags);
1925 // For some values which are null, we record an integer flag to indicate whether
1926 // we have written a valid value to the parcel.
1927 switch (this.type) {
1928 case BOOLEAN:
1929 out.writeBoolean((Boolean) this.value);
1930 break;
1931 case BYTE:
1932 out.writeByte((Byte) this.value);
1933 break;
1934 case SHORT:
1935 out.writeInt((Short) this.value);
1936 break;
1937 case INT:
1938 out.writeInt((Integer) this.value);
1939 break;
1940 case LONG:
1941 out.writeLong((Long) this.value);
1942 break;
1943 case FLOAT:
1944 out.writeFloat((Float) this.value);
1945 break;
1946 case DOUBLE:
1947 out.writeDouble((Double) this.value);
1948 break;
1949 case CHAR:
1950 out.writeInt((int) ((Character) this.value).charValue());
1951 break;
1952 case STRING:
1953 out.writeString8((String) this.value);
1954 break;
1955 case CHAR_SEQUENCE:
1956 TextUtils.writeToParcel((CharSequence) this.value, out, flags);
1957 break;
1958 case BUNDLE:
1959 out.writeBundle((Bundle) this.value);
1960 break;
1961 case BLEND_MODE:
1962 out.writeInt(BlendMode.toValue((BlendMode) this.value));
1963 break;
1964 case URI:
1965 case BITMAP:
1966 case INTENT:
1967 case COLOR_STATE_LIST:
1968 case ICON:
1969 out.writeTypedObject((Parcelable) this.value, flags);
1970 break;
1971 default:
1972 break;
1973 }
1974 }
1975
1976 @Nullable
1977 @Override
1978 protected Object getParameterValue(@Nullable View view) throws ActionException {
1979 return this.value;
1980 }
1981
1982 @Override
1983 public int getActionTag() {
1984 return REFLECTION_ACTION_TAG;
1985 }
1986 }
1987
1988 private final class ResourceReflectionAction extends BaseReflectionAction {
1989
1990 static final int DIMEN_RESOURCE = 1;
1991 static final int COLOR_RESOURCE = 2;
1992 static final int STRING_RESOURCE = 3;
1993
1994 private final int mResourceType;
1995 private final int mResId;
1996
1997 ResourceReflectionAction(@IdRes int viewId, String methodName, int parameterType,
1998 int resourceType, int resId) {
1999 super(viewId, methodName, parameterType);
2000 this.mResourceType = resourceType;
2001 this.mResId = resId;
2002 }
2003
2004 ResourceReflectionAction(Parcel in) {
2005 super(in);
2006 this.mResourceType = in.readInt();
2007 this.mResId = in.readInt();
2008 }
2009
2010 @Override
2011 public void writeToParcel(Parcel dest, int flags) {
2012 super.writeToParcel(dest, flags);
2013 dest.writeInt(this.mResourceType);
2014 dest.writeInt(this.mResId);
2015 }
2016
2017 @Nullable
2018 @Override
2019 protected Object getParameterValue(@Nullable View view) throws ActionException {
2020 if (view == null) return null;
2021
2022 Resources resources = view.getContext().getResources();
2023 try {
2024 switch (this.mResourceType) {
2025 case DIMEN_RESOURCE:
2026 switch (this.type) {
2027 case BaseReflectionAction.INT:
2028 return mResId == 0 ? 0 : resources.getDimensionPixelSize(mResId);
2029 case BaseReflectionAction.FLOAT:
2030 return mResId == 0 ? 0f : resources.getDimension(mResId);
2031 default:
2032 throw new ActionException(
2033 "dimen resources must be used as INT or FLOAT, "
2034 + "not " + this.type);
2035 }
2036 case COLOR_RESOURCE:
2037 switch (this.type) {
2038 case BaseReflectionAction.INT:
2039 return mResId == 0 ? 0 : view.getContext().getColor(mResId);
2040 case BaseReflectionAction.COLOR_STATE_LIST:
2041 return mResId == 0
2042 ? null : view.getContext().getColorStateList(mResId);
2043 default:
2044 throw new ActionException(
2045 "color resources must be used as INT or COLOR_STATE_LIST,"
2046 + " not " + this.type);
2047 }
2048 case STRING_RESOURCE:
2049 switch (this.type) {
2050 case BaseReflectionAction.CHAR_SEQUENCE:
2051 return mResId == 0 ? null : resources.getText(mResId);
2052 case BaseReflectionAction.STRING:
2053 return mResId == 0 ? null : resources.getString(mResId);
2054 default:
2055 throw new ActionException(
2056 "string resources must be used as STRING or CHAR_SEQUENCE,"
2057 + " not " + this.type);
2058 }
2059 default:
2060 throw new ActionException("unknown resource type: " + this.mResourceType);
2061 }
2062 } catch (ActionException ex) {
2063 throw ex;
2064 } catch (Throwable t) {
2065 throw new ActionException(t);
2066 }
2067 }
2068
2069 @Override
2070 public int getActionTag() {
2071 return RESOURCE_REFLECTION_ACTION_TAG;
2072 }
2073 }
2074
2075 private final class AttributeReflectionAction extends BaseReflectionAction {
2076
2077 static final int DIMEN_RESOURCE = 1;
2078 static final int COLOR_RESOURCE = 2;
2079 static final int STRING_RESOURCE = 3;
2080
2081 private final int mResourceType;
2082 private final int mAttrId;
2083
2084 AttributeReflectionAction(@IdRes int viewId, String methodName, int parameterType,
2085 int resourceType, int attrId) {
2086 super(viewId, methodName, parameterType);
2087 this.mResourceType = resourceType;
2088 this.mAttrId = attrId;
2089 }
2090
2091 AttributeReflectionAction(Parcel in) {
2092 super(in);
2093 this.mResourceType = in.readInt();
2094 this.mAttrId = in.readInt();
2095 }
2096
2097 @Override
2098 public void writeToParcel(Parcel dest, int flags) {
2099 super.writeToParcel(dest, flags);
2100 dest.writeInt(this.mResourceType);
2101 dest.writeInt(this.mAttrId);
2102 }
2103
2104 @Override
2105 protected Object getParameterValue(View view) throws ActionException {
2106 TypedArray typedArray = view.getContext().obtainStyledAttributes(new int[]{mAttrId});
2107 try {
2108 // When mAttrId == 0, we will depend on the default values below
2109 if (mAttrId != 0 && typedArray.getType(0) == TypedValue.TYPE_NULL) {
2110 throw new ActionException("Attribute 0x" + Integer.toHexString(this.mAttrId)
2111 + " is not defined");
2112 }
2113 switch (this.mResourceType) {
2114 case DIMEN_RESOURCE:
2115 switch (this.type) {
2116 case BaseReflectionAction.INT:
2117 return typedArray.getDimensionPixelSize(0, 0);
2118 case BaseReflectionAction.FLOAT:
2119 return typedArray.getDimension(0, 0);
2120 default:
2121 throw new ActionException(
2122 "dimen attribute 0x" + Integer.toHexString(this.mAttrId)
2123 + " must be used as INT or FLOAT,"
2124 + " not " + this.type);
2125 }
2126 case COLOR_RESOURCE:
2127 switch (this.type) {
2128 case BaseReflectionAction.INT:
2129 return typedArray.getColor(0, 0);
2130 case BaseReflectionAction.COLOR_STATE_LIST:
2131 return typedArray.getColorStateList(0);
2132 default:
2133 throw new ActionException(
2134 "color attribute 0x" + Integer.toHexString(this.mAttrId)
2135 + " must be used as INT or COLOR_STATE_LIST,"
2136 + " not " + this.type);
2137 }
2138 case STRING_RESOURCE:
2139 switch (this.type) {
2140 case BaseReflectionAction.CHAR_SEQUENCE:
2141 return typedArray.getText(0);
2142 case BaseReflectionAction.STRING:
2143 return typedArray.getString(0);
2144 default:
2145 throw new ActionException(
2146 "string attribute 0x" + Integer.toHexString(this.mAttrId)
2147 + " must be used as STRING or CHAR_SEQUENCE,"
2148 + " not " + this.type);
2149 }
2150 default:
2151 // Note: This can only be an implementation error.
2152 throw new ActionException(
2153 "Unknown resource type: " + this.mResourceType);
2154 }
2155 } catch (ActionException ex) {
2156 throw ex;
2157 } catch (Throwable t) {
2158 throw new ActionException(t);
2159 } finally {
2160 typedArray.recycle();
2161 }
2162 }
2163
2164 @Override
2165 public int getActionTag() {
2166 return ATTRIBUTE_REFLECTION_ACTION_TAG;
2167 }
2168 }
2169 private final class ComplexUnitDimensionReflectionAction extends BaseReflectionAction {
2170
2171 private final float mValue;
2172 @ComplexDimensionUnit
2173 private final int mUnit;
2174
2175 ComplexUnitDimensionReflectionAction(int viewId, String methodName, int parameterType,
2176 float value, @ComplexDimensionUnit int unit) {
2177 super(viewId, methodName, parameterType);
2178 this.mValue = value;
2179 this.mUnit = unit;
2180 }
2181
2182 ComplexUnitDimensionReflectionAction(Parcel in) {
2183 super(in);
2184 this.mValue = in.readFloat();
2185 this.mUnit = in.readInt();
2186 }
2187
2188 @Override
2189 public void writeToParcel(Parcel dest, int flags) {
2190 super.writeToParcel(dest, flags);
2191 dest.writeFloat(this.mValue);
2192 dest.writeInt(this.mUnit);
2193 }
2194
2195 @Nullable
2196 @Override
2197 protected Object getParameterValue(@Nullable View view) throws ActionException {
2198 if (view == null) return null;
2199
2200 DisplayMetrics dm = view.getContext().getResources().getDisplayMetrics();
2201 try {
2202 int data = TypedValue.createComplexDimension(this.mValue, this.mUnit);
2203 switch (this.type) {
2204 case ReflectionAction.INT:
2205 return TypedValue.complexToDimensionPixelSize(data, dm);
2206 case ReflectionAction.FLOAT:
2207 return TypedValue.complexToDimension(data, dm);
2208 default:
2209 throw new ActionException(
2210 "parameter type must be INT or FLOAT, not " + this.type);
2211 }
2212 } catch (ActionException ex) {
2213 throw ex;
2214 } catch (Throwable t) {
2215 throw new ActionException(t);
2216 }
2217 }
2218
2219 @Override
2220 public int getActionTag() {
2221 return COMPLEX_UNIT_DIMENSION_REFLECTION_ACTION_TAG;
2222 }
2223 }
2224
2225 private final class NightModeReflectionAction extends BaseReflectionAction {
2226
2227 private final Object mLightValue;
2228 private final Object mDarkValue;
2229
2230 NightModeReflectionAction(
2231 @IdRes int viewId,
2232 String methodName,
2233 int type,
2234 Object lightValue,
2235 Object darkValue) {
2236 super(viewId, methodName, type);
2237 mLightValue = lightValue;
2238 mDarkValue = darkValue;
2239 }
2240
2241 NightModeReflectionAction(Parcel in) {
2242 super(in);
2243 switch (this.type) {
2244 case ICON:
2245 mLightValue = in.readTypedObject(Icon.CREATOR);
2246 mDarkValue = in.readTypedObject(Icon.CREATOR);
2247 break;
2248 case COLOR_STATE_LIST:
2249 mLightValue = in.readTypedObject(ColorStateList.CREATOR);
2250 mDarkValue = in.readTypedObject(ColorStateList.CREATOR);
2251 break;
2252 case INT:
2253 mLightValue = in.readInt();
2254 mDarkValue = in.readInt();
2255 break;
2256 default:
2257 throw new ActionException("Unexpected night mode action type: " + this.type);
2258 }
2259 }
2260
2261 @Override
2262 public void writeToParcel(Parcel out, int flags) {
2263 super.writeToParcel(out, flags);
2264 switch (this.type) {
2265 case ICON:
2266 case COLOR_STATE_LIST:
2267 out.writeTypedObject((Parcelable) mLightValue, flags);
2268 out.writeTypedObject((Parcelable) mDarkValue, flags);
2269 break;
2270 case INT:
2271 out.writeInt((int) mLightValue);
2272 out.writeInt((int) mDarkValue);
2273 break;
2274 }
2275 }
2276
2277 @Nullable
2278 @Override
2279 protected Object getParameterValue(@Nullable View view) throws ActionException {
2280 if (view == null) return null;
2281
2282 Configuration configuration = view.getResources().getConfiguration();
2283 return configuration.isNightModeActive() ? mDarkValue : mLightValue;
2284 }
2285
2286 @Override
2287 public int getActionTag() {
2288 return NIGHT_MODE_REFLECTION_ACTION_TAG;
2289 }
2290 }
2291
2292 /**
2293 * This is only used for async execution of actions and it not parcelable.
2294 */
2295 private static final class RunnableAction extends RuntimeAction {
2296 private final Runnable mRunnable;
2297
2298 RunnableAction(Runnable r) {
2299 mRunnable = r;
2300 }
2301
2302 @Override
2303 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2304 mRunnable.run();
2305 }
2306 }
2307
2308 private static boolean hasStableId(View view) {
2309 Object tag = view.getTag(com.android.internal.R.id.remote_views_stable_id);
2310 return tag != null;
2311 }
2312
2313 private static int getStableId(View view) {
2314 Integer id = (Integer) view.getTag(com.android.internal.R.id.remote_views_stable_id);
2315 return id == null ? ViewGroupActionAdd.NO_ID : id;
2316 }
2317
2318 private static void setStableId(View view, int stableId) {
2319 view.setTagInternal(com.android.internal.R.id.remote_views_stable_id, stableId);
2320 }
2321
2322 // Returns the next recyclable child of the view group, or -1 if there are none.
2323 private static int getNextRecyclableChild(ViewGroup vg) {
2324 Integer tag = (Integer) vg.getTag(com.android.internal.R.id.remote_views_next_child);
2325 return tag == null ? -1 : tag;
2326 }
2327
2328 private static int getViewLayoutId(View v) {
2329 return (Integer) v.getTag(R.id.widget_frame);
2330 }
2331
2332 private static void setNextRecyclableChild(ViewGroup vg, int nextChild, int numChildren) {
2333 if (nextChild < 0 || nextChild >= numChildren) {
2334 vg.setTagInternal(com.android.internal.R.id.remote_views_next_child, -1);
2335 } else {
2336 vg.setTagInternal(com.android.internal.R.id.remote_views_next_child, nextChild);
2337 }
2338 }
2339
2340 private void finalizeViewRecycling(ViewGroup root) {
2341 // Remove any recyclable children that were not used. nextChild should either be -1 or point
2342 // to the next recyclable child that hasn't been recycled.
2343 int nextChild = getNextRecyclableChild(root);
2344 if (nextChild >= 0 && nextChild < root.getChildCount()) {
2345 root.removeViews(nextChild, root.getChildCount() - nextChild);
2346 }
2347 // Make sure on the next round, we don't try to recycle if removeAllViews is not called.
2348 setNextRecyclableChild(root, -1, 0);
2349 // Traverse the view tree.
2350 for (int i = 0; i < root.getChildCount(); i++) {
2351 View child = root.getChildAt(i);
2352 if (child instanceof ViewGroup && !child.isRootNamespace()) {
2353 finalizeViewRecycling((ViewGroup) child);
2354 }
2355 }
2356 }
2357
2358 /**
2359 * ViewGroup methods that are related to adding Views.
2360 */
2361 private class ViewGroupActionAdd extends Action {
2362 static final int NO_ID = -1;
2363 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2364 private RemoteViews mNestedViews;
2365 private int mIndex;
2366 private int mStableId;
2367
2368 ViewGroupActionAdd(@IdRes int viewId, RemoteViews nestedViews) {
2369 this(viewId, nestedViews, -1 /* index */, NO_ID /* nestedViewId */);
2370 }
2371
2372 ViewGroupActionAdd(@IdRes int viewId, RemoteViews nestedViews, int index) {
2373 this(viewId, nestedViews, index, NO_ID /* nestedViewId */);
2374 }
2375
2376 ViewGroupActionAdd(@IdRes int viewId, RemoteViews nestedViews, int index, int stableId) {
2377 this.viewId = viewId;
2378 mNestedViews = nestedViews;
2379 mIndex = index;
2380 mStableId = stableId;
2381 nestedViews.configureAsChild(getHierarchyRootData());
2382 }
2383
2384 ViewGroupActionAdd(Parcel parcel, ApplicationInfo info, int depth) {
2385 viewId = parcel.readInt();
2386 mIndex = parcel.readInt();
2387 mStableId = parcel.readInt();
2388 mNestedViews = new RemoteViews(parcel, getHierarchyRootData(), info, depth);
2389 mNestedViews.addFlags(mApplyFlags);
2390 }
2391
2392 public void writeToParcel(Parcel dest, int flags) {
2393 dest.writeInt(viewId);
2394 dest.writeInt(mIndex);
2395 dest.writeInt(mStableId);
2396 mNestedViews.writeToParcel(dest, flags);
2397 }
2398
2399 @Override
2400 public void setHierarchyRootData(HierarchyRootData root) {
2401 mNestedViews.configureAsChild(root);
2402 }
2403
2404 private int findViewIndexToRecycle(ViewGroup target, RemoteViews newContent) {
2405 for (int nextChild = getNextRecyclableChild(target); nextChild < target.getChildCount();
2406 nextChild++) {
2407 View child = target.getChildAt(nextChild);
2408 if (getStableId(child) == mStableId) {
2409 return nextChild;
2410 }
2411 }
2412 return -1;
2413 }
2414
2415 @Override
2416 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2417 final Context context = root.getContext();
2418 final ViewGroup target = root.findViewById(viewId);
2419
2420 if (target == null) {
2421 return;
2422 }
2423
2424 // If removeAllViews was called, this returns the next potential recycled view.
2425 // If there are no more views to recycle (or removeAllViews was not called), this
2426 // will return -1.
2427 final int nextChild = getNextRecyclableChild(target);
2428 RemoteViews rvToApply = mNestedViews.getRemoteViewsToApply(context);
2429
2430 int flagsToPropagate = mApplyFlags & FLAG_MASK_TO_PROPAGATE;
2431 if (flagsToPropagate != 0) rvToApply.addFlags(flagsToPropagate);
2432
2433 if (nextChild >= 0 && mStableId != NO_ID) {
2434 // At that point, the views starting at index nextChild are the ones recyclable but
2435 // not yet recycled. All views added on that round of application are placed before.
2436 // Find the next view with the same stable id, or -1.
2437 int recycledViewIndex = findViewIndexToRecycle(target, rvToApply);
2438 if (recycledViewIndex >= 0) {
2439 View child = target.getChildAt(recycledViewIndex);
2440 if (rvToApply.canRecycleView(child)) {
2441 if (nextChild < recycledViewIndex) {
2442 target.removeViews(nextChild, recycledViewIndex - nextChild);
2443 }
2444 setNextRecyclableChild(target, nextChild + 1, target.getChildCount());
2445 rvToApply.reapplyNestedViews(context, child, rootParent, params);
2446 return;
2447 }
2448 // If we cannot recycle the views, we still remove all views in between to
2449 // avoid weird behaviors and insert the new view in place of the old one.
2450 target.removeViews(nextChild, recycledViewIndex - nextChild + 1);
2451 }
2452 }
2453 // If we cannot recycle, insert the new view before the next recyclable child.
2454
2455 // Inflate nested views and add as children
2456 View nestedView = rvToApply.apply(context, target, rootParent, null /* size */, params);
2457 if (mStableId != NO_ID) {
2458 setStableId(nestedView, mStableId);
2459 }
2460 target.addView(nestedView, mIndex >= 0 ? mIndex : nextChild);
2461 if (nextChild >= 0) {
2462 // If we are at the end, there is no reason to try to recycle anymore
2463 setNextRecyclableChild(target, nextChild + 1, target.getChildCount());
2464 }
2465 }
2466
2467 @Override
2468 public Action initActionAsync(ViewTree root, ViewGroup rootParent,
2469 ActionApplyParams params) {
2470 // In the async implementation, update the view tree so that subsequent calls to
2471 // findViewById return the current view.
2472 root.createTree();
2473 ViewTree target = root.findViewTreeById(viewId);
2474 if ((target == null) || !(target.mRoot instanceof ViewGroup)) {
2475 return ACTION_NOOP;
2476 }
2477 final ViewGroup targetVg = (ViewGroup) target.mRoot;
2478
2479 // Inflate nested views and perform all the async tasks for the child remoteView.
2480 final Context context = root.mRoot.getContext();
2481
2482 // If removeAllViews was called, this returns the next potential recycled view.
2483 // If there are no more views to recycle (or removeAllViews was not called), this
2484 // will return -1.
2485 final int nextChild = getNextRecyclableChild(targetVg);
2486 if (nextChild >= 0 && mStableId != NO_ID) {
2487 RemoteViews rvToApply = mNestedViews.getRemoteViewsToApply(context);
2488 final int recycledViewIndex = target.findChildIndex(nextChild,
2489 view -> getStableId(view) == mStableId);
2490 if (recycledViewIndex >= 0) {
2491 // At that point, the views starting at index nextChild are the ones
2492 // recyclable but not yet recycled. All views added on that round of
2493 // application are placed before.
2494 ViewTree recycled = target.mChildren.get(recycledViewIndex);
2495 // We can only recycle the view if the layout id is the same.
2496 if (rvToApply.canRecycleView(recycled.mRoot)) {
2497 if (recycledViewIndex > nextChild) {
2498 target.removeChildren(nextChild, recycledViewIndex - nextChild);
2499 }
2500 setNextRecyclableChild(targetVg, nextChild + 1, target.mChildren.size());
2501 final AsyncApplyTask reapplyTask = rvToApply.getInternalAsyncApplyTask(
2502 context,
2503 targetVg, null /* listener */, params, null /* size */,
2504 recycled.mRoot);
2505 final ViewTree tree = reapplyTask.doInBackground();
2506 if (tree == null) {
2507 throw new ActionException(reapplyTask.mError);
2508 }
2509 return new RuntimeAction() {
2510 @Override
2511 public void apply(View root, ViewGroup rootParent,
2512 ActionApplyParams params) throws ActionException {
2513 reapplyTask.onPostExecute(tree);
2514 if (recycledViewIndex > nextChild) {
2515 targetVg.removeViews(nextChild, recycledViewIndex - nextChild);
2516 }
2517 }
2518 };
2519 }
2520 // If the layout id is different, still remove the children as if we recycled
2521 // the view, to insert at the same place.
2522 target.removeChildren(nextChild, recycledViewIndex - nextChild + 1);
2523 return insertNewView(context, target, params,
2524 () -> targetVg.removeViews(nextChild,
2525 recycledViewIndex - nextChild + 1));
2526
2527 }
2528 }
2529 // If we cannot recycle, simply add the view at the same available slot.
2530 return insertNewView(context, target, params, () -> {});
2531 }
2532
2533 private Action insertNewView(Context context, ViewTree target,
2534 ActionApplyParams params, Runnable finalizeAction) {
2535 ViewGroup targetVg = (ViewGroup) target.mRoot;
2536 int nextChild = getNextRecyclableChild(targetVg);
2537 final AsyncApplyTask task = mNestedViews.getInternalAsyncApplyTask(context, targetVg,
2538 null /* listener */, params, null /* size */, null /* result */);
2539 final ViewTree tree = task.doInBackground();
2540
2541 if (tree == null) {
2542 throw new ActionException(task.mError);
2543 }
2544 if (mStableId != NO_ID) {
2545 setStableId(task.mResult, mStableId);
2546 }
2547
2548 // Update the global view tree, so that next call to findViewTreeById
2549 // goes through the subtree as well.
2550 final int insertIndex = mIndex >= 0 ? mIndex : nextChild;
2551 target.addChild(tree, insertIndex);
2552 if (nextChild >= 0) {
2553 setNextRecyclableChild(targetVg, nextChild + 1, target.mChildren.size());
2554 }
2555
2556 return new RuntimeAction() {
2557 @Override
2558 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2559 task.onPostExecute(tree);
2560 finalizeAction.run();
2561 targetVg.addView(task.mResult, insertIndex);
2562 }
2563 };
2564 }
2565
2566 @Override
2567 public int mergeBehavior() {
2568 return MERGE_APPEND;
2569 }
2570
2571 @Override
2572 public boolean prefersAsyncApply() {
2573 return mNestedViews.prefersAsyncApply();
2574 }
2575
2576 @Override
2577 public int getActionTag() {
2578 return VIEW_GROUP_ACTION_ADD_TAG;
2579 }
2580 }
2581
2582 /**
2583 * ViewGroup methods related to removing child views.
2584 */
2585 private class ViewGroupActionRemove extends Action {
2586 /**
2587 * Id that indicates that all child views of the affected ViewGroup should be removed.
2588 *
2589 * <p>Using -2 because the default id is -1. This avoids accidentally matching that.
2590 */
2591 private static final int REMOVE_ALL_VIEWS_ID = -2;
2592
2593 private int mViewIdToKeep;
2594
2595 ViewGroupActionRemove(@IdRes int viewId) {
2596 this(viewId, REMOVE_ALL_VIEWS_ID);
2597 }
2598
2599 ViewGroupActionRemove(@IdRes int viewId, @IdRes int viewIdToKeep) {
2600 this.viewId = viewId;
2601 mViewIdToKeep = viewIdToKeep;
2602 }
2603
2604 ViewGroupActionRemove(Parcel parcel) {
2605 viewId = parcel.readInt();
2606 mViewIdToKeep = parcel.readInt();
2607 }
2608
2609 public void writeToParcel(Parcel dest, int flags) {
2610 dest.writeInt(viewId);
2611 dest.writeInt(mViewIdToKeep);
2612 }
2613
2614 @Override
2615 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2616 final ViewGroup target = root.findViewById(viewId);
2617
2618 if (target == null) {
2619 return;
2620 }
2621
2622 if (mViewIdToKeep == REMOVE_ALL_VIEWS_ID) {
2623 // Remote any view without a stable id
2624 for (int i = target.getChildCount() - 1; i >= 0; i--) {
2625 if (!hasStableId(target.getChildAt(i))) {
2626 target.removeViewAt(i);
2627 }
2628 }
2629 // In the end, only children with a stable id (i.e. recyclable) are left.
2630 setNextRecyclableChild(target, 0, target.getChildCount());
2631 return;
2632 }
2633
2634 removeAllViewsExceptIdToKeep(target);
2635 }
2636
2637 @Override
2638 public Action initActionAsync(ViewTree root, ViewGroup rootParent,
2639 ActionApplyParams params) {
2640 // In the async implementation, update the view tree so that subsequent calls to
2641 // findViewById return the current view.
2642 root.createTree();
2643 ViewTree target = root.findViewTreeById(viewId);
2644
2645 if ((target == null) || !(target.mRoot instanceof ViewGroup)) {
2646 return ACTION_NOOP;
2647 }
2648
2649 final ViewGroup targetVg = (ViewGroup) target.mRoot;
2650
2651 if (mViewIdToKeep == REMOVE_ALL_VIEWS_ID) {
2652 target.mChildren.removeIf(childTree -> !hasStableId(childTree.mRoot));
2653 setNextRecyclableChild(targetVg, 0, target.mChildren.size());
2654 } else {
2655 // Remove just the children which don't match the excepted view
2656 target.mChildren.removeIf(childTree -> childTree.mRoot.getId() != mViewIdToKeep);
2657 if (target.mChildren.isEmpty()) {
2658 target.mChildren = null;
2659 }
2660 }
2661 return new RuntimeAction() {
2662 @Override
2663 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2664 if (mViewIdToKeep == REMOVE_ALL_VIEWS_ID) {
2665 for (int i = targetVg.getChildCount() - 1; i >= 0; i--) {
2666 if (!hasStableId(targetVg.getChildAt(i))) {
2667 targetVg.removeViewAt(i);
2668 }
2669 }
2670 return;
2671 }
2672
2673 removeAllViewsExceptIdToKeep(targetVg);
2674 }
2675 };
2676 }
2677
2678 /**
2679 * Iterates through the children in the given ViewGroup and removes all the views that
2680 * do not have an id of {@link #mViewIdToKeep}.
2681 */
2682 private void removeAllViewsExceptIdToKeep(ViewGroup viewGroup) {
2683 // Otherwise, remove all the views that do not match the id to keep.
2684 int index = viewGroup.getChildCount() - 1;
2685 while (index >= 0) {
2686 if (viewGroup.getChildAt(index).getId() != mViewIdToKeep) {
2687 viewGroup.removeViewAt(index);
2688 }
2689 index--;
2690 }
2691 }
2692
2693 @Override
2694 public int getActionTag() {
2695 return VIEW_GROUP_ACTION_REMOVE_TAG;
2696 }
2697
2698 @Override
2699 public int mergeBehavior() {
2700 return MERGE_APPEND;
2701 }
2702 }
2703
2704 /**
2705 * Action to remove a view from its parent.
2706 */
2707 private class RemoveFromParentAction extends Action {
2708
2709 RemoveFromParentAction(@IdRes int viewId) {
2710 this.viewId = viewId;
2711 }
2712
2713 RemoveFromParentAction(Parcel parcel) {
2714 viewId = parcel.readInt();
2715 }
2716
2717 public void writeToParcel(Parcel dest, int flags) {
2718 dest.writeInt(viewId);
2719 }
2720
2721 @Override
2722 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2723 final View target = root.findViewById(viewId);
2724
2725 if (target == null || target == root) {
2726 return;
2727 }
2728
2729 ViewParent parent = target.getParent();
2730 if (parent instanceof ViewManager) {
2731 ((ViewManager) parent).removeView(target);
2732 }
2733 }
2734
2735 @Override
2736 public Action initActionAsync(ViewTree root, ViewGroup rootParent,
2737 ActionApplyParams params) {
2738 // In the async implementation, update the view tree so that subsequent calls to
2739 // findViewById return the correct view.
2740 root.createTree();
2741 ViewTree target = root.findViewTreeById(viewId);
2742
2743 if (target == null || target == root) {
2744 return ACTION_NOOP;
2745 }
2746
2747 ViewTree parent = root.findViewTreeParentOf(target);
2748 if (parent == null || !(parent.mRoot instanceof ViewManager)) {
2749 return ACTION_NOOP;
2750 }
2751 final ViewManager parentVg = (ViewManager) parent.mRoot;
2752
2753 parent.mChildren.remove(target);
2754 return new RuntimeAction() {
2755 @Override
2756 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2757 parentVg.removeView(target.mRoot);
2758 }
2759 };
2760 }
2761
2762 @Override
2763 public int getActionTag() {
2764 return REMOVE_FROM_PARENT_ACTION_TAG;
2765 }
2766
2767 @Override
2768 public int mergeBehavior() {
2769 return MERGE_APPEND;
2770 }
2771 }
2772
2773 /**
2774 * Helper action to set compound drawables on a TextView. Supports relative
2775 * (s/t/e/b) or cardinal (l/t/r/b) arrangement.
2776 */
2777 private class TextViewDrawableAction extends Action {
2778 public TextViewDrawableAction(@IdRes int viewId, boolean isRelative, @DrawableRes int d1,
2779 @DrawableRes int d2, @DrawableRes int d3, @DrawableRes int d4) {
2780 this.viewId = viewId;
2781 this.isRelative = isRelative;
2782 this.useIcons = false;
2783 this.d1 = d1;
2784 this.d2 = d2;
2785 this.d3 = d3;
2786 this.d4 = d4;
2787 }
2788
2789 public TextViewDrawableAction(@IdRes int viewId, boolean isRelative,
2790 Icon i1, Icon i2, Icon i3, Icon i4) {
2791 this.viewId = viewId;
2792 this.isRelative = isRelative;
2793 this.useIcons = true;
2794 this.i1 = i1;
2795 this.i2 = i2;
2796 this.i3 = i3;
2797 this.i4 = i4;
2798 }
2799
2800 public TextViewDrawableAction(Parcel parcel) {
2801 viewId = parcel.readInt();
2802 isRelative = (parcel.readInt() != 0);
2803 useIcons = (parcel.readInt() != 0);
2804 if (useIcons) {
2805 i1 = parcel.readTypedObject(Icon.CREATOR);
2806 i2 = parcel.readTypedObject(Icon.CREATOR);
2807 i3 = parcel.readTypedObject(Icon.CREATOR);
2808 i4 = parcel.readTypedObject(Icon.CREATOR);
2809 } else {
2810 d1 = parcel.readInt();
2811 d2 = parcel.readInt();
2812 d3 = parcel.readInt();
2813 d4 = parcel.readInt();
2814 }
2815 }
2816
2817 public void writeToParcel(Parcel dest, int flags) {
2818 dest.writeInt(viewId);
2819 dest.writeInt(isRelative ? 1 : 0);
2820 dest.writeInt(useIcons ? 1 : 0);
2821 if (useIcons) {
2822 dest.writeTypedObject(i1, 0);
2823 dest.writeTypedObject(i2, 0);
2824 dest.writeTypedObject(i3, 0);
2825 dest.writeTypedObject(i4, 0);
2826 } else {
2827 dest.writeInt(d1);
2828 dest.writeInt(d2);
2829 dest.writeInt(d3);
2830 dest.writeInt(d4);
2831 }
2832 }
2833
2834 @Override
2835 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2836 final TextView target = root.findViewById(viewId);
2837 if (target == null) return;
2838 if (drawablesLoaded) {
2839 if (isRelative) {
2840 target.setCompoundDrawablesRelativeWithIntrinsicBounds(id1, id2, id3, id4);
2841 } else {
2842 target.setCompoundDrawablesWithIntrinsicBounds(id1, id2, id3, id4);
2843 }
2844 } else if (useIcons) {
2845 final Context ctx = target.getContext();
2846 final Drawable id1 = i1 == null ? null : i1.loadDrawable(ctx);
2847 final Drawable id2 = i2 == null ? null : i2.loadDrawable(ctx);
2848 final Drawable id3 = i3 == null ? null : i3.loadDrawable(ctx);
2849 final Drawable id4 = i4 == null ? null : i4.loadDrawable(ctx);
2850 if (isRelative) {
2851 target.setCompoundDrawablesRelativeWithIntrinsicBounds(id1, id2, id3, id4);
2852 } else {
2853 target.setCompoundDrawablesWithIntrinsicBounds(id1, id2, id3, id4);
2854 }
2855 } else {
2856 if (isRelative) {
2857 target.setCompoundDrawablesRelativeWithIntrinsicBounds(d1, d2, d3, d4);
2858 } else {
2859 target.setCompoundDrawablesWithIntrinsicBounds(d1, d2, d3, d4);
2860 }
2861 }
2862 }
2863
2864 @Override
2865 public Action initActionAsync(ViewTree root, ViewGroup rootParent,
2866 ActionApplyParams params) {
2867 final TextView target = root.findViewById(viewId);
2868 if (target == null) return ACTION_NOOP;
2869
2870 TextViewDrawableAction copy = useIcons ?
2871 new TextViewDrawableAction(viewId, isRelative, i1, i2, i3, i4) :
2872 new TextViewDrawableAction(viewId, isRelative, d1, d2, d3, d4);
2873
2874 // Load the drawables on the background thread.
2875 copy.drawablesLoaded = true;
2876 final Context ctx = target.getContext();
2877
2878 if (useIcons) {
2879 copy.id1 = i1 == null ? null : i1.loadDrawable(ctx);
2880 copy.id2 = i2 == null ? null : i2.loadDrawable(ctx);
2881 copy.id3 = i3 == null ? null : i3.loadDrawable(ctx);
2882 copy.id4 = i4 == null ? null : i4.loadDrawable(ctx);
2883 } else {
2884 copy.id1 = d1 == 0 ? null : ctx.getDrawable(d1);
2885 copy.id2 = d2 == 0 ? null : ctx.getDrawable(d2);
2886 copy.id3 = d3 == 0 ? null : ctx.getDrawable(d3);
2887 copy.id4 = d4 == 0 ? null : ctx.getDrawable(d4);
2888 }
2889 return copy;
2890 }
2891
2892 @Override
2893 public boolean prefersAsyncApply() {
2894 return useIcons;
2895 }
2896
2897 @Override
2898 public int getActionTag() {
2899 return TEXT_VIEW_DRAWABLE_ACTION_TAG;
2900 }
2901
2902 @Override
2903 public void visitUris(@NonNull Consumer<Uri> visitor) {
2904 if (useIcons) {
2905 visitIconUri(i1, visitor);
2906 visitIconUri(i2, visitor);
2907 visitIconUri(i3, visitor);
2908 visitIconUri(i4, visitor);
2909 }
2910 }
2911
2912 boolean isRelative = false;
2913 boolean useIcons = false;
2914 int d1, d2, d3, d4;
2915 Icon i1, i2, i3, i4;
2916
2917 boolean drawablesLoaded = false;
2918 Drawable id1, id2, id3, id4;
2919 }
2920
2921 /**
2922 * Helper action to set text size on a TextView in any supported units.
2923 */
2924 private class TextViewSizeAction extends Action {
2925 TextViewSizeAction(@IdRes int viewId, @ComplexDimensionUnit int units, float size) {
2926 this.viewId = viewId;
2927 this.units = units;
2928 this.size = size;
2929 }
2930
2931 TextViewSizeAction(Parcel parcel) {
2932 viewId = parcel.readInt();
2933 units = parcel.readInt();
2934 size = parcel.readFloat();
2935 }
2936
2937 public void writeToParcel(Parcel dest, int flags) {
2938 dest.writeInt(viewId);
2939 dest.writeInt(units);
2940 dest.writeFloat(size);
2941 }
2942
2943 @Override
2944 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2945 final TextView target = root.findViewById(viewId);
2946 if (target == null) return;
2947 target.setTextSize(units, size);
2948 }
2949
2950 @Override
2951 public int getActionTag() {
2952 return TEXT_VIEW_SIZE_ACTION_TAG;
2953 }
2954
2955 int units;
2956 float size;
2957 }
2958
2959 /**
2960 * Helper action to set padding on a View.
2961 */
2962 private class ViewPaddingAction extends Action {
2963 public ViewPaddingAction(@IdRes int viewId, @Px int left, @Px int top,
2964 @Px int right, @Px int bottom) {
2965 this.viewId = viewId;
2966 this.left = left;
2967 this.top = top;
2968 this.right = right;
2969 this.bottom = bottom;
2970 }
2971
2972 public ViewPaddingAction(Parcel parcel) {
2973 viewId = parcel.readInt();
2974 left = parcel.readInt();
2975 top = parcel.readInt();
2976 right = parcel.readInt();
2977 bottom = parcel.readInt();
2978 }
2979
2980 public void writeToParcel(Parcel dest, int flags) {
2981 dest.writeInt(viewId);
2982 dest.writeInt(left);
2983 dest.writeInt(top);
2984 dest.writeInt(right);
2985 dest.writeInt(bottom);
2986 }
2987
2988 @Override
2989 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
2990 final View target = root.findViewById(viewId);
2991 if (target == null) return;
2992 target.setPadding(left, top, right, bottom);
2993 }
2994
2995 @Override
2996 public int getActionTag() {
2997 return VIEW_PADDING_ACTION_TAG;
2998 }
2999
3000 @Px int left, top, right, bottom;
3001 }
3002
3003 /**
3004 * Helper action to set layout params on a View.
3005 */
3006 private static class LayoutParamAction extends Action {
3007
3008 static final int LAYOUT_MARGIN_LEFT = MARGIN_LEFT;
3009 static final int LAYOUT_MARGIN_TOP = MARGIN_TOP;
3010 static final int LAYOUT_MARGIN_RIGHT = MARGIN_RIGHT;
3011 static final int LAYOUT_MARGIN_BOTTOM = MARGIN_BOTTOM;
3012 static final int LAYOUT_MARGIN_START = MARGIN_START;
3013 static final int LAYOUT_MARGIN_END = MARGIN_END;
3014 static final int LAYOUT_WIDTH = 8;
3015 static final int LAYOUT_HEIGHT = 9;
3016
3017 final int mProperty;
3018 final int mValueType;
3019 final int mValue;
3020
3021 /**
3022 * @param viewId ID of the view alter
3023 * @param property which layout parameter to alter
3024 * @param value new value of the layout parameter
3025 * @param units the units of the given value
3026 */
3027 LayoutParamAction(@IdRes int viewId, int property, float value,
3028 @ComplexDimensionUnit int units) {
3029 this.viewId = viewId;
3030 this.mProperty = property;
3031 this.mValueType = VALUE_TYPE_COMPLEX_UNIT;
3032 this.mValue = TypedValue.createComplexDimension(value, units);
3033 }
3034
3035 /**
3036 * @param viewId ID of the view alter
3037 * @param property which layout parameter to alter
3038 * @param value value to set.
3039 * @param valueType must be one of {@link #VALUE_TYPE_COMPLEX_UNIT},
3040 * {@link #VALUE_TYPE_RESOURCE}, {@link #VALUE_TYPE_ATTRIBUTE} or
3041 * {@link #VALUE_TYPE_RAW}.
3042 */
3043 LayoutParamAction(@IdRes int viewId, int property, int value, @ValueType int valueType) {
3044 this.viewId = viewId;
3045 this.mProperty = property;
3046 this.mValueType = valueType;
3047 this.mValue = value;
3048 }
3049
3050 public LayoutParamAction(Parcel parcel) {
3051 viewId = parcel.readInt();
3052 mProperty = parcel.readInt();
3053 mValueType = parcel.readInt();
3054 mValue = parcel.readInt();
3055 }
3056
3057 public void writeToParcel(Parcel dest, int flags) {
3058 dest.writeInt(viewId);
3059 dest.writeInt(mProperty);
3060 dest.writeInt(mValueType);
3061 dest.writeInt(mValue);
3062 }
3063
3064 @Override
3065 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
3066 final View target = root.findViewById(viewId);
3067 if (target == null) {
3068 return;
3069 }
3070 ViewGroup.LayoutParams layoutParams = target.getLayoutParams();
3071 if (layoutParams == null) {
3072 return;
3073 }
3074 switch (mProperty) {
3075 case LAYOUT_MARGIN_LEFT:
3076 if (layoutParams instanceof MarginLayoutParams) {
3077 ((MarginLayoutParams) layoutParams).leftMargin = getPixelOffset(target);
3078 target.setLayoutParams(layoutParams);
3079 }
3080 break;
3081 case LAYOUT_MARGIN_TOP:
3082 if (layoutParams instanceof MarginLayoutParams) {
3083 ((MarginLayoutParams) layoutParams).topMargin = getPixelOffset(target);
3084 target.setLayoutParams(layoutParams);
3085 }
3086 break;
3087 case LAYOUT_MARGIN_RIGHT:
3088 if (layoutParams instanceof MarginLayoutParams) {
3089 ((MarginLayoutParams) layoutParams).rightMargin = getPixelOffset(target);
3090 target.setLayoutParams(layoutParams);
3091 }
3092 break;
3093 case LAYOUT_MARGIN_BOTTOM:
3094 if (layoutParams instanceof MarginLayoutParams) {
3095 ((MarginLayoutParams) layoutParams).bottomMargin = getPixelOffset(target);
3096 target.setLayoutParams(layoutParams);
3097 }
3098 break;
3099 case LAYOUT_MARGIN_START:
3100 if (layoutParams instanceof MarginLayoutParams) {
3101 ((MarginLayoutParams) layoutParams).setMarginStart(getPixelOffset(target));
3102 target.setLayoutParams(layoutParams);
3103 }
3104 break;
3105 case LAYOUT_MARGIN_END:
3106 if (layoutParams instanceof MarginLayoutParams) {
3107 ((MarginLayoutParams) layoutParams).setMarginEnd(getPixelOffset(target));
3108 target.setLayoutParams(layoutParams);
3109 }
3110 break;
3111 case LAYOUT_WIDTH:
3112 layoutParams.width = getPixelSize(target);
3113 target.setLayoutParams(layoutParams);
3114 break;
3115 case LAYOUT_HEIGHT:
3116 layoutParams.height = getPixelSize(target);
3117 target.setLayoutParams(layoutParams);
3118 break;
3119 default:
3120 throw new IllegalArgumentException("Unknown property " + mProperty);
3121 }
3122 }
3123
3124 private int getPixelOffset(View target) {
3125 try {
3126 switch (mValueType) {
3127 case VALUE_TYPE_ATTRIBUTE:
3128 TypedArray typedArray = target.getContext().obtainStyledAttributes(
3129 new int[]{this.mValue});
3130 try {
3131 return typedArray.getDimensionPixelOffset(0, 0);
3132 } finally {
3133 typedArray.recycle();
3134 }
3135 case VALUE_TYPE_RESOURCE:
3136 if (mValue == 0) {
3137 return 0;
3138 }
3139 return target.getResources().getDimensionPixelOffset(mValue);
3140 case VALUE_TYPE_COMPLEX_UNIT:
3141 return TypedValue.complexToDimensionPixelOffset(mValue,
3142 target.getResources().getDisplayMetrics());
3143 default:
3144 return mValue;
3145 }
3146 } catch (Throwable t) {
3147 throw new ActionException(t);
3148 }
3149 }
3150
3151 private int getPixelSize(View target) {
3152 try {
3153 switch (mValueType) {
3154 case VALUE_TYPE_ATTRIBUTE:
3155 TypedArray typedArray = target.getContext().obtainStyledAttributes(
3156 new int[]{this.mValue});
3157 try {
3158 return typedArray.getDimensionPixelSize(0, 0);
3159 } finally {
3160 typedArray.recycle();
3161 }
3162 case VALUE_TYPE_RESOURCE:
3163 if (mValue == 0) {
3164 return 0;
3165 }
3166 return target.getResources().getDimensionPixelSize(mValue);
3167 case VALUE_TYPE_COMPLEX_UNIT:
3168 return TypedValue.complexToDimensionPixelSize(mValue,
3169 target.getResources().getDisplayMetrics());
3170 default:
3171 return mValue;
3172 }
3173 } catch (Throwable t) {
3174 throw new ActionException(t);
3175 }
3176 }
3177
3178 @Override
3179 public int getActionTag() {
3180 return LAYOUT_PARAM_ACTION_TAG;
3181 }
3182
3183 @Override
3184 public String getUniqueKey() {
3185 return super.getUniqueKey() + mProperty;
3186 }
3187 }
3188
3189 /**
3190 * Helper action to add a view tag with RemoteInputs.
3191 */
3192 private class SetRemoteInputsAction extends Action {
3193
3194 public SetRemoteInputsAction(@IdRes int viewId, RemoteInput[] remoteInputs) {
3195 this.viewId = viewId;
3196 this.remoteInputs = remoteInputs;
3197 }
3198
3199 public SetRemoteInputsAction(Parcel parcel) {
3200 viewId = parcel.readInt();
3201 remoteInputs = parcel.createTypedArray(RemoteInput.CREATOR);
3202 }
3203
3204 public void writeToParcel(Parcel dest, int flags) {
3205 dest.writeInt(viewId);
3206 dest.writeTypedArray(remoteInputs, flags);
3207 }
3208
3209 @Override
3210 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
3211 final View target = root.findViewById(viewId);
3212 if (target == null) return;
3213
3214 target.setTagInternal(R.id.remote_input_tag, remoteInputs);
3215 }
3216
3217 @Override
3218 public int getActionTag() {
3219 return SET_REMOTE_INPUTS_ACTION_TAG;
3220 }
3221
3222 final Parcelable[] remoteInputs;
3223 }
3224
3225 /**
3226 * Helper action to override all textViewColors
3227 */
3228 private class OverrideTextColorsAction extends Action {
3229
3230 private final int textColor;
3231
3232 public OverrideTextColorsAction(int textColor) {
3233 this.textColor = textColor;
3234 }
3235
3236 public OverrideTextColorsAction(Parcel parcel) {
3237 textColor = parcel.readInt();
3238 }
3239
3240 public void writeToParcel(Parcel dest, int flags) {
3241 dest.writeInt(textColor);
3242 }
3243
3244 @Override
3245 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
3246 // Let's traverse the viewtree and override all textColors!
3247 Stack<View> viewsToProcess = new Stack<>();
3248 viewsToProcess.add(root);
3249 while (!viewsToProcess.isEmpty()) {
3250 View v = viewsToProcess.pop();
3251 if (v instanceof TextView) {
3252 TextView textView = (TextView) v;
3253 textView.setText(ContrastColorUtil.clearColorSpans(textView.getText()));
3254 textView.setTextColor(textColor);
3255 }
3256 if (v instanceof ViewGroup) {
3257 ViewGroup viewGroup = (ViewGroup) v;
3258 for (int i = 0; i < viewGroup.getChildCount(); i++) {
3259 viewsToProcess.push(viewGroup.getChildAt(i));
3260 }
3261 }
3262 }
3263 }
3264
3265 @Override
3266 public int getActionTag() {
3267 return OVERRIDE_TEXT_COLORS_TAG;
3268 }
3269 }
3270
3271 private class SetIntTagAction extends Action {
3272 @IdRes private final int mViewId;
3273 @IdRes private final int mKey;
3274 private final int mTag;
3275
3276 SetIntTagAction(@IdRes int viewId, @IdRes int key, int tag) {
3277 mViewId = viewId;
3278 mKey = key;
3279 mTag = tag;
3280 }
3281
3282 SetIntTagAction(Parcel parcel) {
3283 mViewId = parcel.readInt();
3284 mKey = parcel.readInt();
3285 mTag = parcel.readInt();
3286 }
3287
3288 public void writeToParcel(Parcel dest, int flags) {
3289 dest.writeInt(mViewId);
3290 dest.writeInt(mKey);
3291 dest.writeInt(mTag);
3292 }
3293
3294 @Override
3295 public void apply(View root, ViewGroup rootParent, ActionApplyParams params) {
3296 final View target = root.findViewById(mViewId);
3297 if (target == null) return;
3298
3299 target.setTagInternal(mKey, mTag);
3300 }
3301
3302 @Override
3303 public int getActionTag() {
3304 return SET_INT_TAG_TAG;
3305 }
3306 }
3307
3308 private static class SetCompoundButtonCheckedAction extends Action {
3309
3310 private final boolean mChecked;
3311
3312 SetCompoundButtonCheckedAction(@IdRes int viewId, boolean checked) {
3313 this.viewId = viewId;
3314 mChecked = checked;
3315 }
3316
3317 SetCompoundButtonCheckedAction(Parcel in) {
3318 viewId = in.readInt();
3319 mChecked = in.readBoolean();
3320 }
3321
3322 @Override
3323 public void writeToParcel(Parcel dest, int flags) {
3324 dest.writeInt(viewId);
3325 dest.writeBoolean(mChecked);
3326 }
3327
3328 @Override
3329 public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
3330 throws ActionException {
3331 final View target = root.findViewById(viewId);
3332 if (target == null) return;
3333
3334 if (!(target instanceof CompoundButton)) {
3335 Log.w(LOG_TAG, "Cannot set checked to view "
3336 + viewId + " because it is not a CompoundButton");
3337 return;
3338 }
3339
3340 CompoundButton button = (CompoundButton) target;
3341 Object tag = button.getTag(R.id.remote_checked_change_listener_tag);
3342 // Temporarily unset the checked change listener so calling setChecked doesn't launch
3343 // the intent.
3344 if (tag instanceof OnCheckedChangeListener) {
3345 button.setOnCheckedChangeListener(null);
3346 button.setChecked(mChecked);
3347 button.setOnCheckedChangeListener((OnCheckedChangeListener) tag);
3348 } else {
3349 button.setChecked(mChecked);
3350 }
3351 }
3352
3353 @Override
3354 public int getActionTag() {
3355 return SET_COMPOUND_BUTTON_CHECKED_TAG;
3356 }
3357 }
3358
3359 private static class SetRadioGroupCheckedAction extends Action {
3360
3361 @IdRes private final int mCheckedId;
3362
3363 SetRadioGroupCheckedAction(@IdRes int viewId, @IdRes int checkedId) {
3364 this.viewId = viewId;
3365 mCheckedId = checkedId;
3366 }
3367
3368 SetRadioGroupCheckedAction(Parcel in) {
3369 viewId = in.readInt();
3370 mCheckedId = in.readInt();
3371 }
3372
3373 @Override
3374 public void writeToParcel(Parcel dest, int flags) {
3375 dest.writeInt(viewId);
3376 dest.writeInt(mCheckedId);
3377 }
3378
3379 @Override
3380 public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
3381 throws ActionException {
3382 final View target = root.findViewById(viewId);
3383 if (target == null) return;
3384
3385 if (!(target instanceof RadioGroup)) {
3386 Log.w(LOG_TAG, "Cannot check " + viewId + " because it's not a RadioGroup");
3387 return;
3388 }
3389
3390 RadioGroup group = (RadioGroup) target;
3391
3392 // Temporarily unset all the checked change listeners while we check the group.
3393 for (int i = 0; i < group.getChildCount(); i++) {
3394 View child = group.getChildAt(i);
3395 if (!(child instanceof CompoundButton)) continue;
3396
3397 Object tag = child.getTag(R.id.remote_checked_change_listener_tag);
3398 if (!(tag instanceof OnCheckedChangeListener)) continue;
3399
3400 // Clear the checked change listener, we'll restore it after the check.
3401 ((CompoundButton) child).setOnCheckedChangeListener(null);
3402 }
3403
3404 group.check(mCheckedId);
3405
3406 // Loop through the children again and restore the checked change listeners.
3407 for (int i = 0; i < group.getChildCount(); i++) {
3408 View child = group.getChildAt(i);
3409 if (!(child instanceof CompoundButton)) continue;
3410
3411 Object tag = child.getTag(R.id.remote_checked_change_listener_tag);
3412 if (!(tag instanceof OnCheckedChangeListener)) continue;
3413
3414 ((CompoundButton) child).setOnCheckedChangeListener((OnCheckedChangeListener) tag);
3415 }
3416 }
3417
3418 @Override
3419 public int getActionTag() {
3420 return SET_RADIO_GROUP_CHECKED;
3421 }
3422 }
3423
3424 private static class SetViewOutlinePreferredRadiusAction extends Action {
3425
3426 @ValueType
3427 private final int mValueType;
3428 private final int mValue;
3429
3430 SetViewOutlinePreferredRadiusAction(@IdRes int viewId, int value,
3431 @ValueType int valueType) {
3432 this.viewId = viewId;
3433 this.mValueType = valueType;
3434 this.mValue = value;
3435 }
3436
3437 SetViewOutlinePreferredRadiusAction(
3438 @IdRes int viewId, float radius, @ComplexDimensionUnit int units) {
3439 this.viewId = viewId;
3440 this.mValueType = VALUE_TYPE_COMPLEX_UNIT;
3441 this.mValue = TypedValue.createComplexDimension(radius, units);
3442
3443 }
3444
3445 SetViewOutlinePreferredRadiusAction(Parcel in) {
3446 viewId = in.readInt();
3447 mValueType = in.readInt();
3448 mValue = in.readInt();
3449 }
3450
3451 @Override
3452 public void writeToParcel(Parcel dest, int flags) {
3453 dest.writeInt(viewId);
3454 dest.writeInt(mValueType);
3455 dest.writeInt(mValue);
3456 }
3457
3458 @Override
3459 public void apply(View root, ViewGroup rootParent, ActionApplyParams params)
3460 throws ActionException {
3461 final View target = root.findViewById(viewId);
3462 if (target == null) return;
3463
3464 try {
3465 float radius;
3466 switch (mValueType) {
3467 case VALUE_TYPE_ATTRIBUTE:
3468 TypedArray typedArray = target.getContext().obtainStyledAttributes(
3469 new int[]{mValue});
3470 try {
3471 radius = typedArray.getDimension(0, 0);
3472 } finally {
3473 typedArray.recycle();
3474 }
3475 break;
3476 case VALUE_TYPE_RESOURCE:
3477 radius = mValue == 0 ? 0 : target.getResources().getDimension(mValue);
3478 break;
3479 case VALUE_TYPE_COMPLEX_UNIT:
3480 radius = TypedValue.complexToDimension(mValue,
3481 target.getResources().getDisplayMetrics());
3482 break;
3483 default:
3484 radius = mValue;
3485 }
3486 target.setOutlineProvider(new RemoteViewOutlineProvider(radius));
3487 } catch (Throwable t) {
3488 throw new ActionException(t);
3489 }
3490 }
3491
3492 @Override
3493 public int getActionTag() {
3494 return SET_VIEW_OUTLINE_RADIUS_TAG;
3495 }
3496 }
3497
3498 /**
3499 * OutlineProvider for a view with a radius set by
3500 * {@link #setViewOutlinePreferredRadius(int, float, int)}.
3501 */
3502 public static final class RemoteViewOutlineProvider extends ViewOutlineProvider {
3503
3504 private final float mRadius;
3505
3506 public RemoteViewOutlineProvider(float radius) {
3507 mRadius = radius;
3508 }
3509
3510 /** Returns the corner radius used when providing the view outline. */
3511 public float getRadius() {
3512 return mRadius;
3513 }
3514
3515 @Override
3516 public void getOutline(@NonNull View view, @NonNull Outline outline) {
3517 outline.setRoundRect(
3518 0 /*left*/,
3519 0 /* top */,
3520 view.getWidth() /* right */,
3521 view.getHeight() /* bottom */,
3522 mRadius);
3523 }
3524 }
3525
3526 /**
3527 * Create a new RemoteViews object that will display the views contained
3528 * in the specified layout file.
3529 *
3530 * @param packageName Name of the package that contains the layout resource
3531 * @param layoutId The id of the layout resource
3532 */
3533 public RemoteViews(String packageName, int layoutId) {
3534 this(getApplicationInfo(packageName, UserHandle.myUserId()), layoutId);
3535 }
3536
3537 /**
3538 * Create a new RemoteViews object that will display the views contained
3539 * in the specified layout file and change the id of the root view to the specified one.
3540 *
3541 * @param packageName Name of the package that contains the layout resource
3542 * @param layoutId The id of the layout resource
3543 */
3544 public RemoteViews(@NonNull String packageName, @LayoutRes int layoutId, @IdRes int viewId) {
3545 this(packageName, layoutId);
3546 this.mViewId = viewId;
3547 }
3548
3549 /**
3550 * Create a new RemoteViews object that will display the views contained
3551 * in the specified layout file.
3552 *
3553 * @param application The application whose content is shown by the views.
3554 * @param layoutId The id of the layout resource.
3555 *
3556 * @hide
3557 */
3558 protected RemoteViews(ApplicationInfo application, @LayoutRes int layoutId) {
3559 mApplication = application;
3560 mLayoutId = layoutId;
3561 mApplicationInfoCache.put(application);
3562 }
3563
3564 private boolean hasMultipleLayouts() {
3565 return hasLandscapeAndPortraitLayouts() || hasSizedRemoteViews();
3566 }
3567
3568 private boolean hasLandscapeAndPortraitLayouts() {
3569 return (mLandscape != null) && (mPortrait != null);
3570 }
3571
3572 private boolean hasSizedRemoteViews() {
3573 return mSizedRemoteViews != null;
3574 }
3575
3576 private @Nullable SizeF getIdealSize() {
3577 return mIdealSize;
3578 }
3579
3580 private void setIdealSize(@Nullable SizeF size) {
3581 mIdealSize = size;
3582 }
3583
3584 /**
3585 * Finds the smallest view in {@code mSizedRemoteViews}.
3586 * This method must not be called if {@code mSizedRemoteViews} is null.
3587 */
3588 private RemoteViews findSmallestRemoteView() {
3589 return mSizedRemoteViews.get(mSizedRemoteViews.size() - 1);
3590 }
3591
3592 /**
3593 * Create a new RemoteViews object that will inflate as the specified
3594 * landspace or portrait RemoteViews, depending on the current configuration.
3595 *
3596 * @param landscape The RemoteViews to inflate in landscape configuration
3597 * @param portrait The RemoteViews to inflate in portrait configuration
3598 * @throws IllegalArgumentException if either landscape or portrait are null or if they are
3599 * not from the same application
3600 */
3601 public RemoteViews(RemoteViews landscape, RemoteViews portrait) {
3602 if (landscape == null || portrait == null) {
3603 throw new IllegalArgumentException("Both RemoteViews must be non-null");
3604 }
3605 if (!landscape.hasSameAppInfo(portrait.mApplication)) {
3606 throw new IllegalArgumentException(
3607 "Both RemoteViews must share the same package and user");
3608 }
3609 mApplication = portrait.mApplication;
3610 mLayoutId = portrait.mLayoutId;
3611 mViewId = portrait.mViewId;
3612 mLightBackgroundLayoutId = portrait.mLightBackgroundLayoutId;
3613
3614 mLandscape = landscape;
3615 mPortrait = portrait;
3616
3617 mClassCookies = (portrait.mClassCookies != null)
3618 ? portrait.mClassCookies : landscape.mClassCookies;
3619
3620 configureDescendantsAsChildren();
3621 }
3622
3623 /**
3624 * Create a new RemoteViews object that will inflate the layout with the closest size
3625 * specification.
3626 *
3627 * The default remote views in that case is always the one with the smallest area.
3628 *
3629 * If the {@link RemoteViews} host provides the size of the view, the layout with the largest
3630 * area that fits entirely in the provided size will be used (i.e. the width and height of
3631 * the layout must be less than the size of the view, with a 1dp margin to account for
3632 * rounding). If no layout fits in the view, the layout with the smallest area will be used.
3633 *
3634 * @param remoteViews Mapping of size to layout.
3635 * @throws IllegalArgumentException if the map is empty, there are more than
3636 * MAX_INIT_VIEW_COUNT layouts or the remote views are not all from the same application.
3637 */
3638 public RemoteViews(@NonNull Map<SizeF, RemoteViews> remoteViews) {
3639 if (remoteViews.isEmpty()) {
3640 throw new IllegalArgumentException("The set of RemoteViews cannot be empty");
3641 }
3642 if (remoteViews.size() > MAX_INIT_VIEW_COUNT) {
3643 throw new IllegalArgumentException("Too many RemoteViews in constructor");
3644 }
3645 if (remoteViews.size() == 1) {
3646 // If the map only contains a single mapping, treat this as if that RemoteViews was
3647 // passed as the top-level RemoteViews.
3648 RemoteViews single = remoteViews.values().iterator().next();
3649 initializeFrom(single, /* hierarchyRoot= */ single);
3650 return;
3651 }
3652 mClassCookies = initializeSizedRemoteViews(
3653 remoteViews.entrySet().stream().map(
3654 entry -> {
3655 entry.getValue().setIdealSize(entry.getKey());
3656 return entry.getValue();
3657 }
3658 ).iterator()
3659 );
3660
3661 RemoteViews smallestView = findSmallestRemoteView();
3662 mApplication = smallestView.mApplication;
3663 mLayoutId = smallestView.mLayoutId;
3664 mViewId = smallestView.mViewId;
3665 mLightBackgroundLayoutId = smallestView.mLightBackgroundLayoutId;
3666
3667 configureDescendantsAsChildren();
3668 }
3669
3670 // Initialize mSizedRemoteViews and return the class cookies.
3671 private Map<Class, Object> initializeSizedRemoteViews(Iterator<RemoteViews> remoteViews) {
3672 List<RemoteViews> sizedRemoteViews = new ArrayList<>();
3673 Map<Class, Object> classCookies = null;
3674 float viewArea = Float.MAX_VALUE;
3675 RemoteViews smallestView = null;
3676 while (remoteViews.hasNext()) {
3677 RemoteViews view = remoteViews.next();
3678 SizeF size = view.getIdealSize();
3679 if (size == null) {
3680 throw new IllegalStateException("Expected RemoteViews to have ideal size");
3681 }
3682 float newViewArea = size.getWidth() * size.getHeight();
3683 if (smallestView != null && !view.hasSameAppInfo(smallestView.mApplication)) {
3684 throw new IllegalArgumentException(
3685 "All RemoteViews must share the same package and user");
3686 }
3687 if (smallestView == null || newViewArea < viewArea) {
3688 if (smallestView != null) {
3689 sizedRemoteViews.add(smallestView);
3690 }
3691 viewArea = newViewArea;
3692 smallestView = view;
3693 } else {
3694 sizedRemoteViews.add(view);
3695 }
3696 view.setIdealSize(size);
3697 if (classCookies == null) {
3698 classCookies = view.mClassCookies;
3699 }
3700 }
3701 sizedRemoteViews.add(smallestView);
3702 mSizedRemoteViews = sizedRemoteViews;
3703 return classCookies;
3704 }
3705
3706 /**
3707 * Creates a copy of another RemoteViews.
3708 */
3709 public RemoteViews(RemoteViews src) {
3710 initializeFrom(src, /* hierarchyRoot= */ null);
3711 }
3712
3713 /**
3714 * No-arg constructor for use with {@link #initializeFrom(RemoteViews, RemoteViews)}. A
3715 * constructor taking two RemoteViews parameters would clash with the landscape/portrait
3716 * constructor.
3717 */
3718 private RemoteViews() {}
3719
3720 private static RemoteViews createInitializedFrom(@NonNull RemoteViews src,
3721 @Nullable RemoteViews hierarchyRoot) {
3722 RemoteViews child = new RemoteViews();
3723 child.initializeFrom(src, hierarchyRoot);
3724 return child;
3725 }
3726
3727 private void initializeFrom(@NonNull RemoteViews src, @Nullable RemoteViews hierarchyRoot) {
3728 if (hierarchyRoot == null) {
3729 mBitmapCache = src.mBitmapCache;
3730 mApplicationInfoCache = src.mApplicationInfoCache;
3731 } else {
3732 mBitmapCache = hierarchyRoot.mBitmapCache;
3733 mApplicationInfoCache = hierarchyRoot.mApplicationInfoCache;
3734 }
3735 if (hierarchyRoot == null || src.mIsRoot) {
3736 // If there's no provided root, or if src was itself a root, then this RemoteViews is
3737 // the root of the new hierarchy.
3738 mIsRoot = true;
3739 hierarchyRoot = this;
3740 } else {
3741 // Otherwise, we're a descendant in the hierarchy.
3742 mIsRoot = false;
3743 }
3744 mApplication = src.mApplication;
3745 mLayoutId = src.mLayoutId;
3746 mLightBackgroundLayoutId = src.mLightBackgroundLayoutId;
3747 mApplyFlags = src.mApplyFlags;
3748 mClassCookies = src.mClassCookies;
3749 mIdealSize = src.mIdealSize;
3750 mProviderInstanceId = src.mProviderInstanceId;
3751
3752 if (src.hasLandscapeAndPortraitLayouts()) {
3753 mLandscape = createInitializedFrom(src.mLandscape, hierarchyRoot);
3754 mPortrait = createInitializedFrom(src.mPortrait, hierarchyRoot);
3755 }
3756
3757 if (src.hasSizedRemoteViews()) {
3758 mSizedRemoteViews = new ArrayList<>(src.mSizedRemoteViews.size());
3759 for (RemoteViews srcView : src.mSizedRemoteViews) {
3760 mSizedRemoteViews.add(createInitializedFrom(srcView, hierarchyRoot));
3761 }
3762 }
3763
3764 if (src.mActions != null) {
3765 Parcel p = Parcel.obtain();
3766 p.putClassCookies(mClassCookies);
3767 src.writeActionsToParcel(p, /* flags= */ 0);
3768 p.setDataPosition(0);
3769 // Since src is already in memory, we do not care about stack overflow as it has
3770 // already been read once.
3771 readActionsFromParcel(p, 0);
3772 p.recycle();
3773 }
3774
3775 // Now that everything is initialized and duplicated, create new caches for this
3776 // RemoteViews and recursively set up all descendants.
3777 if (mIsRoot) {
3778 reconstructCaches();
3779 }
3780 }
3781
3782 /**
3783 * Reads a RemoteViews object from a parcel.
3784 *
3785 * @param parcel
3786 */
3787 public RemoteViews(Parcel parcel) {
3788 this(parcel, /* rootData= */ null, /* info= */ null, /* depth= */ 0);
3789 }
3790
3791 private RemoteViews(@NonNull Parcel parcel, @Nullable HierarchyRootData rootData,
3792 @Nullable ApplicationInfo info, int depth) {
3793 if (depth > MAX_NESTED_VIEWS
3794 && (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID)) {
3795 throw new IllegalArgumentException("Too many nested views.");
3796 }
3797 depth++;
3798
3799 int mode = parcel.readInt();
3800
3801 if (rootData == null) {
3802 // We only store a bitmap cache in the root of the RemoteViews.
3803 mBitmapCache = new BitmapCache(parcel);
3804 // Store the class cookies such that they are available when we clone this RemoteView.
3805 mClassCookies = parcel.copyClassCookies();
3806 } else {
3807 configureAsChild(rootData);
3808 }
3809
3810 if (mode == MODE_NORMAL) {
3811 mApplication = ApplicationInfo.CREATOR.createFromParcel(parcel);
3812 mIdealSize = parcel.readInt() == 0 ? null : SizeF.CREATOR.createFromParcel(parcel);
3813 mLayoutId = parcel.readInt();
3814 mViewId = parcel.readInt();
3815 mLightBackgroundLayoutId = parcel.readInt();
3816
3817 readActionsFromParcel(parcel, depth);
3818 } else if (mode == MODE_HAS_SIZED_REMOTEVIEWS) {
3819 int numViews = parcel.readInt();
3820 if (numViews > MAX_INIT_VIEW_COUNT) {
3821 throw new IllegalArgumentException(
3822 "Too many views in mapping from size to RemoteViews.");
3823 }
3824 List<RemoteViews> remoteViews = new ArrayList<>(numViews);
3825 for (int i = 0; i < numViews; i++) {
3826 RemoteViews view = new RemoteViews(parcel, getHierarchyRootData(), info, depth);
3827 info = view.mApplication;
3828 remoteViews.add(view);
3829 }
3830 initializeSizedRemoteViews(remoteViews.iterator());
3831 RemoteViews smallestView = findSmallestRemoteView();
3832 mApplication = smallestView.mApplication;
3833 mLayoutId = smallestView.mLayoutId;
3834 mViewId = smallestView.mViewId;
3835 mLightBackgroundLayoutId = smallestView.mLightBackgroundLayoutId;
3836 } else {
3837 // MODE_HAS_LANDSCAPE_AND_PORTRAIT
3838 mLandscape = new RemoteViews(parcel, getHierarchyRootData(), info, depth);
3839 mPortrait =
3840 new RemoteViews(parcel, getHierarchyRootData(), mLandscape.mApplication, depth);
3841 mApplication = mPortrait.mApplication;
3842 mLayoutId = mPortrait.mLayoutId;
3843 mViewId = mPortrait.mViewId;
3844 mLightBackgroundLayoutId = mPortrait.mLightBackgroundLayoutId;
3845 }
3846 mApplyFlags = parcel.readInt();
3847 mProviderInstanceId = parcel.readLong();
3848
3849 // Ensure that all descendants have their caches set up recursively.
3850 if (mIsRoot) {
3851 configureDescendantsAsChildren();
3852 }
3853 }
3854
3855 private void readActionsFromParcel(Parcel parcel, int depth) {
3856 int count = parcel.readInt();
3857 if (count > 0) {
3858 mActions = new ArrayList<>(count);
3859 for (int i = 0; i < count; i++) {
3860 mActions.add(getActionFromParcel(parcel, depth));
3861 }
3862 }
3863 }
3864
3865 private Action getActionFromParcel(Parcel parcel, int depth) {
3866 int tag = parcel.readInt();
3867 switch (tag) {
3868 case SET_ON_CLICK_RESPONSE_TAG:
3869 return new SetOnClickResponse(parcel);
3870 case SET_DRAWABLE_TINT_TAG:
3871 return new SetDrawableTint(parcel);
3872 case REFLECTION_ACTION_TAG:
3873 return new ReflectionAction(parcel);
3874 case VIEW_GROUP_ACTION_ADD_TAG:
3875 return new ViewGroupActionAdd(parcel, mApplication, depth);
3876 case VIEW_GROUP_ACTION_REMOVE_TAG:
3877 return new ViewGroupActionRemove(parcel);
3878 case VIEW_CONTENT_NAVIGATION_TAG:
3879 return new ViewContentNavigation(parcel);
3880 case SET_EMPTY_VIEW_ACTION_TAG:
3881 return new SetEmptyView(parcel);
3882 case SET_PENDING_INTENT_TEMPLATE_TAG:
3883 return new SetPendingIntentTemplate(parcel);
3884 case SET_REMOTE_VIEW_ADAPTER_INTENT_TAG:
3885 return new SetRemoteViewsAdapterIntent(parcel);
3886 case TEXT_VIEW_DRAWABLE_ACTION_TAG:
3887 return new TextViewDrawableAction(parcel);
3888 case TEXT_VIEW_SIZE_ACTION_TAG:
3889 return new TextViewSizeAction(parcel);
3890 case VIEW_PADDING_ACTION_TAG:
3891 return new ViewPaddingAction(parcel);
3892 case BITMAP_REFLECTION_ACTION_TAG:
3893 return new BitmapReflectionAction(parcel);
3894 case SET_REMOTE_VIEW_ADAPTER_LIST_TAG:
3895 return new SetRemoteViewsAdapterList(parcel);
3896 case SET_REMOTE_INPUTS_ACTION_TAG:
3897 return new SetRemoteInputsAction(parcel);
3898 case LAYOUT_PARAM_ACTION_TAG:
3899 return new LayoutParamAction(parcel);
3900 case OVERRIDE_TEXT_COLORS_TAG:
3901 return new OverrideTextColorsAction(parcel);
3902 case SET_RIPPLE_DRAWABLE_COLOR_TAG:
3903 return new SetRippleDrawableColor(parcel);
3904 case SET_INT_TAG_TAG:
3905 return new SetIntTagAction(parcel);
3906 case REMOVE_FROM_PARENT_ACTION_TAG:
3907 return new RemoveFromParentAction(parcel);
3908 case RESOURCE_REFLECTION_ACTION_TAG:
3909 return new ResourceReflectionAction(parcel);
3910 case COMPLEX_UNIT_DIMENSION_REFLECTION_ACTION_TAG:
3911 return new ComplexUnitDimensionReflectionAction(parcel);
3912 case SET_COMPOUND_BUTTON_CHECKED_TAG:
3913 return new SetCompoundButtonCheckedAction(parcel);
3914 case SET_RADIO_GROUP_CHECKED:
3915 return new SetRadioGroupCheckedAction(parcel);
3916 case SET_VIEW_OUTLINE_RADIUS_TAG:
3917 return new SetViewOutlinePreferredRadiusAction(parcel);
3918 case SET_ON_CHECKED_CHANGE_RESPONSE_TAG:
3919 return new SetOnCheckedChangeResponse(parcel);
3920 case NIGHT_MODE_REFLECTION_ACTION_TAG:
3921 return new NightModeReflectionAction(parcel);
3922 case SET_REMOTE_COLLECTION_ITEMS_ADAPTER_TAG:
3923 return new SetRemoteCollectionItemListAdapterAction(parcel);
3924 case ATTRIBUTE_REFLECTION_ACTION_TAG:
3925 return new AttributeReflectionAction(parcel);
3926 default:
3927 throw new ActionException("Tag " + tag + " not found");
3928 }
3929 };
3930
3931 /**
3932 * Returns a deep copy of the RemoteViews object. The RemoteView may not be
3933 * attached to another RemoteView -- it must be the root of a hierarchy.
3934 *
3935 * @deprecated use {@link #RemoteViews(RemoteViews)} instead.
3936 * @throws IllegalStateException if this is not the root of a RemoteView
3937 * hierarchy
3938 */
3939 @Override
3940 @Deprecated
3941 public RemoteViews clone() {
3942 Preconditions.checkState(mIsRoot, "RemoteView has been attached to another RemoteView. "
3943 + "May only clone the root of a RemoteView hierarchy.");
3944
3945 return new RemoteViews(this);
3946 }
3947
3948 public String getPackage() {
3949 return (mApplication != null) ? mApplication.packageName : null;
3950 }
3951
3952 /**
3953 * Returns the layout id of the root layout associated with this RemoteViews. In the case
3954 * that the RemoteViews has both a landscape and portrait root, this will return the layout
3955 * id associated with the portrait layout.
3956 *
3957 * @return the layout id.
3958 */
3959 public int getLayoutId() {
3960 return hasFlags(FLAG_USE_LIGHT_BACKGROUND_LAYOUT) && (mLightBackgroundLayoutId != 0)
3961 ? mLightBackgroundLayoutId : mLayoutId;
3962 }
3963
3964 /**
3965 * Sets the root of the hierarchy and then recursively traverses the tree to update the root
3966 * and populate caches for all descendants.
3967 */
3968 private void configureAsChild(@NonNull HierarchyRootData rootData) {
3969 mIsRoot = false;
3970 mBitmapCache = rootData.mBitmapCache;
3971 mApplicationInfoCache = rootData.mApplicationInfoCache;
3972 mClassCookies = rootData.mClassCookies;
3973 configureDescendantsAsChildren();
3974 }
3975
3976 /**
3977 * Recursively traverses the tree to update the root and populate caches for all descendants.
3978 */
3979 private void configureDescendantsAsChildren() {
3980 // Before propagating down the tree, replace our application from the root application info
3981 // cache, to ensure the same instance is present throughout the hierarchy to allow for
3982 // squashing.
3983 mApplication = mApplicationInfoCache.getOrPut(mApplication);
3984
3985 HierarchyRootData rootData = getHierarchyRootData();
3986 if (hasSizedRemoteViews()) {
3987 for (RemoteViews remoteView : mSizedRemoteViews) {
3988 remoteView.configureAsChild(rootData);
3989 }
3990 } else if (hasLandscapeAndPortraitLayouts()) {
3991 mLandscape.configureAsChild(rootData);
3992 mPortrait.configureAsChild(rootData);
3993 } else {
3994 if (mActions != null) {
3995 for (Action action : mActions) {
3996 action.setHierarchyRootData(rootData);
3997 }
3998 }
3999 }
4000 }
4001
4002 /**
4003 * Recreates caches at the root level of the hierarchy, then recursively populates the caches
4004 * down the hierarchy.
4005 */
4006 private void reconstructCaches() {
4007 if (!mIsRoot) return;
4008 mBitmapCache = new BitmapCache();
4009 mApplicationInfoCache = new ApplicationInfoCache();
4010 mApplication = mApplicationInfoCache.getOrPut(mApplication);
4011 configureDescendantsAsChildren();
4012 }
4013
4014 /**
4015 * Returns an estimate of the bitmap heap memory usage for this RemoteViews.
4016 */
4017 /** @hide */
4018 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4019 public int estimateMemoryUsage() {
4020 return mBitmapCache.getBitmapMemory();
4021 }
4022
4023 /**
4024 * Add an action to be executed on the remote side when apply is called.
4025 *
4026 * @param a The action to add
4027 */
4028 private void addAction(Action a) {
4029 if (hasMultipleLayouts()) {
4030 throw new RuntimeException("RemoteViews specifying separate layouts for orientation"
4031 + " or size cannot be modified. Instead, fully configure each layouts"
4032 + " individually before constructing the combined layout.");
4033 }
4034 if (mActions == null) {
4035 mActions = new ArrayList<>();
4036 }
4037 mActions.add(a);
4038 }
4039
4040 /**
4041 * Equivalent to calling {@link ViewGroup#addView(View)} after inflating the
4042 * given {@link RemoteViews}. This allows users to build "nested"
4043 * {@link RemoteViews}. In cases where consumers of {@link RemoteViews} may
4044 * recycle layouts, use {@link #removeAllViews(int)} to clear any existing
4045 * children.
4046 *
4047 * @param viewId The id of the parent {@link ViewGroup} to add child into.
4048 * @param nestedView {@link RemoteViews} that describes the child.
4049 */
4050 public void addView(@IdRes int viewId, RemoteViews nestedView) {
4051 // Clear all children when nested views omitted
4052 addAction(nestedView == null
4053 ? new ViewGroupActionRemove(viewId)
4054 : new ViewGroupActionAdd(viewId, nestedView));
4055 }
4056
4057 /**
4058 * Equivalent to calling {@link ViewGroup#addView(View)} after inflating the given
4059 * {@link RemoteViews}. If the {@link RemoteViews} may be re-inflated or updated,
4060 * {@link #removeAllViews(int)} must be called on the same {@code viewId
4061 * } before the first call to this method for the behavior of this method to be predictable.
4062 *
4063 * The {@code stableId} will be used to identify a potential view to recycled when the remote
4064 * view is inflated. Views can be re-used if inserted in the same order, potentially with
4065 * some views appearing / disappearing. To be recycled the view must not change the layout
4066 * used to inflate it or its view id (see {@link RemoteViews#RemoteViews(String, int, int)}).
4067 *
4068 * Note: if a view is re-used, all the actions will be re-applied on it. However, its properties
4069 * are not reset, so what was applied in previous round will have an effect. As a view may be
4070 * re-created at any time by the host, the RemoteViews should not rely on keeping information
4071 * from previous applications and always re-set all the properties they need.
4072 *
4073 * @param viewId The id of the parent {@link ViewGroup} to add child into.
4074 * @param nestedView {@link RemoteViews} that describes the child.
4075 * @param stableId An id that is stable across different versions of RemoteViews.
4076 */
4077 public void addStableView(@IdRes int viewId, @NonNull RemoteViews nestedView, int stableId) {
4078 addAction(new ViewGroupActionAdd(viewId, nestedView, -1 /* index */, stableId));
4079 }
4080
4081 /**
4082 * Equivalent to calling {@link ViewGroup#addView(View, int)} after inflating the
4083 * given {@link RemoteViews}.
4084 *
4085 * @param viewId The id of the parent {@link ViewGroup} to add the child into.
4086 * @param nestedView {@link RemoteViews} of the child to add.
4087 * @param index The position at which to add the child.
4088 *
4089 * @hide
4090 */
4091 @UnsupportedAppUsage
4092 public void addView(@IdRes int viewId, RemoteViews nestedView, int index) {
4093 addAction(new ViewGroupActionAdd(viewId, nestedView, index));
4094 }
4095
4096 /**
4097 * Equivalent to calling {@link ViewGroup#removeAllViews()}.
4098 *
4099 * @param viewId The id of the parent {@link ViewGroup} to remove all
4100 * children from.
4101 */
4102 public void removeAllViews(@IdRes int viewId) {
4103 addAction(new ViewGroupActionRemove(viewId));
4104 }
4105
4106 /**
4107 * Removes all views in the {@link ViewGroup} specified by the {@code viewId} except for any
4108 * child that has the {@code viewIdToKeep} as its id.
4109 *
4110 * @param viewId The id of the parent {@link ViewGroup} to remove children from.
4111 * @param viewIdToKeep The id of a child that should not be removed.
4112 *
4113 * @hide
4114 */
4115 public void removeAllViewsExceptId(@IdRes int viewId, @IdRes int viewIdToKeep) {
4116 addAction(new ViewGroupActionRemove(viewId, viewIdToKeep));
4117 }
4118
4119 /**
4120 * Removes the {@link View} specified by the {@code viewId} from its parent {@link ViewManager}.
4121 * This will do nothing if the viewId specifies the root view of this RemoteViews.
4122 *
4123 * @param viewId The id of the {@link View} to remove from its parent.
4124 *
4125 * @hide
4126 */
4127 public void removeFromParent(@IdRes int viewId) {
4128 addAction(new RemoveFromParentAction(viewId));
4129 }
4130
4131 /**
4132 * Equivalent to calling {@link AdapterViewAnimator#showNext()}
4133 *
4134 * @param viewId The id of the view on which to call {@link AdapterViewAnimator#showNext()}
4135 * @deprecated As RemoteViews may be reapplied frequently, it is preferable to call
4136 * {@link #setDisplayedChild(int, int)} to ensure that the adapter index does not change
4137 * unexpectedly.
4138 */
4139 @Deprecated
4140 public void showNext(@IdRes int viewId) {
4141 addAction(new ViewContentNavigation(viewId, true /* next */));
4142 }
4143
4144 /**
4145 * Equivalent to calling {@link AdapterViewAnimator#showPrevious()}
4146 *
4147 * @param viewId The id of the view on which to call {@link AdapterViewAnimator#showPrevious()}
4148 * @deprecated As RemoteViews may be reapplied frequently, it is preferable to call
4149 * {@link #setDisplayedChild(int, int)} to ensure that the adapter index does not change
4150 * unexpectedly.
4151 */
4152 @Deprecated
4153 public void showPrevious(@IdRes int viewId) {
4154 addAction(new ViewContentNavigation(viewId, false /* next */));
4155 }
4156
4157 /**
4158 * Equivalent to calling {@link AdapterViewAnimator#setDisplayedChild(int)}
4159 *
4160 * @param viewId The id of the view on which to call
4161 * {@link AdapterViewAnimator#setDisplayedChild(int)}
4162 */
4163 public void setDisplayedChild(@IdRes int viewId, int childIndex) {
4164 setInt(viewId, "setDisplayedChild", childIndex);
4165 }
4166
4167 /**
4168 * Equivalent to calling {@link View#setVisibility(int)}
4169 *
4170 * @param viewId The id of the view whose visibility should change
4171 * @param visibility The new visibility for the view
4172 */
4173 public void setViewVisibility(@IdRes int viewId, @View.Visibility int visibility) {
4174 setInt(viewId, "setVisibility", visibility);
4175 }
4176
4177 /**
4178 * Equivalent to calling {@link TextView#setText(CharSequence)}
4179 *
4180 * @param viewId The id of the view whose text should change
4181 * @param text The new text for the view
4182 */
4183 public void setTextViewText(@IdRes int viewId, CharSequence text) {
4184 setCharSequence(viewId, "setText", text);
4185 }
4186
4187 /**
4188 * Equivalent to calling {@link TextView#setTextSize(int, float)}
4189 *
4190 * @param viewId The id of the view whose text size should change
4191 * @param units The units of size (e.g. COMPLEX_UNIT_SP)
4192 * @param size The size of the text
4193 */
4194 public void setTextViewTextSize(@IdRes int viewId, int units, float size) {
4195 addAction(new TextViewSizeAction(viewId, units, size));
4196 }
4197
4198 /**
4199 * Equivalent to calling
4200 * {@link TextView#setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)}.
4201 *
4202 * @param viewId The id of the view whose text should change
4203 * @param left The id of a drawable to place to the left of the text, or 0
4204 * @param top The id of a drawable to place above the text, or 0
4205 * @param right The id of a drawable to place to the right of the text, or 0
4206 * @param bottom The id of a drawable to place below the text, or 0
4207 */
4208 public void setTextViewCompoundDrawables(@IdRes int viewId, @DrawableRes int left,
4209 @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) {
4210 addAction(new TextViewDrawableAction(viewId, false, left, top, right, bottom));
4211 }
4212
4213 /**
4214 * Equivalent to calling {@link
4215 * TextView#setCompoundDrawablesRelativeWithIntrinsicBounds(int, int, int, int)}.
4216 *
4217 * @param viewId The id of the view whose text should change
4218 * @param start The id of a drawable to place before the text (relative to the
4219 * layout direction), or 0
4220 * @param top The id of a drawable to place above the text, or 0
4221 * @param end The id of a drawable to place after the text, or 0
4222 * @param bottom The id of a drawable to place below the text, or 0
4223 */
4224 public void setTextViewCompoundDrawablesRelative(@IdRes int viewId, @DrawableRes int start,
4225 @DrawableRes int top, @DrawableRes int end, @DrawableRes int bottom) {
4226 addAction(new TextViewDrawableAction(viewId, true, start, top, end, bottom));
4227 }
4228
4229 /**
4230 * Equivalent to calling {@link
4231 * TextView#setCompoundDrawablesWithIntrinsicBounds(Drawable, Drawable, Drawable, Drawable)}
4232 * using the drawables yielded by {@link Icon#loadDrawable(Context)}.
4233 *
4234 * @param viewId The id of the view whose text should change
4235 * @param left an Icon to place to the left of the text, or 0
4236 * @param top an Icon to place above the text, or 0
4237 * @param right an Icon to place to the right of the text, or 0
4238 * @param bottom an Icon to place below the text, or 0
4239 *
4240 * @hide
4241 */
4242 public void setTextViewCompoundDrawables(@IdRes int viewId,
4243 Icon left, Icon top, Icon right, Icon bottom) {
4244 addAction(new TextViewDrawableAction(viewId, false, left, top, right, bottom));
4245 }
4246
4247 /**
4248 * Equivalent to calling {@link
4249 * TextView#setCompoundDrawablesRelativeWithIntrinsicBounds(Drawable, Drawable, Drawable, Drawable)}
4250 * using the drawables yielded by {@link Icon#loadDrawable(Context)}.
4251 *
4252 * @param viewId The id of the view whose text should change
4253 * @param start an Icon to place before the text (relative to the
4254 * layout direction), or 0
4255 * @param top an Icon to place above the text, or 0
4256 * @param end an Icon to place after the text, or 0
4257 * @param bottom an Icon to place below the text, or 0
4258 *
4259 * @hide
4260 */
4261 public void setTextViewCompoundDrawablesRelative(@IdRes int viewId,
4262 Icon start, Icon top, Icon end, Icon bottom) {
4263 addAction(new TextViewDrawableAction(viewId, true, start, top, end, bottom));
4264 }
4265
4266 /**
4267 * Equivalent to calling {@link ImageView#setImageResource(int)}
4268 *
4269 * @param viewId The id of the view whose drawable should change
4270 * @param srcId The new resource id for the drawable
4271 */
4272 public void setImageViewResource(@IdRes int viewId, @DrawableRes int srcId) {
4273 setInt(viewId, "setImageResource", srcId);
4274 }
4275
4276 /**
4277 * Equivalent to calling {@link ImageView#setImageURI(Uri)}
4278 *
4279 * @param viewId The id of the view whose drawable should change
4280 * @param uri The Uri for the image
4281 */
4282 public void setImageViewUri(@IdRes int viewId, Uri uri) {
4283 setUri(viewId, "setImageURI", uri);
4284 }
4285
4286 /**
4287 * Equivalent to calling {@link ImageView#setImageBitmap(Bitmap)}
4288 *
4289 * @param viewId The id of the view whose bitmap should change
4290 * @param bitmap The new Bitmap for the drawable
4291 */
4292 public void setImageViewBitmap(@IdRes int viewId, Bitmap bitmap) {
4293 setBitmap(viewId, "setImageBitmap", bitmap);
4294 }
4295
4296 /**
4297 * Equivalent to calling {@link ImageView#setImageIcon(Icon)}
4298 *
4299 * @param viewId The id of the view whose bitmap should change
4300 * @param icon The new Icon for the ImageView
4301 */
4302 public void setImageViewIcon(@IdRes int viewId, Icon icon) {
4303 setIcon(viewId, "setImageIcon", icon);
4304 }
4305
4306 /**
4307 * Equivalent to calling {@link AdapterView#setEmptyView(View)}
4308 *
4309 * @param viewId The id of the view on which to set the empty view
4310 * @param emptyViewId The view id of the empty view
4311 */
4312 public void setEmptyView(@IdRes int viewId, @IdRes int emptyViewId) {
4313 addAction(new SetEmptyView(viewId, emptyViewId));
4314 }
4315
4316 /**
4317 * Equivalent to calling {@link Chronometer#setBase Chronometer.setBase},
4318 * {@link Chronometer#setFormat Chronometer.setFormat},
4319 * and {@link Chronometer#start Chronometer.start()} or
4320 * {@link Chronometer#stop Chronometer.stop()}.
4321 *
4322 * @param viewId The id of the {@link Chronometer} to change
4323 * @param base The time at which the timer would have read 0:00. This
4324 * time should be based off of
4325 * {@link android.os.SystemClock#elapsedRealtime SystemClock.elapsedRealtime()}.
4326 * @param format The Chronometer format string, or null to
4327 * simply display the timer value.
4328 * @param started True if you want the clock to be started, false if not.
4329 *
4330 * @see #setChronometerCountDown(int, boolean)
4331 */
4332 public void setChronometer(@IdRes int viewId, long base, String format, boolean started) {
4333 setLong(viewId, "setBase", base);
4334 setString(viewId, "setFormat", format);
4335 setBoolean(viewId, "setStarted", started);
4336 }
4337
4338 /**
4339 * Equivalent to calling {@link Chronometer#setCountDown(boolean) Chronometer.setCountDown} on
4340 * the chronometer with the given viewId.
4341 *
4342 * @param viewId The id of the {@link Chronometer} to change
4343 * @param isCountDown True if you want the chronometer to count down to base instead of
4344 * counting up.
4345 */
4346 public void setChronometerCountDown(@IdRes int viewId, boolean isCountDown) {
4347 setBoolean(viewId, "setCountDown", isCountDown);
4348 }
4349
4350 /**
4351 * Equivalent to calling {@link ProgressBar#setMax ProgressBar.setMax},
4352 * {@link ProgressBar#setProgress ProgressBar.setProgress}, and
4353 * {@link ProgressBar#setIndeterminate ProgressBar.setIndeterminate}
4354 *
4355 * If indeterminate is true, then the values for max and progress are ignored.
4356 *
4357 * @param viewId The id of the {@link ProgressBar} to change
4358 * @param max The 100% value for the progress bar
4359 * @param progress The current value of the progress bar.
4360 * @param indeterminate True if the progress bar is indeterminate,
4361 * false if not.
4362 */
4363 public void setProgressBar(@IdRes int viewId, int max, int progress,
4364 boolean indeterminate) {
4365 setBoolean(viewId, "setIndeterminate", indeterminate);
4366 if (!indeterminate) {
4367 setInt(viewId, "setMax", max);
4368 setInt(viewId, "setProgress", progress);
4369 }
4370 }
4371
4372 /**
4373 * Equivalent to calling
4374 * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)}
4375 * to launch the provided {@link PendingIntent}. The source bounds
4376 * ({@link Intent#getSourceBounds()}) of the intent will be set to the bounds of the clicked
4377 * view in screen space.
4378 * Note that any activity options associated with the mPendingIntent may get overridden
4379 * before starting the intent.
4380 *
4381 * When setting the on-click action of items within collections (eg. {@link ListView},
4382 * {@link StackView} etc.), this method will not work. Instead, use {@link
4383 * RemoteViews#setPendingIntentTemplate(int, PendingIntent)} in conjunction with
4384 * {@link RemoteViews#setOnClickFillInIntent(int, Intent)}.
4385 *
4386 * @param viewId The id of the view that will trigger the {@link PendingIntent} when clicked
4387 * @param pendingIntent The {@link PendingIntent} to send when user clicks
4388 */
4389 public void setOnClickPendingIntent(@IdRes int viewId, PendingIntent pendingIntent) {
4390 setOnClickResponse(viewId, RemoteResponse.fromPendingIntent(pendingIntent));
4391 }
4392
4393 /**
4394 * Equivalent of calling
4395 * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)}
4396 * to launch the provided {@link RemoteResponse}.
4397 *
4398 * @param viewId The id of the view that will trigger the {@link RemoteResponse} when clicked
4399 * @param response The {@link RemoteResponse} to send when user clicks
4400 */
4401 public void setOnClickResponse(@IdRes int viewId, @NonNull RemoteResponse response) {
4402 addAction(new SetOnClickResponse(viewId, response));
4403 }
4404
4405 /**
4406 * When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is very
4407 * costly to set PendingIntents on the individual items, and is hence not recommended. Instead
4408 * this method should be used to set a single PendingIntent template on the collection, and
4409 * individual items can differentiate their on-click behavior using
4410 * {@link RemoteViews#setOnClickFillInIntent(int, Intent)}.
4411 *
4412 * @param viewId The id of the collection who's children will use this PendingIntent template
4413 * when clicked
4414 * @param pendingIntentTemplate The {@link PendingIntent} to be combined with extras specified
4415 * by a child of viewId and executed when that child is clicked
4416 */
4417 public void setPendingIntentTemplate(@IdRes int viewId, PendingIntent pendingIntentTemplate) {
4418 addAction(new SetPendingIntentTemplate(viewId, pendingIntentTemplate));
4419 }
4420
4421 /**
4422 * When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is very
4423 * costly to set PendingIntents on the individual items, and is hence not recommended. Instead
4424 * a single PendingIntent template can be set on the collection, see {@link
4425 * RemoteViews#setPendingIntentTemplate(int, PendingIntent)}, and the individual on-click
4426 * action of a given item can be distinguished by setting a fillInIntent on that item. The
4427 * fillInIntent is then combined with the PendingIntent template in order to determine the final
4428 * intent which will be executed when the item is clicked. This works as follows: any fields
4429 * which are left blank in the PendingIntent template, but are provided by the fillInIntent
4430 * will be overwritten, and the resulting PendingIntent will be used. The rest
4431 * of the PendingIntent template will then be filled in with the associated fields that are
4432 * set in fillInIntent. See {@link Intent#fillIn(Intent, int)} for more details.
4433 *
4434 * @param viewId The id of the view on which to set the fillInIntent
4435 * @param fillInIntent The intent which will be combined with the parent's PendingIntent
4436 * in order to determine the on-click behavior of the view specified by viewId
4437 */
4438 public void setOnClickFillInIntent(@IdRes int viewId, Intent fillInIntent) {
4439 setOnClickResponse(viewId, RemoteResponse.fromFillInIntent(fillInIntent));
4440 }
4441
4442 /**
4443 * Equivalent to calling
4444 * {@link android.widget.CompoundButton#setOnCheckedChangeListener(
4445 * android.widget.CompoundButton.OnCheckedChangeListener)}
4446 * to launch the provided {@link RemoteResponse}.
4447 *
4448 * The intent will be filled with the current checked state of the view at the key
4449 * {@link #EXTRA_CHECKED}.
4450 *
4451 * The {@link RemoteResponse} will not be launched in response to check changes arising from
4452 * {@link #setCompoundButtonChecked(int, boolean)} or {@link #setRadioGroupChecked(int, int)}
4453 * usages.
4454 *
4455 * The {@link RemoteResponse} must be created using
4456 * {@link RemoteResponse#fromFillInIntent(Intent)} in conjunction with
4457 * {@link RemoteViews#setPendingIntentTemplate(int, PendingIntent)} for items inside
4458 * collections (eg. {@link ListView}, {@link StackView} etc.).
4459 *
4460 * Otherwise, create the {@link RemoteResponse} using
4461 * {@link RemoteResponse#fromPendingIntent(PendingIntent)}.
4462 *
4463 * @param viewId The id of the view that will trigger the {@link PendingIntent} when checked
4464 * state changes.
4465 * @param response The {@link RemoteResponse} to send when the checked state changes.
4466 */
4467 public void setOnCheckedChangeResponse(
4468 @IdRes int viewId,
4469 @NonNull RemoteResponse response) {
4470 addAction(
4471 new SetOnCheckedChangeResponse(
4472 viewId,
4473 response.setInteractionType(
4474 RemoteResponse.INTERACTION_TYPE_CHECKED_CHANGE)));
4475 }
4476
4477 /**
4478 * @hide
4479 * Equivalent to calling
4480 * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)},
4481 * on the {@link Drawable} of a given view.
4482 * <p>
4483 *
4484 * @param viewId The id of the view that contains the target
4485 * {@link Drawable}
4486 * @param targetBackground If true, apply these parameters to the
4487 * {@link Drawable} returned by
4488 * {@link android.view.View#getBackground()}. Otherwise, assume
4489 * the target view is an {@link ImageView} and apply them to
4490 * {@link ImageView#getDrawable()}.
4491 * @param colorFilter Specify a color for a
4492 * {@link android.graphics.ColorFilter} for this drawable. This will be ignored if
4493 * {@code mode} is {@code null}.
4494 * @param mode Specify a PorterDuff mode for this drawable, or null to leave
4495 * unchanged.
4496 */
4497 public void setDrawableTint(@IdRes int viewId, boolean targetBackground,
4498 @ColorInt int colorFilter, @NonNull PorterDuff.Mode mode) {
4499 addAction(new SetDrawableTint(viewId, targetBackground, colorFilter, mode));
4500 }
4501
4502 /**
4503 * @hide
4504 * Equivalent to calling
4505 * {@link RippleDrawable#setColor(ColorStateList)} on the {@link Drawable} of a given view,
4506 * assuming it's a {@link RippleDrawable}.
4507 * <p>
4508 *
4509 * @param viewId The id of the view that contains the target
4510 * {@link RippleDrawable}
4511 * @param colorStateList Specify a color for a
4512 * {@link ColorStateList} for this drawable.
4513 */
4514 public void setRippleDrawableColor(@IdRes int viewId, ColorStateList colorStateList) {
4515 addAction(new SetRippleDrawableColor(viewId, colorStateList));
4516 }
4517
4518 /**
4519 * @hide
4520 * Equivalent to calling {@link android.widget.ProgressBar#setProgressTintList}.
4521 *
4522 * @param viewId The id of the view whose tint should change
4523 * @param tint the tint to apply, may be {@code null} to clear tint
4524 */
4525 public void setProgressTintList(@IdRes int viewId, ColorStateList tint) {
4526 addAction(new ReflectionAction(viewId, "setProgressTintList",
4527 BaseReflectionAction.COLOR_STATE_LIST, tint));
4528 }
4529
4530 /**
4531 * @hide
4532 * Equivalent to calling {@link android.widget.ProgressBar#setProgressBackgroundTintList}.
4533 *
4534 * @param viewId The id of the view whose tint should change
4535 * @param tint the tint to apply, may be {@code null} to clear tint
4536 */
4537 public void setProgressBackgroundTintList(@IdRes int viewId, ColorStateList tint) {
4538 addAction(new ReflectionAction(viewId, "setProgressBackgroundTintList",
4539 BaseReflectionAction.COLOR_STATE_LIST, tint));
4540 }
4541
4542 /**
4543 * @hide
4544 * Equivalent to calling {@link android.widget.ProgressBar#setIndeterminateTintList}.
4545 *
4546 * @param viewId The id of the view whose tint should change
4547 * @param tint the tint to apply, may be {@code null} to clear tint
4548 */
4549 public void setProgressIndeterminateTintList(@IdRes int viewId, ColorStateList tint) {
4550 addAction(new ReflectionAction(viewId, "setIndeterminateTintList",
4551 BaseReflectionAction.COLOR_STATE_LIST, tint));
4552 }
4553
4554 /**
4555 * Equivalent to calling {@link android.widget.TextView#setTextColor(int)}.
4556 *
4557 * @param viewId The id of the view whose text color should change
4558 * @param color Sets the text color for all the states (normal, selected,
4559 * focused) to be this color.
4560 */
4561 public void setTextColor(@IdRes int viewId, @ColorInt int color) {
4562 setInt(viewId, "setTextColor", color);
4563 }
4564
4565 /**
4566 * @hide
4567 * Equivalent to calling {@link android.widget.TextView#setTextColor(ColorStateList)}.
4568 *
4569 * @param viewId The id of the view whose text color should change
4570 * @param colors the text colors to set
4571 */
4572 public void setTextColor(@IdRes int viewId, ColorStateList colors) {
4573 addAction(new ReflectionAction(viewId, "setTextColor",
4574 BaseReflectionAction.COLOR_STATE_LIST, colors));
4575 }
4576
4577 /**
4578 * Equivalent to calling {@link android.widget.AbsListView#setRemoteViewsAdapter(Intent)}.
4579 *
4580 * @param appWidgetId The id of the app widget which contains the specified view. (This
4581 * parameter is ignored in this deprecated method)
4582 * @param viewId The id of the {@link AdapterView}
4583 * @param intent The intent of the service which will be
4584 * providing data to the RemoteViewsAdapter
4585 * @deprecated This method has been deprecated. See
4586 * {@link android.widget.RemoteViews#setRemoteAdapter(int, Intent)}
4587 */
4588 @Deprecated
4589 public void setRemoteAdapter(int appWidgetId, @IdRes int viewId, Intent intent) {
4590 setRemoteAdapter(viewId, intent);
4591 }
4592
4593 /**
4594 * Equivalent to calling {@link android.widget.AbsListView#setRemoteViewsAdapter(Intent)}.
4595 * Can only be used for App Widgets.
4596 *
4597 * @param viewId The id of the {@link AdapterView}
4598 * @param intent The intent of the service which will be
4599 * providing data to the RemoteViewsAdapter
4600 */
4601 public void setRemoteAdapter(@IdRes int viewId, Intent intent) {
4602 addAction(new SetRemoteViewsAdapterIntent(viewId, intent));
4603 }
4604
4605 /**
4606 * Creates a simple Adapter for the viewId specified. The viewId must point to an AdapterView,
4607 * ie. {@link ListView}, {@link GridView}, {@link StackView} or {@link AdapterViewAnimator}.
4608 * This is a simpler but less flexible approach to populating collection widgets. Its use is
4609 * encouraged for most scenarios, as long as the total memory within the list of RemoteViews
4610 * is relatively small (ie. doesn't contain large or numerous Bitmaps, see {@link
4611 * RemoteViews#setImageViewBitmap}). In the case of numerous images, the use of API is still
4612 * possible by setting image URIs instead of Bitmaps, see {@link RemoteViews#setImageViewUri}.
4613 *
4614 * This API is supported in the compatibility library for previous API levels, see
4615 * RemoteViewsCompat.
4616 *
4617 * @param viewId The id of the {@link AdapterView}
4618 * @param list The list of RemoteViews which will populate the view specified by viewId.
4619 * @param viewTypeCount The maximum number of unique layout id's used to construct the list of
4620 * RemoteViews. This count cannot change during the life-cycle of a given widget, so this
4621 * parameter should account for the maximum possible number of types that may appear in the
4622 * See {@link Adapter#getViewTypeCount()}.
4623 *
4624 * @hide
4625 * @deprecated this appears to have no users outside of UnsupportedAppUsage?
4626 */
4627 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4628 @Deprecated
4629 public void setRemoteAdapter(@IdRes int viewId, ArrayList<RemoteViews> list,
4630 int viewTypeCount) {
4631 addAction(new SetRemoteViewsAdapterList(viewId, list, viewTypeCount));
4632 }
4633
4634 /**
4635 * Creates a simple Adapter for the viewId specified. The viewId must point to an AdapterView,
4636 * ie. {@link ListView}, {@link GridView}, {@link StackView} or {@link AdapterViewAnimator}.
4637 * This is a simpler but less flexible approach to populating collection widgets. Its use is
4638 * encouraged for most scenarios, as long as the total memory within the list of RemoteViews
4639 * is relatively small (ie. doesn't contain large or numerous Bitmaps, see {@link
4640 * RemoteViews#setImageViewBitmap}). In the case of numerous images, the use of API is still
4641 * possible by setting image URIs instead of Bitmaps, see {@link RemoteViews#setImageViewUri}.
4642 *
4643 * This API is supported in the compatibility library for previous API levels, see
4644 * RemoteViewsCompat.
4645 *
4646 * @param viewId The id of the {@link AdapterView}.
4647 * @param items The items to display in the {@link AdapterView}.
4648 */
4649 public void setRemoteAdapter(@IdRes int viewId, @NonNull RemoteCollectionItems items) {
4650 addAction(new SetRemoteCollectionItemListAdapterAction(viewId, items));
4651 }
4652
4653 /**
4654 * Equivalent to calling {@link ListView#smoothScrollToPosition(int)}.
4655 *
4656 * @param viewId The id of the view to change
4657 * @param position Scroll to this adapter position
4658 */
4659 public void setScrollPosition(@IdRes int viewId, int position) {
4660 setInt(viewId, "smoothScrollToPosition", position);
4661 }
4662
4663 /**
4664 * Equivalent to calling {@link ListView#smoothScrollByOffset(int)}.
4665 *
4666 * @param viewId The id of the view to change
4667 * @param offset Scroll by this adapter position offset
4668 */
4669 public void setRelativeScrollPosition(@IdRes int viewId, int offset) {
4670 setInt(viewId, "smoothScrollByOffset", offset);
4671 }
4672
4673 /**
4674 * Equivalent to calling {@link android.view.View#setPadding(int, int, int, int)}.
4675 *
4676 * @param viewId The id of the view to change
4677 * @param left the left padding in pixels
4678 * @param top the top padding in pixels
4679 * @param right the right padding in pixels
4680 * @param bottom the bottom padding in pixels
4681 */
4682 public void setViewPadding(@IdRes int viewId,
4683 @Px int left, @Px int top, @Px int right, @Px int bottom) {
4684 addAction(new ViewPaddingAction(viewId, left, top, right, bottom));
4685 }
4686
4687 /**
4688 * Equivalent to calling {@link MarginLayoutParams#setMarginEnd}.
4689 * Only works if the {@link View#getLayoutParams()} supports margins.
4690 *
4691 * @param viewId The id of the view to change
4692 * @param type The margin being set e.g. {@link #MARGIN_END}
4693 * @param dimen a dimension resource to apply to the margin, or 0 to clear the margin.
4694 */
4695 public void setViewLayoutMarginDimen(@IdRes int viewId, @MarginType int type,
4696 @DimenRes int dimen) {
4697 addAction(new LayoutParamAction(viewId, type, dimen, VALUE_TYPE_RESOURCE));
4698 }
4699
4700 /**
4701 * Equivalent to calling {@link MarginLayoutParams#setMarginEnd}.
4702 * Only works if the {@link View#getLayoutParams()} supports margins.
4703 *
4704 * @param viewId The id of the view to change
4705 * @param type The margin being set e.g. {@link #MARGIN_END}
4706 * @param attr a dimension attribute to apply to the margin, or 0 to clear the margin.
4707 */
4708 public void setViewLayoutMarginAttr(@IdRes int viewId, @MarginType int type,
4709 @AttrRes int attr) {
4710 addAction(new LayoutParamAction(viewId, type, attr, VALUE_TYPE_ATTRIBUTE));
4711 }
4712
4713 /**
4714 * Equivalent to calling {@link MarginLayoutParams#setMarginEnd}.
4715 * Only works if the {@link View#getLayoutParams()} supports margins.
4716 *
4717 * <p>NOTE: It is recommended to use {@link TypedValue#COMPLEX_UNIT_PX} only for 0.
4718 * Setting margins in pixels will behave poorly when the RemoteViews object is used on a
4719 * display with a different density.
4720 *
4721 * @param viewId The id of the view to change
4722 * @param type The margin being set e.g. {@link #MARGIN_END}
4723 * @param value a value for the margin the given units.
4724 * @param units The unit type of the value e.g. {@link TypedValue#COMPLEX_UNIT_DIP}
4725 */
4726 public void setViewLayoutMargin(@IdRes int viewId, @MarginType int type, float value,
4727 @ComplexDimensionUnit int units) {
4728 addAction(new LayoutParamAction(viewId, type, value, units));
4729 }
4730
4731 /**
4732 * Equivalent to setting {@link android.view.ViewGroup.LayoutParams#width} except that you may
4733 * provide the value in any dimension units.
4734 *
4735 * <p>NOTE: It is recommended to use {@link TypedValue#COMPLEX_UNIT_PX} only for 0,
4736 * {@link ViewGroup.LayoutParams#WRAP_CONTENT}, or {@link ViewGroup.LayoutParams#MATCH_PARENT}.
4737 * Setting actual sizes in pixels will behave poorly when the RemoteViews object is used on a
4738 * display with a different density.
4739 *
4740 * @param width Width of the view in the given units
4741 * @param units The unit type of the value e.g. {@link TypedValue#COMPLEX_UNIT_DIP}
4742 */
4743 public void setViewLayoutWidth(@IdRes int viewId, float width,
4744 @ComplexDimensionUnit int units) {
4745 addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_WIDTH, width, units));
4746 }
4747
4748 /**
4749 * Equivalent to setting {@link android.view.ViewGroup.LayoutParams#width} with
4750 * the result of {@link Resources#getDimensionPixelSize(int)}.
4751 *
4752 * @param widthDimen the dimension resource for the view's width
4753 */
4754 public void setViewLayoutWidthDimen(@IdRes int viewId, @DimenRes int widthDimen) {
4755 addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_WIDTH, widthDimen,
4756 VALUE_TYPE_RESOURCE));
4757 }
4758
4759 /**
4760 * Equivalent to setting {@link android.view.ViewGroup.LayoutParams#width} with
4761 * the value of the given attribute in the current theme.
4762 *
4763 * @param widthAttr the dimension attribute for the view's width
4764 */
4765 public void setViewLayoutWidthAttr(@IdRes int viewId, @AttrRes int widthAttr) {
4766 addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_WIDTH, widthAttr,
4767 VALUE_TYPE_ATTRIBUTE));
4768 }
4769
4770 /**
4771 * Equivalent to setting {@link android.view.ViewGroup.LayoutParams#height} except that you may
4772 * provide the value in any dimension units.
4773 *
4774 * <p>NOTE: It is recommended to use {@link TypedValue#COMPLEX_UNIT_PX} only for 0,
4775 * {@link ViewGroup.LayoutParams#WRAP_CONTENT}, or {@link ViewGroup.LayoutParams#MATCH_PARENT}.
4776 * Setting actual sizes in pixels will behave poorly when the RemoteViews object is used on a
4777 * display with a different density.
4778 *
4779 * @param height height of the view in the given units
4780 * @param units The unit type of the value e.g. {@link TypedValue#COMPLEX_UNIT_DIP}
4781 */
4782 public void setViewLayoutHeight(@IdRes int viewId, float height,
4783 @ComplexDimensionUnit int units) {
4784 addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_HEIGHT, height, units));
4785 }
4786
4787 /**
4788 * Equivalent to setting {@link android.view.ViewGroup.LayoutParams#height} with
4789 * the result of {@link Resources#getDimensionPixelSize(int)}.
4790 *
4791 * @param heightDimen a dimen resource to read the height from.
4792 */
4793 public void setViewLayoutHeightDimen(@IdRes int viewId, @DimenRes int heightDimen) {
4794 addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_HEIGHT, heightDimen,
4795 VALUE_TYPE_RESOURCE));
4796 }
4797
4798 /**
4799 * Equivalent to setting {@link android.view.ViewGroup.LayoutParams#height} with
4800 * the value of the given attribute in the current theme.
4801 *
4802 * @param heightAttr a dimen attribute to read the height from.
4803 */
4804 public void setViewLayoutHeightAttr(@IdRes int viewId, @AttrRes int heightAttr) {
4805 addAction(new LayoutParamAction(viewId, LayoutParamAction.LAYOUT_HEIGHT, heightAttr,
4806 VALUE_TYPE_ATTRIBUTE));
4807 }
4808
4809 /**
4810 * Sets an OutlineProvider on the view whose corner radius is a dimension calculated using
4811 * {@link TypedValue#applyDimension(int, float, DisplayMetrics)}.
4812 *
4813 * <p>NOTE: It is recommended to use {@link TypedValue#COMPLEX_UNIT_PX} only for 0.
4814 * Setting margins in pixels will behave poorly when the RemoteViews object is used on a
4815 * display with a different density.
4816 */
4817 public void setViewOutlinePreferredRadius(
4818 @IdRes int viewId, float radius, @ComplexDimensionUnit int units) {
4819 addAction(new SetViewOutlinePreferredRadiusAction(viewId, radius, units));
4820 }
4821
4822 /**
4823 * Sets an OutlineProvider on the view whose corner radius is a dimension resource with
4824 * {@code resId}.
4825 */
4826 public void setViewOutlinePreferredRadiusDimen(@IdRes int viewId, @DimenRes int resId) {
4827 addAction(new SetViewOutlinePreferredRadiusAction(viewId, resId, VALUE_TYPE_RESOURCE));
4828 }
4829
4830 /**
4831 * Sets an OutlineProvider on the view whose corner radius is a dimension attribute with
4832 * {@code attrId}.
4833 */
4834 public void setViewOutlinePreferredRadiusAttr(@IdRes int viewId, @AttrRes int attrId) {
4835 addAction(new SetViewOutlinePreferredRadiusAction(viewId, attrId, VALUE_TYPE_ATTRIBUTE));
4836 }
4837
4838 /**
4839 * Call a method taking one boolean on a view in the layout for this RemoteViews.
4840 *
4841 * @param viewId The id of the view on which to call the method.
4842 * @param methodName The name of the method to call.
4843 * @param value The value to pass to the method.
4844 */
4845 public void setBoolean(@IdRes int viewId, String methodName, boolean value) {
4846 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.BOOLEAN, value));
4847 }
4848
4849 /**
4850 * Call a method taking one byte on a view in the layout for this RemoteViews.
4851 *
4852 * @param viewId The id of the view on which to call the method.
4853 * @param methodName The name of the method to call.
4854 * @param value The value to pass to the method.
4855 */
4856 public void setByte(@IdRes int viewId, String methodName, byte value) {
4857 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.BYTE, value));
4858 }
4859
4860 /**
4861 * Call a method taking one short on a view in the layout for this RemoteViews.
4862 *
4863 * @param viewId The id of the view on which to call the method.
4864 * @param methodName The name of the method to call.
4865 * @param value The value to pass to the method.
4866 */
4867 public void setShort(@IdRes int viewId, String methodName, short value) {
4868 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.SHORT, value));
4869 }
4870
4871 /**
4872 * Call a method taking one int on a view in the layout for this RemoteViews.
4873 *
4874 * @param viewId The id of the view on which to call the method.
4875 * @param methodName The name of the method to call.
4876 * @param value The value to pass to the method.
4877 */
4878 public void setInt(@IdRes int viewId, String methodName, int value) {
4879 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.INT, value));
4880 }
4881
4882 /**
4883 * Call a method taking one int, a size in pixels, on a view in the layout for this
4884 * RemoteViews.
4885 *
4886 * The dimension will be resolved from the resources at the time the {@link RemoteViews} is
4887 * (re-)applied.
4888 *
4889 * Undefined resources will result in an exception, except 0 which will resolve to 0.
4890 *
4891 * @param viewId The id of the view on which to call the method.
4892 * @param methodName The name of the method to call.
4893 * @param dimenResource The resource to resolve and pass as argument to the method.
4894 */
4895 public void setIntDimen(@IdRes int viewId, @NonNull String methodName,
4896 @DimenRes int dimenResource) {
4897 addAction(new ResourceReflectionAction(viewId, methodName, BaseReflectionAction.INT,
4898 ResourceReflectionAction.DIMEN_RESOURCE, dimenResource));
4899 }
4900
4901 /**
4902 * Call a method taking one int, a size in pixels, on a view in the layout for this
4903 * RemoteViews.
4904 *
4905 * The dimension will be resolved from the specified dimension at the time of inflation.
4906 *
4907 * @param viewId The id of the view on which to call the method.
4908 * @param methodName The name of the method to call.
4909 * @param value The value of the dimension.
4910 * @param unit The unit in which the value is specified.
4911 */
4912 public void setIntDimen(@IdRes int viewId, @NonNull String methodName,
4913 float value, @ComplexDimensionUnit int unit) {
4914 addAction(new ComplexUnitDimensionReflectionAction(viewId, methodName, ReflectionAction.INT,
4915 value, unit));
4916 }
4917
4918 /**
4919 * Call a method taking one int, a size in pixels, on a view in the layout for this
4920 * RemoteViews.
4921 *
4922 * The dimension will be resolved from the theme attribute at the time the
4923 * {@link RemoteViews} is (re-)applied.
4924 *
4925 * Unresolvable attributes will result in an exception, except 0 which will resolve to 0.
4926 *
4927 * @param viewId The id of the view on which to call the method.
4928 * @param methodName The name of the method to call.
4929 * @param dimenAttr The attribute to resolve and pass as argument to the method.
4930 */
4931 public void setIntDimenAttr(@IdRes int viewId, @NonNull String methodName,
4932 @AttrRes int dimenAttr) {
4933 addAction(new AttributeReflectionAction(viewId, methodName, BaseReflectionAction.INT,
4934 ResourceReflectionAction.DIMEN_RESOURCE, dimenAttr));
4935 }
4936
4937 /**
4938 * Call a method taking one int, a color, on a view in the layout for this RemoteViews.
4939 *
4940 * The Color will be resolved from the resources at the time the {@link RemoteViews} is (re-)
4941 * applied.
4942 *
4943 * Undefined resources will result in an exception, except 0 which will resolve to 0.
4944 *
4945 * @param viewId The id of the view on which to call the method.
4946 * @param methodName The name of the method to call.
4947 * @param colorResource The resource to resolve and pass as argument to the method.
4948 */
4949 public void setColor(@IdRes int viewId, @NonNull String methodName,
4950 @ColorRes int colorResource) {
4951 addAction(new ResourceReflectionAction(viewId, methodName, BaseReflectionAction.INT,
4952 ResourceReflectionAction.COLOR_RESOURCE, colorResource));
4953 }
4954
4955 /**
4956 * Call a method taking one int, a color, on a view in the layout for this RemoteViews.
4957 *
4958 * The Color will be resolved from the theme attribute at the time the {@link RemoteViews} is
4959 * (re-)applied.
4960 *
4961 * Unresolvable attributes will result in an exception, except 0 which will resolve to 0.
4962 *
4963 * @param viewId The id of the view on which to call the method.
4964 * @param methodName The name of the method to call.
4965 * @param colorAttribute The theme attribute to resolve and pass as argument to the method.
4966 */
4967 public void setColorAttr(@IdRes int viewId, @NonNull String methodName,
4968 @AttrRes int colorAttribute) {
4969 addAction(new AttributeReflectionAction(viewId, methodName, BaseReflectionAction.INT,
4970 AttributeReflectionAction.COLOR_RESOURCE, colorAttribute));
4971 }
4972
4973 /**
4974 * Call a method taking one int, a color, on a view in the layout for this RemoteViews.
4975 *
4976 * @param viewId The id of the view on which to call the method.
4977 * @param methodName The name of the method to call.
4978 * @param notNight The value to pass to the method when the view's configuration is set to
4979 * {@link Configuration#UI_MODE_NIGHT_NO}
4980 * @param night The value to pass to the method when the view's configuration is set to
4981 * {@link Configuration#UI_MODE_NIGHT_YES}
4982 */
4983 public void setColorInt(
4984 @IdRes int viewId,
4985 @NonNull String methodName,
4986 @ColorInt int notNight,
4987 @ColorInt int night) {
4988 addAction(
4989 new NightModeReflectionAction(
4990 viewId,
4991 methodName,
4992 BaseReflectionAction.INT,
4993 notNight,
4994 night));
4995 }
4996
4997
4998 /**
4999 * Call a method taking one ColorStateList on a view in the layout for this RemoteViews.
5000 *
5001 * @param viewId The id of the view on which to call the method.
5002 * @param methodName The name of the method to call.
5003 * @param value The value to pass to the method.
5004 */
5005 public void setColorStateList(@IdRes int viewId, @NonNull String methodName,
5006 @Nullable ColorStateList value) {
5007 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.COLOR_STATE_LIST,
5008 value));
5009 }
5010
5011 /**
5012 * Call a method taking one ColorStateList on a view in the layout for this RemoteViews.
5013 *
5014 * @param viewId The id of the view on which to call the method.
5015 * @param methodName The name of the method to call.
5016 * @param notNight The value to pass to the method when the view's configuration is set to
5017 * {@link Configuration#UI_MODE_NIGHT_NO}
5018 * @param night The value to pass to the method when the view's configuration is set to
5019 * {@link Configuration#UI_MODE_NIGHT_YES}
5020 */
5021 public void setColorStateList(
5022 @IdRes int viewId,
5023 @NonNull String methodName,
5024 @Nullable ColorStateList notNight,
5025 @Nullable ColorStateList night) {
5026 addAction(
5027 new NightModeReflectionAction(
5028 viewId,
5029 methodName,
5030 BaseReflectionAction.COLOR_STATE_LIST,
5031 notNight,
5032 night));
5033 }
5034
5035 /**
5036 * Call a method taking one ColorStateList on a view in the layout for this RemoteViews.
5037 *
5038 * The ColorStateList will be resolved from the resources at the time the {@link RemoteViews} is
5039 * (re-)applied.
5040 *
5041 * Undefined resources will result in an exception, except 0 which will resolve to null.
5042 *
5043 * @param viewId The id of the view on which to call the method.
5044 * @param methodName The name of the method to call.
5045 * @param colorResource The resource to resolve and pass as argument to the method.
5046 */
5047 public void setColorStateList(@IdRes int viewId, @NonNull String methodName,
5048 @ColorRes int colorResource) {
5049 addAction(new ResourceReflectionAction(viewId, methodName,
5050 BaseReflectionAction.COLOR_STATE_LIST, ResourceReflectionAction.COLOR_RESOURCE,
5051 colorResource));
5052 }
5053
5054 /**
5055 * Call a method taking one ColorStateList on a view in the layout for this RemoteViews.
5056 *
5057 * The ColorStateList will be resolved from the theme attribute at the time the
5058 * {@link RemoteViews} is (re-)applied.
5059 *
5060 * Unresolvable attributes will result in an exception, except 0 which will resolve to null.
5061 *
5062 * @param viewId The id of the view on which to call the method.
5063 * @param methodName The name of the method to call.
5064 * @param colorAttr The theme attribute to resolve and pass as argument to the method.
5065 */
5066 public void setColorStateListAttr(@IdRes int viewId, @NonNull String methodName,
5067 @AttrRes int colorAttr) {
5068 addAction(new AttributeReflectionAction(viewId, methodName,
5069 BaseReflectionAction.COLOR_STATE_LIST, ResourceReflectionAction.COLOR_RESOURCE,
5070 colorAttr));
5071 }
5072
5073 /**
5074 * Call a method taking one long on a view in the layout for this RemoteViews.
5075 *
5076 * @param viewId The id of the view on which to call the method.
5077 * @param methodName The name of the method to call.
5078 * @param value The value to pass to the method.
5079 */
5080 public void setLong(@IdRes int viewId, String methodName, long value) {
5081 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.LONG, value));
5082 }
5083
5084 /**
5085 * Call a method taking one float on a view in the layout for this RemoteViews.
5086 *
5087 * @param viewId The id of the view on which to call the method.
5088 * @param methodName The name of the method to call.
5089 * @param value The value to pass to the method.
5090 */
5091 public void setFloat(@IdRes int viewId, String methodName, float value) {
5092 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.FLOAT, value));
5093 }
5094
5095 /**
5096 * Call a method taking one float, a size in pixels, on a view in the layout for this
5097 * RemoteViews.
5098 *
5099 * The dimension will be resolved from the resources at the time the {@link RemoteViews} is
5100 * (re-)applied.
5101 *
5102 * Undefined resources will result in an exception, except 0 which will resolve to 0f.
5103 *
5104 * @param viewId The id of the view on which to call the method.
5105 * @param methodName The name of the method to call.
5106 * @param dimenResource The resource to resolve and pass as argument to the method.
5107 */
5108 public void setFloatDimen(@IdRes int viewId, @NonNull String methodName,
5109 @DimenRes int dimenResource) {
5110 addAction(new ResourceReflectionAction(viewId, methodName, BaseReflectionAction.FLOAT,
5111 ResourceReflectionAction.DIMEN_RESOURCE, dimenResource));
5112 }
5113
5114 /**
5115 * Call a method taking one float, a size in pixels, on a view in the layout for this
5116 * RemoteViews.
5117 *
5118 * The dimension will be resolved from the resources at the time the {@link RemoteViews} is
5119 * (re-)applied.
5120 *
5121 * @param viewId The id of the view on which to call the method.
5122 * @param methodName The name of the method to call.
5123 * @param value The value of the dimension.
5124 * @param unit The unit in which the value is specified.
5125 */
5126 public void setFloatDimen(@IdRes int viewId, @NonNull String methodName,
5127 float value, @ComplexDimensionUnit int unit) {
5128 addAction(
5129 new ComplexUnitDimensionReflectionAction(viewId, methodName, ReflectionAction.FLOAT,
5130 value, unit));
5131 }
5132
5133 /**
5134 * Call a method taking one float, a size in pixels, on a view in the layout for this
5135 * RemoteViews.
5136 *
5137 * The dimension will be resolved from the theme attribute at the time the {@link RemoteViews}
5138 * is (re-)applied.
5139 *
5140 * Unresolvable attributes will result in an exception, except 0 which will resolve to 0f.
5141 *
5142 * @param viewId The id of the view on which to call the method.
5143 * @param methodName The name of the method to call.
5144 * @param dimenAttr The attribute to resolve and pass as argument to the method.
5145 */
5146 public void setFloatDimenAttr(@IdRes int viewId, @NonNull String methodName,
5147 @AttrRes int dimenAttr) {
5148 addAction(new AttributeReflectionAction(viewId, methodName, BaseReflectionAction.FLOAT,
5149 ResourceReflectionAction.DIMEN_RESOURCE, dimenAttr));
5150 }
5151
5152 /**
5153 * Call a method taking one double on a view in the layout for this RemoteViews.
5154 *
5155 * @param viewId The id of the view on which to call the method.
5156 * @param methodName The name of the method to call.
5157 * @param value The value to pass to the method.
5158 */
5159 public void setDouble(@IdRes int viewId, String methodName, double value) {
5160 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.DOUBLE, value));
5161 }
5162
5163 /**
5164 * Call a method taking one char on a view in the layout for this RemoteViews.
5165 *
5166 * @param viewId The id of the view on which to call the method.
5167 * @param methodName The name of the method to call.
5168 * @param value The value to pass to the method.
5169 */
5170 public void setChar(@IdRes int viewId, String methodName, char value) {
5171 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.CHAR, value));
5172 }
5173
5174 /**
5175 * Call a method taking one String on a view in the layout for this RemoteViews.
5176 *
5177 * @param viewId The id of the view on which to call the method.
5178 * @param methodName The name of the method to call.
5179 * @param value The value to pass to the method.
5180 */
5181 public void setString(@IdRes int viewId, String methodName, String value) {
5182 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.STRING, value));
5183 }
5184
5185 /**
5186 * Call a method taking one CharSequence on a view in the layout for this RemoteViews.
5187 *
5188 * @param viewId The id of the view on which to call the method.
5189 * @param methodName The name of the method to call.
5190 * @param value The value to pass to the method.
5191 */
5192 public void setCharSequence(@IdRes int viewId, String methodName, CharSequence value) {
5193 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.CHAR_SEQUENCE,
5194 value));
5195 }
5196
5197 /**
5198 * Call a method taking one CharSequence on a view in the layout for this RemoteViews.
5199 *
5200 * The CharSequence will be resolved from the resources at the time the {@link RemoteViews} is
5201 * (re-)applied.
5202 *
5203 * Undefined resources will result in an exception, except 0 which will resolve to null.
5204 *
5205 * @param viewId The id of the view on which to call the method.
5206 * @param methodName The name of the method to call.
5207 * @param stringResource The resource to resolve and pass as argument to the method.
5208 */
5209 public void setCharSequence(@IdRes int viewId, @NonNull String methodName,
5210 @StringRes int stringResource) {
5211 addAction(
5212 new ResourceReflectionAction(viewId, methodName, BaseReflectionAction.CHAR_SEQUENCE,
5213 ResourceReflectionAction.STRING_RESOURCE, stringResource));
5214 }
5215
5216 /**
5217 * Call a method taking one CharSequence on a view in the layout for this RemoteViews.
5218 *
5219 * The CharSequence will be resolved from the theme attribute at the time the
5220 * {@link RemoteViews} is (re-)applied.
5221 *
5222 * Unresolvable attributes will result in an exception, except 0 which will resolve to null.
5223 *
5224 * @param viewId The id of the view on which to call the method.
5225 * @param methodName The name of the method to call.
5226 * @param stringAttribute The attribute to resolve and pass as argument to the method.
5227 */
5228 public void setCharSequenceAttr(@IdRes int viewId, @NonNull String methodName,
5229 @AttrRes int stringAttribute) {
5230 addAction(
5231 new AttributeReflectionAction(viewId, methodName,
5232 BaseReflectionAction.CHAR_SEQUENCE,
5233 AttributeReflectionAction.STRING_RESOURCE, stringAttribute));
5234 }
5235
5236 /**
5237 * Call a method taking one Uri on a view in the layout for this RemoteViews.
5238 *
5239 * @param viewId The id of the view on which to call the method.
5240 * @param methodName The name of the method to call.
5241 * @param value The value to pass to the method.
5242 */
5243 public void setUri(@IdRes int viewId, String methodName, Uri value) {
5244 if (value != null) {
5245 // Resolve any filesystem path before sending remotely
5246 value = value.getCanonicalUri();
5247 if (StrictMode.vmFileUriExposureEnabled()) {
5248 value.checkFileUriExposed("RemoteViews.setUri()");
5249 }
5250 }
5251 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.URI, value));
5252 }
5253
5254 /**
5255 * Call a method taking one Bitmap on a view in the layout for this RemoteViews.
5256 * @more
5257 * <p class="note">The bitmap will be flattened into the parcel if this object is
5258 * sent across processes, so it may end up using a lot of memory, and may be fairly slow.</p>
5259 *
5260 * @param viewId The id of the view on which to call the method.
5261 * @param methodName The name of the method to call.
5262 * @param value The value to pass to the method.
5263 */
5264 public void setBitmap(@IdRes int viewId, String methodName, Bitmap value) {
5265 addAction(new BitmapReflectionAction(viewId, methodName, value));
5266 }
5267
5268 /**
5269 * Call a method taking one BlendMode on a view in the layout for this RemoteViews.
5270 *
5271 * @param viewId The id of the view on which to call the method.
5272 * @param methodName The name of the method to call.
5273 * @param value The value to pass to the method.
5274 */
5275 public void setBlendMode(@IdRes int viewId, @NonNull String methodName,
5276 @Nullable BlendMode value) {
5277 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.BLEND_MODE, value));
5278 }
5279
5280 /**
5281 * Call a method taking one Bundle on a view in the layout for this RemoteViews.
5282 *
5283 * @param viewId The id of the view on which to call the method.
5284 * @param methodName The name of the method to call.
5285 * @param value The value to pass to the method.
5286 */
5287 public void setBundle(@IdRes int viewId, String methodName, Bundle value) {
5288 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.BUNDLE, value));
5289 }
5290
5291 /**
5292 * Call a method taking one Intent on a view in the layout for this RemoteViews.
5293 *
5294 * @param viewId The id of the view on which to call the method.
5295 * @param methodName The name of the method to call.
5296 * @param value The {@link android.content.Intent} to pass the method.
5297 */
5298 public void setIntent(@IdRes int viewId, String methodName, Intent value) {
5299 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.INTENT, value));
5300 }
5301
5302 /**
5303 * Call a method taking one Icon on a view in the layout for this RemoteViews.
5304 *
5305 * @param viewId The id of the view on which to call the method.
5306 * @param methodName The name of the method to call.
5307 * @param value The {@link android.graphics.drawable.Icon} to pass the method.
5308 */
5309 public void setIcon(@IdRes int viewId, String methodName, Icon value) {
5310 addAction(new ReflectionAction(viewId, methodName, BaseReflectionAction.ICON, value));
5311 }
5312
5313 /**
5314 * Call a method taking one Icon on a view in the layout for this RemoteViews.
5315 *
5316 * @param viewId The id of the view on which to call the method.
5317 * @param methodName The name of the method to call.
5318 * @param notNight The value to pass to the method when the view's configuration is set to
5319 * {@link Configuration#UI_MODE_NIGHT_NO}
5320 * @param night The value to pass to the method when the view's configuration is set to
5321 * {@link Configuration#UI_MODE_NIGHT_YES}
5322 */
5323 public void setIcon(
5324 @IdRes int viewId,
5325 @NonNull String methodName,
5326 @Nullable Icon notNight,
5327 @Nullable Icon night) {
5328 addAction(
5329 new NightModeReflectionAction(
5330 viewId,
5331 methodName,
5332 BaseReflectionAction.ICON,
5333 notNight,
5334 night));
5335 }
5336
5337 /**
5338 * Equivalent to calling View.setContentDescription(CharSequence).
5339 *
5340 * @param viewId The id of the view whose content description should change.
5341 * @param contentDescription The new content description for the view.
5342 */
5343 public void setContentDescription(@IdRes int viewId, CharSequence contentDescription) {
5344 setCharSequence(viewId, "setContentDescription", contentDescription);
5345 }
5346
5347 /**
5348 * Equivalent to calling {@link android.view.View#setAccessibilityTraversalBefore(int)}.
5349 *
5350 * @param viewId The id of the view whose before view in accessibility traversal to set.
5351 * @param nextId The id of the next in the accessibility traversal.
5352 **/
5353 public void setAccessibilityTraversalBefore(@IdRes int viewId, @IdRes int nextId) {
5354 setInt(viewId, "setAccessibilityTraversalBefore", nextId);
5355 }
5356
5357 /**
5358 * Equivalent to calling {@link android.view.View#setAccessibilityTraversalAfter(int)}.
5359 *
5360 * @param viewId The id of the view whose after view in accessibility traversal to set.
5361 * @param nextId The id of the next in the accessibility traversal.
5362 **/
5363 public void setAccessibilityTraversalAfter(@IdRes int viewId, @IdRes int nextId) {
5364 setInt(viewId, "setAccessibilityTraversalAfter", nextId);
5365 }
5366
5367 /**
5368 * Equivalent to calling {@link View#setLabelFor(int)}.
5369 *
5370 * @param viewId The id of the view whose property to set.
5371 * @param labeledId The id of a view for which this view serves as a label.
5372 */
5373 public void setLabelFor(@IdRes int viewId, @IdRes int labeledId) {
5374 setInt(viewId, "setLabelFor", labeledId);
5375 }
5376
5377 /**
5378 * Equivalent to calling {@link android.widget.CompoundButton#setChecked(boolean)}.
5379 *
5380 * @param viewId The id of the view whose property to set.
5381 * @param checked true to check the button, false to uncheck it.
5382 */
5383 public void setCompoundButtonChecked(@IdRes int viewId, boolean checked) {
5384 addAction(new SetCompoundButtonCheckedAction(viewId, checked));
5385 }
5386
5387 /**
5388 * Equivalent to calling {@link android.widget.RadioGroup#check(int)}.
5389 *
5390 * @param viewId The id of the view whose property to set.
5391 * @param checkedId The unique id of the radio button to select in the group.
5392 */
5393 public void setRadioGroupChecked(@IdRes int viewId, @IdRes int checkedId) {
5394 addAction(new SetRadioGroupCheckedAction(viewId, checkedId));
5395 }
5396
5397 /**
5398 * Provides an alternate layout ID, which can be used to inflate this view. This layout will be
5399 * used by the host when the widgets displayed on a light-background where foreground elements
5400 * and text can safely draw using a dark color without any additional background protection.
5401 */
5402 public void setLightBackgroundLayoutId(@LayoutRes int layoutId) {
5403 mLightBackgroundLayoutId = layoutId;
5404 }
5405
5406 /**
5407 * If this view supports dark text versions, creates a copy representing that version,
5408 * otherwise returns itself.
5409 * @hide
5410 */
5411 public RemoteViews getDarkTextViews() {
5412 if (hasFlags(FLAG_USE_LIGHT_BACKGROUND_LAYOUT)) {
5413 return this;
5414 }
5415
5416 try {
5417 addFlags(FLAG_USE_LIGHT_BACKGROUND_LAYOUT);
5418 return new RemoteViews(this);
5419 } finally {
5420 mApplyFlags &= ~FLAG_USE_LIGHT_BACKGROUND_LAYOUT;
5421 }
5422 }
5423
5424 private RemoteViews getRemoteViewsToApply(Context context) {
5425 if (hasLandscapeAndPortraitLayouts()) {
5426 int orientation = context.getResources().getConfiguration().orientation;
5427 if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
5428 return mLandscape;
5429 }
5430 return mPortrait;
5431 }
5432 if (hasSizedRemoteViews()) {
5433 return findSmallestRemoteView();
5434 }
5435 return this;
5436 }
5437
5438 /**
5439 * Returns the square distance between two points.
5440 *
5441 * This is particularly useful when we only care about the ordering of the distances.
5442 */
5443 private static float squareDistance(SizeF p1, SizeF p2) {
5444 float dx = p1.getWidth() - p2.getWidth();
5445 float dy = p1.getHeight() - p2.getHeight();
5446 return dx * dx + dy * dy;
5447 }
5448
5449 /**
5450 * Returns whether the layout fits in the space available to the widget.
5451 *
5452 * A layout fits on a widget if the widget size is known (i.e. not null) and both dimensions
5453 * are smaller than the ones of the widget, adding some padding to account for rounding errors.
5454 */
5455 private static boolean fitsIn(SizeF sizeLayout, @Nullable SizeF sizeWidget) {
5456 return sizeWidget != null && (Math.ceil(sizeWidget.getWidth()) + 1 > sizeLayout.getWidth())
5457 && (Math.ceil(sizeWidget.getHeight()) + 1 > sizeLayout.getHeight());
5458 }
5459
5460 private RemoteViews findBestFitLayout(@NonNull SizeF widgetSize) {
5461 // Find the better remote view
5462 RemoteViews bestFit = null;
5463 float bestSqDist = Float.MAX_VALUE;
5464 for (RemoteViews layout : mSizedRemoteViews) {
5465 SizeF layoutSize = layout.getIdealSize();
5466 if (layoutSize == null) {
5467 throw new IllegalStateException("Expected RemoteViews to have ideal size");
5468 }
5469
5470 if (fitsIn(layoutSize, widgetSize)) {
5471 if (bestFit == null) {
5472 bestFit = layout;
5473 bestSqDist = squareDistance(layoutSize, widgetSize);
5474 } else {
5475 float newSqDist = squareDistance(layoutSize, widgetSize);
5476 if (newSqDist < bestSqDist) {
5477 bestFit = layout;
5478 bestSqDist = newSqDist;
5479 }
5480 }
5481 }
5482 }
5483 if (bestFit == null) {
5484 Log.w(LOG_TAG, "Could not find a RemoteViews fitting the current size: " + widgetSize);
5485 return findSmallestRemoteView();
5486 }
5487 return bestFit;
5488 }
5489
5490 /**
5491 * Returns the most appropriate {@link RemoteViews} given the context and, if not null, the
5492 * size of the widget.
5493 *
5494 * If {@link RemoteViews#hasSizedRemoteViews()} returns true, the most appropriate view is
5495 * the one that fits in the widget (according to {@link RemoteViews#fitsIn}) and has the
5496 * diagonal the most similar to the widget. If no layout fits or the size of the widget is
5497 * not specified, the one with the smallest area will be chosen.
5498 *
5499 * @hide
5500 */
5501 public RemoteViews getRemoteViewsToApply(@NonNull Context context,
5502 @Nullable SizeF widgetSize) {
5503 if (!hasSizedRemoteViews() || widgetSize == null) {
5504 // If there isn't multiple remote views, fall back on the previous methods.
5505 return getRemoteViewsToApply(context);
5506 }
5507 return findBestFitLayout(widgetSize);
5508 }
5509
5510 /**
5511 * Checks whether the change of size will lead to using a different {@link RemoteViews}.
5512 *
5513 * @hide
5514 */
5515 @Nullable
5516 public RemoteViews getRemoteViewsToApplyIfDifferent(@Nullable SizeF oldSize,
5517 @NonNull SizeF newSize) {
5518 if (!hasSizedRemoteViews()) {
5519 return null;
5520 }
5521 RemoteViews oldBestFit = oldSize == null ? findSmallestRemoteView() : findBestFitLayout(
5522 oldSize);
5523 RemoteViews newBestFit = findBestFitLayout(newSize);
5524 if (oldBestFit != newBestFit) {
5525 return newBestFit;
5526 }
5527 return null;
5528 }
5529
5530
5531 /**
5532 * Inflates the view hierarchy represented by this object and applies
5533 * all of the actions.
5534 *
5535 * <p><strong>Caller beware: this may throw</strong>
5536 *
5537 * @param context Default context to use
5538 * @param parent Parent that the resulting view hierarchy will be attached to. This method
5539 * does <strong>not</strong> attach the hierarchy. The caller should do so when appropriate.
5540 * @return The inflated view hierarchy
5541 */
5542 public View apply(Context context, ViewGroup parent) {
5543 return apply(context, parent, null);
5544 }
5545
5546 /** @hide */
5547 public View apply(Context context, ViewGroup parent, InteractionHandler handler) {
5548 return apply(context, parent, handler, null);
5549 }
5550
5551 /** @hide */
5552 public View apply(@NonNull Context context, @NonNull ViewGroup parent,
5553 @Nullable InteractionHandler handler, @Nullable SizeF size) {
5554 return apply(context, parent, size, new ActionApplyParams()
5555 .withInteractionHandler(handler));
5556 }
5557
5558 /** @hide */
5559 public View applyWithTheme(@NonNull Context context, @NonNull ViewGroup parent,
5560 @Nullable InteractionHandler handler, @StyleRes int applyThemeResId) {
5561 return apply(context, parent, null, new ActionApplyParams()
5562 .withInteractionHandler(handler)
5563 .withThemeResId(applyThemeResId));
5564 }
5565
5566 /** @hide */
5567 public View apply(Context context, ViewGroup parent, InteractionHandler handler,
5568 @Nullable SizeF size, @Nullable ColorResources colorResources) {
5569 return apply(context, parent, size, new ActionApplyParams()
5570 .withInteractionHandler(handler)
5571 .withColorResources(colorResources));
5572 }
5573
5574 /** @hide **/
5575 public View apply(Context context, ViewGroup parent, @Nullable SizeF size,
5576 ActionApplyParams params) {
5577 return apply(context, parent, parent, size, params);
5578 }
5579
5580 private View apply(Context context, ViewGroup directParent, ViewGroup rootParent,
5581 @Nullable SizeF size, ActionApplyParams params) {
5582 RemoteViews rvToApply = getRemoteViewsToApply(context, size);
5583 View result = inflateView(context, rvToApply, directParent,
5584 params.applyThemeResId, params.colorResources);
5585 rvToApply.performApply(result, rootParent, params);
5586 return result;
5587 }
5588
5589 private View inflateView(Context context, RemoteViews rv, @Nullable ViewGroup parent,
5590 @StyleRes int applyThemeResId, @Nullable ColorResources colorResources) {
5591 // RemoteViews may be built by an application installed in another
5592 // user. So build a context that loads resources from that user but
5593 // still returns the current users userId so settings like data / time formats
5594 // are loaded without requiring cross user persmissions.
5595 final Context contextForResources =
5596 getContextForResourcesEnsuringCorrectCachedApkPaths(context);
5597 if (colorResources != null) {
5598 colorResources.apply(contextForResources);
5599 }
5600 Context inflationContext = new RemoteViewsContextWrapper(context, contextForResources);
5601
5602 // If mApplyThemeResId is not given, Theme.DeviceDefault will be used.
5603 if (applyThemeResId != 0) {
5604 inflationContext = new ContextThemeWrapper(inflationContext, applyThemeResId);
5605 }
5606 LayoutInflater inflater = LayoutInflater.from(context);
5607
5608 // Clone inflater so we load resources from correct context and
5609 // we don't add a filter to the static version returned by getSystemService.
5610 inflater = inflater.cloneInContext(inflationContext);
5611 inflater.setFilter(shouldUseStaticFilter() ? INFLATER_FILTER : this);
5612 View v = inflater.inflate(rv.getLayoutId(), parent, false);
5613 if (mViewId != View.NO_ID) {
5614 v.setId(mViewId);
5615 v.setTagInternal(R.id.remote_views_override_id, mViewId);
5616 }
5617 v.setTagInternal(R.id.widget_frame, rv.getLayoutId());
5618 return v;
5619 }
5620
5621 /**
5622 * A static filter is much lighter than RemoteViews itself. It's optimized here only for
5623 * RemoteVies class. Subclasses should always override this and return true if not overriding
5624 * {@link this#onLoadClass(Class)}.
5625 *
5626 * @hide
5627 */
5628 protected boolean shouldUseStaticFilter() {
5629 return this.getClass().equals(RemoteViews.class);
5630 }
5631
5632 /**
5633 * Implement this interface to receive a callback when
5634 * {@link #applyAsync} or {@link #reapplyAsync} is finished.
5635 * @hide
5636 */
5637 public interface OnViewAppliedListener {
5638 /**
5639 * Callback when the RemoteView has finished inflating,
5640 * but no actions have been applied yet.
5641 */
5642 default void onViewInflated(View v) {};
5643
5644 void onViewApplied(View v);
5645
5646 void onError(Exception e);
5647 }
5648
5649 /**
5650 * Applies the views asynchronously, moving as much of the task on the background
5651 * thread as possible.
5652 *
5653 * @see #apply(Context, ViewGroup)
5654 * @param context Default context to use
5655 * @param parent Parent that the resulting view hierarchy will be attached to. This method
5656 * does <strong>not</strong> attach the hierarchy. The caller should do so when appropriate.
5657 * @param listener the callback to run when all actions have been applied. May be null.
5658 * @param executor The executor to use. If null {@link AsyncTask#THREAD_POOL_EXECUTOR} is used.
5659 * @return CancellationSignal
5660 * @hide
5661 */
5662 public CancellationSignal applyAsync(
5663 Context context, ViewGroup parent, Executor executor, OnViewAppliedListener listener) {
5664 return applyAsync(context, parent, executor, listener, null /* handler */);
5665 }
5666
5667 /** @hide */
5668 public CancellationSignal applyAsync(Context context, ViewGroup parent,
5669 Executor executor, OnViewAppliedListener listener, InteractionHandler handler) {
5670 return applyAsync(context, parent, executor, listener, handler, null /* size */);
5671 }
5672
5673 /** @hide */
5674 public CancellationSignal applyAsync(Context context, ViewGroup parent,
5675 Executor executor, OnViewAppliedListener listener, InteractionHandler handler,
5676 SizeF size) {
5677 return applyAsync(context, parent, executor, listener, handler, size,
5678 null /* themeColors */);
5679 }
5680
5681 /** @hide */
5682 public CancellationSignal applyAsync(Context context, ViewGroup parent, Executor executor,
5683 OnViewAppliedListener listener, InteractionHandler handler, SizeF size,
5684 ColorResources colorResources) {
5685
5686 ActionApplyParams params = new ActionApplyParams()
5687 .withInteractionHandler(handler)
5688 .withColorResources(colorResources)
5689 .withExecutor(executor);
5690 return new AsyncApplyTask(getRemoteViewsToApply(context, size), parent, context, listener,
5691 params, null /* result */, true /* topLevel */).startTaskOnExecutor(executor);
5692 }
5693
5694 private AsyncApplyTask getInternalAsyncApplyTask(Context context, ViewGroup parent,
5695 OnViewAppliedListener listener, ActionApplyParams params, SizeF size, View result) {
5696 return new AsyncApplyTask(getRemoteViewsToApply(context, size), parent, context, listener,
5697 params, result, false /* topLevel */);
5698 }
5699
5700 private class AsyncApplyTask extends AsyncTask<Void, Void, ViewTree>
5701 implements CancellationSignal.OnCancelListener {
5702 final CancellationSignal mCancelSignal = new CancellationSignal();
5703 final RemoteViews mRV;
5704 final ViewGroup mParent;
5705 final Context mContext;
5706 final OnViewAppliedListener mListener;
5707 final ActionApplyParams mApplyParams;
5708
5709 /**
5710 * Whether the remote view is the top-level one (i.e. not within an action).
5711 *
5712 * This is only used if the result is specified (i.e. the view is being recycled).
5713 */
5714 final boolean mTopLevel;
5715
5716 private View mResult;
5717 private ViewTree mTree;
5718 private Action[] mActions;
5719 private Exception mError;
5720
5721 private AsyncApplyTask(
5722 RemoteViews rv, ViewGroup parent, Context context, OnViewAppliedListener listener,
5723 ActionApplyParams applyParams, View result, boolean topLevel) {
5724 mRV = rv;
5725 mParent = parent;
5726 mContext = context;
5727 mListener = listener;
5728 mTopLevel = topLevel;
5729 mApplyParams = applyParams;
5730 mResult = result;
5731 }
5732
5733 @Nullable
5734 @Override
5735 protected ViewTree doInBackground(Void... params) {
5736 try {
5737 if (mResult == null) {
5738 mResult = inflateView(mContext, mRV, mParent, 0, mApplyParams.colorResources);
5739 }
5740
5741 mTree = new ViewTree(mResult);
5742
5743 if (mRV.mActions != null) {
5744 int count = mRV.mActions.size();
5745 mActions = new Action[count];
5746 for (int i = 0; i < count && !isCancelled(); i++) {
5747 // TODO: check if isCancelled in nested views.
5748 mActions[i] = mRV.mActions.get(i)
5749 .initActionAsync(mTree, mParent, mApplyParams);
5750 }
5751 } else {
5752 mActions = null;
5753 }
5754 return mTree;
5755 } catch (Exception e) {
5756 mError = e;
5757 return null;
5758 }
5759 }
5760
5761 @Override
5762 protected void onPostExecute(ViewTree viewTree) {
5763 mCancelSignal.setOnCancelListener(null);
5764 if (mError == null) {
5765 if (mListener != null) {
5766 mListener.onViewInflated(viewTree.mRoot);
5767 }
5768
5769 try {
5770 if (mActions != null) {
5771
5772 ActionApplyParams applyParams = mApplyParams.clone();
5773 if (applyParams.handler == null) {
5774 applyParams.handler = DEFAULT_INTERACTION_HANDLER;
5775 }
5776 for (Action a : mActions) {
5777 a.apply(viewTree.mRoot, mParent, applyParams);
5778 }
5779 }
5780 // If the parent of the view is has is a root, resolve the recycling.
5781 if (mTopLevel && mResult instanceof ViewGroup) {
5782 finalizeViewRecycling((ViewGroup) mResult);
5783 }
5784 } catch (Exception e) {
5785 mError = e;
5786 }
5787 }
5788
5789 if (mListener != null) {
5790 if (mError != null) {
5791 mListener.onError(mError);
5792 } else {
5793 mListener.onViewApplied(viewTree.mRoot);
5794 }
5795 } else if (mError != null) {
5796 if (mError instanceof ActionException) {
5797 throw (ActionException) mError;
5798 } else {
5799 throw new ActionException(mError);
5800 }
5801 }
5802 }
5803
5804 @Override
5805 public void onCancel() {
5806 cancel(true);
5807 }
5808
5809 private CancellationSignal startTaskOnExecutor(Executor executor) {
5810 mCancelSignal.setOnCancelListener(this);
5811 executeOnExecutor(executor == null ? AsyncTask.THREAD_POOL_EXECUTOR : executor);
5812 return mCancelSignal;
5813 }
5814 }
5815
5816 /**
5817 * Applies all of the actions to the provided view.
5818 *
5819 * <p><strong>Caller beware: this may throw</strong>
5820 *
5821 * @param v The view to apply the actions to. This should be the result of
5822 * the {@link #apply(Context,ViewGroup)} call.
5823 */
5824 public void reapply(Context context, View v) {
5825 reapply(context, v, null /* size */, new ActionApplyParams());
5826 }
5827
5828 /** @hide */
5829 public void reapply(Context context, View v, InteractionHandler handler) {
5830 reapply(context, v, null /* size */,
5831 new ActionApplyParams().withInteractionHandler(handler));
5832 }
5833
5834 /** @hide */
5835 public void reapply(Context context, View v, InteractionHandler handler, SizeF size,
5836 ColorResources colorResources) {
5837 reapply(context, v, size, new ActionApplyParams()
5838 .withInteractionHandler(handler).withColorResources(colorResources));
5839 }
5840
5841 /** @hide */
5842 public void reapply(Context context, View v, @Nullable SizeF size, ActionApplyParams params) {
5843 reapply(context, v, (ViewGroup) v.getParent(), size, params, true);
5844 }
5845
5846 private void reapplyNestedViews(Context context, View v, ViewGroup rootParent,
5847 ActionApplyParams params) {
5848 reapply(context, v, rootParent, null, params, false);
5849 }
5850
5851 // Note: topLevel should be true only for calls on the topLevel RemoteViews, internal calls
5852 // should set it to false.
5853 private void reapply(Context context, View v, ViewGroup rootParent,
5854 @Nullable SizeF size, ActionApplyParams params, boolean topLevel) {
5855 RemoteViews rvToApply = getRemoteViewsToReapply(context, v, size);
5856 rvToApply.performApply(v, rootParent, params);
5857
5858 // If the parent of the view is has is a root, resolve the recycling.
5859 if (topLevel && v instanceof ViewGroup) {
5860 finalizeViewRecycling((ViewGroup) v);
5861 }
5862 }
5863
5864 /** @hide */
5865 public boolean canRecycleView(@Nullable View v) {
5866 if (v == null) {
5867 return false;
5868 }
5869 Integer previousLayoutId = (Integer) v.getTag(R.id.widget_frame);
5870 if (previousLayoutId == null) {
5871 return false;
5872 }
5873 Integer overrideIdTag = (Integer) v.getTag(R.id.remote_views_override_id);
5874 int overrideId = overrideIdTag == null ? View.NO_ID : overrideIdTag;
5875 // If mViewId is View.NO_ID, we only recycle if overrideId is also View.NO_ID.
5876 // Otherwise, it might be that, on a previous iteration, the view's ID was set to
5877 // something else, and it should now be reset to the ID defined in the XML layout file,
5878 // whatever it is.
5879 return previousLayoutId == getLayoutId() && mViewId == overrideId;
5880 }
5881
5882 /**
5883 * Returns the RemoteViews that should be used in the reapply operation.
5884 *
5885 * If the current RemoteViews has multiple layout, this will select the correct one.
5886 *
5887 * @throws RuntimeException If the current RemoteViews should not be reapplied onto the provided
5888 * View.
5889 */
5890 private RemoteViews getRemoteViewsToReapply(Context context, View v, @Nullable SizeF size) {
5891 RemoteViews rvToApply = getRemoteViewsToApply(context, size);
5892
5893 // In the case that a view has this RemoteViews applied in one orientation or size, is
5894 // persisted across change, and has the RemoteViews re-applied in a different situation
5895 // (orientation or size), we throw an exception, since the layouts may be completely
5896 // unrelated.
5897 // If the ViewID has been changed on the view, or is changed by the RemoteViews, we also
5898 // may throw an exception, as the RemoteViews will probably not apply properly.
5899 // However, we need to let potentially unrelated RemoteViews apply, as this lack of testing
5900 // is already used in production code in some apps.
5901 if (hasMultipleLayouts()
5902 || rvToApply.mViewId != View.NO_ID
5903 || v.getTag(R.id.remote_views_override_id) != null) {
5904 if (!rvToApply.canRecycleView(v)) {
5905 throw new RuntimeException("Attempting to re-apply RemoteViews to a view that" +
5906 " that does not share the same root layout id.");
5907 }
5908 }
5909
5910 return rvToApply;
5911 }
5912
5913 /**
5914 * Applies all the actions to the provided view, moving as much of the task on the background
5915 * thread as possible.
5916 *
5917 * @see #reapply(Context, View)
5918 * @param context Default context to use
5919 * @param v The view to apply the actions to. This should be the result of
5920 * the {@link #apply(Context,ViewGroup)} call.
5921 * @param listener the callback to run when all actions have been applied. May be null.
5922 * @param executor The executor to use. If null {@link AsyncTask#THREAD_POOL_EXECUTOR} is used
5923 * @return CancellationSignal
5924 * @hide
5925 */
5926 public CancellationSignal reapplyAsync(Context context, View v, Executor executor,
5927 OnViewAppliedListener listener) {
5928 return reapplyAsync(context, v, executor, listener, null);
5929 }
5930
5931 /** @hide */
5932 public CancellationSignal reapplyAsync(Context context, View v, Executor executor,
5933 OnViewAppliedListener listener, InteractionHandler handler) {
5934 return reapplyAsync(context, v, executor, listener, handler, null, null);
5935 }
5936
5937 /** @hide */
5938 public CancellationSignal reapplyAsync(Context context, View v, Executor executor,
5939 OnViewAppliedListener listener, InteractionHandler handler, SizeF size,
5940 ColorResources colorResources) {
5941 RemoteViews rvToApply = getRemoteViewsToReapply(context, v, size);
5942
5943 ActionApplyParams params = new ActionApplyParams()
5944 .withColorResources(colorResources)
5945 .withInteractionHandler(handler)
5946 .withExecutor(executor);
5947
5948 return new AsyncApplyTask(rvToApply, (ViewGroup) v.getParent(),
5949 context, listener, params, v, true /* topLevel */)
5950 .startTaskOnExecutor(executor);
5951 }
5952
5953 private void performApply(View v, ViewGroup parent, ActionApplyParams params) {
5954 params = params.clone();
5955 if (params.handler == null) {
5956 params.handler = DEFAULT_INTERACTION_HANDLER;
5957 }
5958 if (mActions != null) {
5959 final int count = mActions.size();
5960 for (int i = 0; i < count; i++) {
5961 mActions.get(i).apply(v, parent, params);
5962 }
5963 }
5964 }
5965
5966 /**
5967 * Returns true if the RemoteViews contains potentially costly operations and should be
5968 * applied asynchronously.
5969 *
5970 * @hide
5971 */
5972 public boolean prefersAsyncApply() {
5973 if (mActions != null) {
5974 final int count = mActions.size();
5975 for (int i = 0; i < count; i++) {
5976 if (mActions.get(i).prefersAsyncApply()) {
5977 return true;
5978 }
5979 }
5980 }
5981 return false;
5982 }
5983
5984 /** @hide */
5985 public void updateAppInfo(@NonNull ApplicationInfo info) {
5986 ApplicationInfo existing = mApplicationInfoCache.get(info);
5987 if (existing != null && !existing.sourceDir.equals(info.sourceDir)) {
5988 // Overlay paths are generated against a particular version of an application.
5989 // The overlays paths of a newly upgraded application are incompatible with the
5990 // old version of the application.
5991 return;
5992 }
5993
5994 // If we can update to the new AppInfo, put it in the cache and propagate the change
5995 // throughout the hierarchy.
5996 mApplicationInfoCache.put(info);
5997 configureDescendantsAsChildren();
5998 }
5999
6000 private Context getContextForResourcesEnsuringCorrectCachedApkPaths(Context context) {
6001 if (mApplication != null) {
6002 if (context.getUserId() == UserHandle.getUserId(mApplication.uid)
6003 && context.getPackageName().equals(mApplication.packageName)) {
6004 return context;
6005 }
6006 try {
6007 LoadedApk.checkAndUpdateApkPaths(mApplication);
6008 return context.createApplicationContext(mApplication,
6009 Context.CONTEXT_RESTRICTED);
6010 } catch (NameNotFoundException e) {
6011 Log.e(LOG_TAG, "Package name " + mApplication.packageName + " not found");
6012 }
6013 }
6014
6015 return context;
6016 }
6017
6018 /**
6019 * Utility class to hold all the options when applying the remote views
6020 * @hide
6021 */
6022 public class ActionApplyParams {
6023
6024 public InteractionHandler handler;
6025 public ColorResources colorResources;
6026 public Executor executor;
6027 @StyleRes public int applyThemeResId;
6028
6029 @Override
6030 public ActionApplyParams clone() {
6031 return new ActionApplyParams()
6032 .withInteractionHandler(handler)
6033 .withColorResources(colorResources)
6034 .withExecutor(executor)
6035 .withThemeResId(applyThemeResId);
6036 }
6037
6038 public ActionApplyParams withInteractionHandler(InteractionHandler handler) {
6039 this.handler = handler;
6040 return this;
6041 }
6042
6043 public ActionApplyParams withColorResources(ColorResources colorResources) {
6044 this.colorResources = colorResources;
6045 return this;
6046 }
6047
6048 public ActionApplyParams withThemeResId(@StyleRes int themeResId) {
6049 this.applyThemeResId = themeResId;
6050 return this;
6051 }
6052
6053 public ActionApplyParams withExecutor(Executor executor) {
6054 this.executor = executor;
6055 return this;
6056 }
6057 }
6058
6059 /**
6060 * Object allowing the modification of a context to overload the system's dynamic colors.
6061 *
6062 * Only colors from {@link android.R.color#system_accent1_0} to
6063 * {@link android.R.color#system_neutral2_1000} can be overloaded.
6064 * @hide
6065 */
6066 public static final class ColorResources {
6067 // Set of valid colors resources.
6068 private static final int FIRST_RESOURCE_COLOR_ID = android.R.color.system_neutral1_0;
6069 private static final int LAST_RESOURCE_COLOR_ID = android.R.color.system_accent3_1000;
6070 // Size, in bytes, of an entry in the array of colors in an ARSC file.
6071 private static final int ARSC_ENTRY_SIZE = 16;
6072
6073 private final ResourcesLoader mLoader;
6074 private final SparseIntArray mColorMapping;
6075
6076 private ColorResources(ResourcesLoader loader, SparseIntArray colorMapping) {
6077 mLoader = loader;
6078 mColorMapping = colorMapping;
6079 }
6080
6081 /**
6082 * Apply the color resources to the given context.
6083 *
6084 * No resource resolution must have be done on the context given to that method.
6085 */
6086 public void apply(Context context) {
6087 context.getResources().addLoaders(mLoader);
6088 }
6089
6090 public SparseIntArray getColorMapping() {
6091 return mColorMapping;
6092 }
6093
6094 private static ByteArrayOutputStream readFileContent(InputStream input) throws IOException {
6095 ByteArrayOutputStream content = new ByteArrayOutputStream(2048);
6096 byte[] buffer = new byte[4096];
6097 while (input.available() > 0) {
6098 int read = input.read(buffer);
6099 content.write(buffer, 0, read);
6100 }
6101 return content;
6102 }
6103
6104 /**
6105 * Creates the compiled resources content from the asset stored in the APK.
6106 *
6107 * The asset is a compiled resource with the correct resources name and correct ids, only
6108 * the values are incorrect. The last value is at the very end of the file. The resources
6109 * are in an array, the array's entries are 16 bytes each. We use this to work out the
6110 * location of all the positions of the various resources.
6111 */
6112 @Nullable
6113 private static byte[] createCompiledResourcesContent(Context context,
6114 SparseIntArray colorResources) throws IOException {
6115 byte[] content;
6116 try (InputStream input = context.getResources().openRawResource(
6117 com.android.internal.R.raw.remote_views_color_resources)) {
6118 ByteArrayOutputStream rawContent = readFileContent(input);
6119 content = rawContent.toByteArray();
6120 }
6121 int valuesOffset =
6122 content.length - (LAST_RESOURCE_COLOR_ID & 0xffff) * ARSC_ENTRY_SIZE - 4;
6123 if (valuesOffset < 0) {
6124 Log.e(LOG_TAG, "ARSC file for theme colors is invalid.");
6125 return null;
6126 }
6127 for (int colorRes = FIRST_RESOURCE_COLOR_ID; colorRes <= LAST_RESOURCE_COLOR_ID;
6128 colorRes++) {
6129 // The last 2 bytes are the index in the color array.
6130 int index = colorRes & 0xffff;
6131 int offset = valuesOffset + index * ARSC_ENTRY_SIZE;
6132 int value = colorResources.get(colorRes, context.getColor(colorRes));
6133 // Write the 32 bit integer in little endian
6134 for (int b = 0; b < 4; b++) {
6135 content[offset + b] = (byte) (value & 0xff);
6136 value >>= 8;
6137 }
6138 }
6139 return content;
6140 }
6141
6142 /**
6143 * Adds a resource loader for theme colors to the given context.
6144 *
6145 * @param context Context of the view hosting the widget.
6146 * @param colorMapping Mapping of resources to color values.
6147 *
6148 * @hide
6149 */
6150 @Nullable
6151 public static ColorResources create(Context context, SparseIntArray colorMapping) {
6152 try {
6153 byte[] contentBytes = createCompiledResourcesContent(context, colorMapping);
6154 if (contentBytes == null) {
6155 return null;
6156 }
6157 FileDescriptor arscFile = null;
6158 try {
6159 arscFile = Os.memfd_create("remote_views_theme_colors.arsc", 0 /* flags */);
6160 // Note: This must not be closed through the OutputStream.
6161 try (OutputStream pipeWriter = new FileOutputStream(arscFile)) {
6162 pipeWriter.write(contentBytes);
6163
6164 try (ParcelFileDescriptor pfd = ParcelFileDescriptor.dup(arscFile)) {
6165 ResourcesLoader colorsLoader = new ResourcesLoader();
6166 colorsLoader.addProvider(ResourcesProvider
6167 .loadFromTable(pfd, null /* assetsProvider */));
6168 return new ColorResources(colorsLoader, colorMapping.clone());
6169 }
6170 }
6171 } finally {
6172 if (arscFile != null) {
6173 Os.close(arscFile);
6174 }
6175 }
6176 } catch (Exception ex) {
6177 Log.e(LOG_TAG, "Failed to setup the context for theme colors", ex);
6178 }
6179 return null;
6180 }
6181 }
6182
6183 /**
6184 * Returns the number of actions in this RemoteViews. Can be used as a sequence number.
6185 *
6186 * @hide
6187 */
6188 public int getSequenceNumber() {
6189 return (mActions == null) ? 0 : mActions.size();
6190 }
6191
6192 /**
6193 * Used to restrict the views which can be inflated
6194 *
6195 * @see android.view.LayoutInflater.Filter#onLoadClass(java.lang.Class)
6196 * @deprecated Used by system to enforce safe inflation of {@link RemoteViews}. Apps should not
6197 * override this method. Changing of this method will NOT affect the process where RemoteViews
6198 * is rendered.
6199 */
6200 @Deprecated
6201 public boolean onLoadClass(Class clazz) {
6202 return clazz.isAnnotationPresent(RemoteView.class);
6203 }
6204
6205 public int describeContents() {
6206 return 0;
6207 }
6208
6209 public void writeToParcel(Parcel dest, int flags) {
6210 boolean prevSquashingAllowed = dest.allowSquashing();
6211
6212 if (!hasMultipleLayouts()) {
6213 dest.writeInt(MODE_NORMAL);
6214 // We only write the bitmap cache if we are the root RemoteViews, as this cache
6215 // is shared by all children.
6216 if (mIsRoot) {
6217 mBitmapCache.writeBitmapsToParcel(dest, flags);
6218 }
6219 mApplication.writeToParcel(dest, flags);
6220 if (mIsRoot || mIdealSize == null) {
6221 dest.writeInt(0);
6222 } else {
6223 dest.writeInt(1);
6224 mIdealSize.writeToParcel(dest, flags);
6225 }
6226 dest.writeInt(mLayoutId);
6227 dest.writeInt(mViewId);
6228 dest.writeInt(mLightBackgroundLayoutId);
6229 writeActionsToParcel(dest, flags);
6230 } else if (hasSizedRemoteViews()) {
6231 dest.writeInt(MODE_HAS_SIZED_REMOTEVIEWS);
6232 if (mIsRoot) {
6233 mBitmapCache.writeBitmapsToParcel(dest, flags);
6234 }
6235 dest.writeInt(mSizedRemoteViews.size());
6236 for (RemoteViews view : mSizedRemoteViews) {
6237 view.writeToParcel(dest, flags);
6238 }
6239 } else {
6240 dest.writeInt(MODE_HAS_LANDSCAPE_AND_PORTRAIT);
6241 // We only write the bitmap cache if we are the root RemoteViews, as this cache
6242 // is shared by all children.
6243 if (mIsRoot) {
6244 mBitmapCache.writeBitmapsToParcel(dest, flags);
6245 }
6246 mLandscape.writeToParcel(dest, flags);
6247 // Both RemoteViews already share the same package and user
6248 mPortrait.writeToParcel(dest, flags);
6249 }
6250 dest.writeInt(mApplyFlags);
6251 dest.writeLong(mProviderInstanceId);
6252
6253 dest.restoreAllowSquashing(prevSquashingAllowed);
6254 }
6255
6256 private void writeActionsToParcel(Parcel parcel, int flags) {
6257 int count;
6258 if (mActions != null) {
6259 count = mActions.size();
6260 } else {
6261 count = 0;
6262 }
6263 parcel.writeInt(count);
6264 for (int i = 0; i < count; i++) {
6265 Action a = mActions.get(i);
6266 parcel.writeInt(a.getActionTag());
6267 a.writeToParcel(parcel, flags);
6268 }
6269 }
6270
6271 @Nullable
6272 private static ApplicationInfo getApplicationInfo(@Nullable String packageName, int userId) {
6273 if (packageName == null) {
6274 return null;
6275 }
6276
6277 // Get the application for the passed in package and user.
6278 Application application = ActivityThread.currentApplication();
6279 if (application == null) {
6280 throw new IllegalStateException("Cannot create remote views out of an aplication.");
6281 }
6282
6283 ApplicationInfo applicationInfo = application.getApplicationInfo();
6284 if (UserHandle.getUserId(applicationInfo.uid) != userId
6285 || !applicationInfo.packageName.equals(packageName)) {
6286 try {
6287 Context context = application.getBaseContext().createPackageContextAsUser(
6288 packageName, 0, new UserHandle(userId));
6289 applicationInfo = context.getApplicationInfo();
6290 } catch (NameNotFoundException nnfe) {
6291 throw new IllegalArgumentException("No such package " + packageName);
6292 }
6293 }
6294
6295 return applicationInfo;
6296 }
6297
6298 /**
6299 * Returns true if the {@link #mApplication} is same as the provided info.
6300 *
6301 * @hide
6302 */
6303 public boolean hasSameAppInfo(ApplicationInfo info) {
6304 return mApplication.packageName.equals(info.packageName) && mApplication.uid == info.uid;
6305 }
6306
6307 /**
6308 * Parcelable.Creator that instantiates RemoteViews objects
6309 */
6310 public static final @android.annotation.NonNull Parcelable.Creator<RemoteViews> CREATOR = new Parcelable.Creator<RemoteViews>() {
6311 public RemoteViews createFromParcel(Parcel parcel) {
6312 return new RemoteViews(parcel);
6313 }
6314
6315 public RemoteViews[] newArray(int size) {
6316 return new RemoteViews[size];
6317 }
6318 };
6319
6320 /**
6321 * A representation of the view hierarchy. Only views which have a valid ID are added
6322 * and can be searched.
6323 */
6324 private static class ViewTree {
6325 private static final int INSERT_AT_END_INDEX = -1;
6326 private View mRoot;
6327 private ArrayList<ViewTree> mChildren;
6328
6329 private ViewTree(View root) {
6330 mRoot = root;
6331 }
6332
6333 public void createTree() {
6334 if (mChildren != null) {
6335 return;
6336 }
6337
6338 mChildren = new ArrayList<>();
6339 if (mRoot instanceof ViewGroup) {
6340 ViewGroup vg = (ViewGroup) mRoot;
6341 int count = vg.getChildCount();
6342 for (int i = 0; i < count; i++) {
6343 addViewChild(vg.getChildAt(i));
6344 }
6345 }
6346 }
6347
6348 @Nullable
6349 public ViewTree findViewTreeById(@IdRes int id) {
6350 if (mRoot.getId() == id) {
6351 return this;
6352 }
6353 if (mChildren == null) {
6354 return null;
6355 }
6356 for (ViewTree tree : mChildren) {
6357 ViewTree result = tree.findViewTreeById(id);
6358 if (result != null) {
6359 return result;
6360 }
6361 }
6362 return null;
6363 }
6364
6365 @Nullable
6366 public ViewTree findViewTreeParentOf(ViewTree child) {
6367 if (mChildren == null) {
6368 return null;
6369 }
6370 for (ViewTree tree : mChildren) {
6371 if (tree == child) {
6372 return this;
6373 }
6374 ViewTree result = tree.findViewTreeParentOf(child);
6375 if (result != null) {
6376 return result;
6377 }
6378 }
6379 return null;
6380 }
6381
6382 public void replaceView(View v) {
6383 mRoot = v;
6384 mChildren = null;
6385 createTree();
6386 }
6387
6388 @Nullable
6389 public <T extends View> T findViewById(@IdRes int id) {
6390 if (mChildren == null) {
6391 return mRoot.findViewById(id);
6392 }
6393 ViewTree tree = findViewTreeById(id);
6394 return tree == null ? null : (T) tree.mRoot;
6395 }
6396
6397 public void addChild(ViewTree child) {
6398 addChild(child, INSERT_AT_END_INDEX);
6399 }
6400
6401 /**
6402 * Adds the given {@link ViewTree} as a child at the given index.
6403 *
6404 * @param index The position at which to add the child or -1 to add last.
6405 */
6406 public void addChild(ViewTree child, int index) {
6407 if (mChildren == null) {
6408 mChildren = new ArrayList<>();
6409 }
6410 child.createTree();
6411
6412 if (index == INSERT_AT_END_INDEX) {
6413 mChildren.add(child);
6414 return;
6415 }
6416
6417 mChildren.add(index, child);
6418 }
6419
6420 public void removeChildren(int start, int count) {
6421 if (mChildren != null) {
6422 for (int i = 0; i < count; i++) {
6423 mChildren.remove(start);
6424 }
6425 }
6426 }
6427
6428 private void addViewChild(View v) {
6429 // ViewTree only contains Views which can be found using findViewById.
6430 // If isRootNamespace is true, this view is skipped.
6431 // @see ViewGroup#findViewTraversal(int)
6432 if (v.isRootNamespace()) {
6433 return;
6434 }
6435 final ViewTree target;
6436
6437 // If the view has a valid id, i.e., if can be found using findViewById, add it to the
6438 // tree, otherwise skip this view and add its children instead.
6439 if (v.getId() != 0) {
6440 ViewTree tree = new ViewTree(v);
6441 mChildren.add(tree);
6442 target = tree;
6443 } else {
6444 target = this;
6445 }
6446
6447 if (v instanceof ViewGroup) {
6448 if (target.mChildren == null) {
6449 target.mChildren = new ArrayList<>();
6450 ViewGroup vg = (ViewGroup) v;
6451 int count = vg.getChildCount();
6452 for (int i = 0; i < count; i++) {
6453 target.addViewChild(vg.getChildAt(i));
6454 }
6455 }
6456 }
6457 }
6458
6459 /** Find the first child for which the condition is true and return its index. */
6460 public int findChildIndex(Predicate<View> condition) {
6461 return findChildIndex(0, condition);
6462 }
6463
6464 /**
6465 * Find the first child, starting at {@code startIndex}, for which the condition is true and
6466 * return its index.
6467 */
6468 public int findChildIndex(int startIndex, Predicate<View> condition) {
6469 if (mChildren == null) {
6470 return -1;
6471 }
6472
6473 for (int i = startIndex; i < mChildren.size(); i++) {
6474 if (condition.test(mChildren.get(i).mRoot)) {
6475 return i;
6476 }
6477 }
6478 return -1;
6479 }
6480 }
6481
6482 /**
6483 * Class representing a response to an action performed on any element of a RemoteViews.
6484 */
6485 public static class RemoteResponse {
6486
6487 /** @hide **/
6488 @IntDef(prefix = "INTERACTION_TYPE_", value = {
6489 INTERACTION_TYPE_CLICK,
6490 INTERACTION_TYPE_CHECKED_CHANGE,
6491 })
6492 @Retention(RetentionPolicy.SOURCE)
6493 @interface InteractionType {}
6494 /** @hide */
6495 public static final int INTERACTION_TYPE_CLICK = 0;
6496 /** @hide */
6497 public static final int INTERACTION_TYPE_CHECKED_CHANGE = 1;
6498
6499 private PendingIntent mPendingIntent;
6500 private Intent mFillIntent;
6501
6502 private int mInteractionType = INTERACTION_TYPE_CLICK;
6503 private IntArray mViewIds;
6504 private ArrayList<String> mElementNames;
6505
6506 /**
6507 * Creates a response which sends a pending intent as part of the response. The source
6508 * bounds ({@link Intent#getSourceBounds()}) of the intent will be set to the bounds of the
6509 * target view in screen space.
6510 * Note that any activity options associated with the mPendingIntent may get overridden
6511 * before starting the intent.
6512 *
6513 * @param pendingIntent The {@link PendingIntent} to send as part of the response
6514 */
6515 @NonNull
6516 public static RemoteResponse fromPendingIntent(@NonNull PendingIntent pendingIntent) {
6517 RemoteResponse response = new RemoteResponse();
6518 response.mPendingIntent = pendingIntent;
6519 return response;
6520 }
6521
6522 /**
6523 * When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is
6524 * very costly to set PendingIntents on the individual items, and is hence not recommended.
6525 * Instead a single PendingIntent template can be set on the collection, see {@link
6526 * RemoteViews#setPendingIntentTemplate(int, PendingIntent)}, and the individual on-click
6527 * action of a given item can be distinguished by setting a fillInIntent on that item. The
6528 * fillInIntent is then combined with the PendingIntent template in order to determine the
6529 * final intent which will be executed when the item is clicked. This works as follows: any
6530 * fields which are left blank in the PendingIntent template, but are provided by the
6531 * fillInIntent will be overwritten, and the resulting PendingIntent will be used. The rest
6532 * of the PendingIntent template will then be filled in with the associated fields that are
6533 * set in fillInIntent. See {@link Intent#fillIn(Intent, int)} for more details.
6534 * Creates a response which sends a pending intent as part of the response. The source
6535 * bounds ({@link Intent#getSourceBounds()}) of the intent will be set to the bounds of the
6536 * target view in screen space.
6537 * Note that any activity options associated with the mPendingIntent may get overridden
6538 * before starting the intent.
6539 *
6540 * @param fillIntent The intent which will be combined with the parent's PendingIntent in
6541 * order to determine the behavior of the response
6542 * @see RemoteViews#setPendingIntentTemplate(int, PendingIntent)
6543 * @see RemoteViews#setOnClickFillInIntent(int, Intent)
6544 */
6545 @NonNull
6546 public static RemoteResponse fromFillInIntent(@NonNull Intent fillIntent) {
6547 RemoteResponse response = new RemoteResponse();
6548 response.mFillIntent = fillIntent;
6549 return response;
6550 }
6551
6552 /**
6553 * Adds a shared element to be transferred as part of the transition between Activities
6554 * using cross-Activity scene animations. The position of the first element will be used as
6555 * the epicenter for the exit Transition. The position of the associated shared element in
6556 * the launched Activity will be the epicenter of its entering Transition.
6557 *
6558 * @param viewId The id of the view to be shared as part of the transition
6559 * @param sharedElementName The shared element name for this view
6560 * @see ActivityOptions#makeSceneTransitionAnimation(Activity, Pair[])
6561 */
6562 @NonNull
6563 public RemoteResponse addSharedElement(@IdRes int viewId,
6564 @NonNull String sharedElementName) {
6565 if (mViewIds == null) {
6566 mViewIds = new IntArray();
6567 mElementNames = new ArrayList<>();
6568 }
6569 mViewIds.add(viewId);
6570 mElementNames.add(sharedElementName);
6571 return this;
6572 }
6573
6574 /**
6575 * Sets the interaction type for which this RemoteResponse responds.
6576 *
6577 * @param type the type of interaction for which this is a response, such as clicking or
6578 * checked state changing
6579 *
6580 * @hide
6581 */
6582 @NonNull
6583 public RemoteResponse setInteractionType(@InteractionType int type) {
6584 mInteractionType = type;
6585 return this;
6586 }
6587
6588 private void writeToParcel(Parcel dest, int flags) {
6589 PendingIntent.writePendingIntentOrNullToParcel(mPendingIntent, dest);
6590 if (mPendingIntent == null) {
6591 // Only write the intent if pending intent is null
6592 dest.writeTypedObject(mFillIntent, flags);
6593 }
6594 dest.writeInt(mInteractionType);
6595 dest.writeIntArray(mViewIds == null ? null : mViewIds.toArray());
6596 dest.writeStringList(mElementNames);
6597 }
6598
6599 private void readFromParcel(Parcel parcel) {
6600 mPendingIntent = PendingIntent.readPendingIntentOrNullFromParcel(parcel);
6601 if (mPendingIntent == null) {
6602 mFillIntent = parcel.readTypedObject(Intent.CREATOR);
6603 }
6604 mInteractionType = parcel.readInt();
6605 int[] viewIds = parcel.createIntArray();
6606 mViewIds = viewIds == null ? null : IntArray.wrap(viewIds);
6607 mElementNames = parcel.createStringArrayList();
6608 }
6609
6610 private void handleViewInteraction(
6611 View v,
6612 InteractionHandler handler) {
6613 final PendingIntent pi;
6614 if (mPendingIntent != null) {
6615 pi = mPendingIntent;
6616 } else if (mFillIntent != null) {
6617 AdapterView<?> ancestor = getAdapterViewAncestor(v);
6618 if (ancestor == null) {
6619 Log.e(LOG_TAG, "Collection item doesn't have AdapterView parent");
6620 return;
6621 }
6622
6623 // Ensure that a template pending intent has been set on the ancestor
6624 if (!(ancestor.getTag() instanceof PendingIntent)) {
6625 Log.e(LOG_TAG, "Attempting setOnClickFillInIntent or "
6626 + "setOnCheckedChangeFillInIntent without calling "
6627 + "setPendingIntentTemplate on parent.");
6628 return;
6629 }
6630
6631 pi = (PendingIntent) ancestor.getTag();
6632 } else {
6633 Log.e(LOG_TAG, "Response has neither pendingIntent nor fillInIntent");
6634 return;
6635 }
6636
6637 handler.onInteraction(v, pi, this);
6638 }
6639
6640 /**
6641 * Returns the closest ancestor of the view that is an AdapterView or null if none could be
6642 * found.
6643 */
6644 @Nullable
6645 private static AdapterView<?> getAdapterViewAncestor(@Nullable View view) {
6646 if (view == null) return null;
6647
6648 View parent = (View) view.getParent();
6649 // Break the for loop on the first encounter of:
6650 // 1) an AdapterView,
6651 // 2) an AppWidgetHostView that is not a RemoteViewsFrameLayout, or
6652 // 3) a null parent.
6653 // 2) and 3) are unexpected and catch the case where a child is not
6654 // correctly parented in an AdapterView.
6655 while (parent != null && !(parent instanceof AdapterView<?>)
6656 && !((parent instanceof AppWidgetHostView)
6657 && !(parent instanceof RemoteViewsAdapter.RemoteViewsFrameLayout))) {
6658 parent = (View) parent.getParent();
6659 }
6660
6661 return parent instanceof AdapterView<?> ? (AdapterView<?>) parent : null;
6662 }
6663
6664 /** @hide */
6665 public Pair<Intent, ActivityOptions> getLaunchOptions(View view) {
6666 Intent intent = mPendingIntent != null ? new Intent() : new Intent(mFillIntent);
6667 intent.setSourceBounds(getSourceBounds(view));
6668
6669 if (view instanceof CompoundButton
6670 && mInteractionType == INTERACTION_TYPE_CHECKED_CHANGE) {
6671 intent.putExtra(EXTRA_CHECKED, ((CompoundButton) view).isChecked());
6672 }
6673
6674 ActivityOptions opts = null;
6675
6676 Context context = view.getContext();
6677 if (context.getResources().getBoolean(
6678 com.android.internal.R.bool.config_overrideRemoteViewsActivityTransition)) {
6679 TypedArray windowStyle = context.getTheme().obtainStyledAttributes(
6680 com.android.internal.R.styleable.Window);
6681 int windowAnimations = windowStyle.getResourceId(
6682 com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
6683 TypedArray windowAnimationStyle = context.obtainStyledAttributes(
6684 windowAnimations, com.android.internal.R.styleable.WindowAnimation);
6685 int enterAnimationId = windowAnimationStyle.getResourceId(com.android.internal.R
6686 .styleable.WindowAnimation_activityOpenRemoteViewsEnterAnimation, 0);
6687 windowStyle.recycle();
6688 windowAnimationStyle.recycle();
6689
6690 if (enterAnimationId != 0) {
6691 opts = ActivityOptions.makeCustomAnimation(context,
6692 enterAnimationId, 0);
6693 opts.setPendingIntentLaunchFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
6694 }
6695 }
6696
6697 if (opts == null && mViewIds != null && mElementNames != null) {
6698 View parent = (View) view.getParent();
6699 while (parent != null && !(parent instanceof AppWidgetHostView)) {
6700 parent = (View) parent.getParent();
6701 }
6702 if (parent instanceof AppWidgetHostView) {
6703 opts = ((AppWidgetHostView) parent).createSharedElementActivityOptions(
6704 mViewIds.toArray(),
6705 mElementNames.toArray(new String[mElementNames.size()]), intent);
6706 }
6707 }
6708
6709 if (opts == null) {
6710 opts = ActivityOptions.makeBasic();
6711 opts.setPendingIntentLaunchFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
6712 }
6713 if (view.getDisplay() != null) {
6714 opts.setLaunchDisplayId(view.getDisplay().getDisplayId());
6715 } else {
6716 // TODO(b/218409359): Remove once bug is fixed.
6717 Log.w(LOG_TAG, "getLaunchOptions: view.getDisplay() is null!",
6718 new Exception());
6719 }
6720 return Pair.create(intent, opts);
6721 }
6722 }
6723
6724 /** @hide */
6725 public static boolean startPendingIntent(View view, PendingIntent pendingIntent,
6726 Pair<Intent, ActivityOptions> options) {
6727 try {
6728 // TODO: Unregister this handler if PendingIntent.FLAG_ONE_SHOT?
6729 Context context = view.getContext();
6730 // The NEW_TASK flags are applied through the activity options and not as a part of
6731 // the call to startIntentSender() to ensure that they are consistently applied to
6732 // both mutable and immutable PendingIntents.
6733 context.startIntentSender(
6734 pendingIntent.getIntentSender(), options.first,
6735 0, 0, 0, options.second.toBundle());
6736 } catch (IntentSender.SendIntentException e) {
6737 Log.e(LOG_TAG, "Cannot send pending intent: ", e);
6738 return false;
6739 } catch (Exception e) {
6740 Log.e(LOG_TAG, "Cannot send pending intent due to unknown exception: ", e);
6741 return false;
6742 }
6743 return true;
6744 }
6745
6746 /** Representation of a fixed list of items to be displayed in a RemoteViews collection. */
6747 public static final class RemoteCollectionItems implements Parcelable {
6748 private final long[] mIds;
6749 private final RemoteViews[] mViews;
6750 private final boolean mHasStableIds;
6751 private final int mViewTypeCount;
6752
6753 private HierarchyRootData mHierarchyRootData;
6754
6755 RemoteCollectionItems(
6756 long[] ids, RemoteViews[] views, boolean hasStableIds, int viewTypeCount) {
6757 mIds = ids;
6758 mViews = views;
6759 mHasStableIds = hasStableIds;
6760 mViewTypeCount = viewTypeCount;
6761 if (ids.length != views.length) {
6762 throw new IllegalArgumentException(
6763 "RemoteCollectionItems has different number of ids and views");
6764 }
6765 if (viewTypeCount < 1) {
6766 throw new IllegalArgumentException("View type count must be >= 1");
6767 }
6768 int layoutIdCount = (int) Arrays.stream(views)
6769 .mapToInt(RemoteViews::getLayoutId)
6770 .distinct()
6771 .count();
6772 if (layoutIdCount > viewTypeCount) {
6773 throw new IllegalArgumentException(
6774 "View type count is set to " + viewTypeCount + ", but the collection "
6775 + "contains " + layoutIdCount + " different layout ids");
6776 }
6777
6778 // Until the collection items are attached to a parent, we configure the first item
6779 // to be the root of the others to share caches and save space during serialization.
6780 if (views.length > 0) {
6781 setHierarchyRootData(views[0].getHierarchyRootData());
6782 views[0].mIsRoot = true;
6783 }
6784 }
6785
6786 RemoteCollectionItems(@NonNull Parcel in, @Nullable HierarchyRootData hierarchyRootData) {
6787 mHasStableIds = in.readBoolean();
6788 mViewTypeCount = in.readInt();
6789 int length = in.readInt();
6790 mIds = new long[length];
6791 in.readLongArray(mIds);
6792
6793 boolean attached = in.readBoolean();
6794 mViews = new RemoteViews[length];
6795 int firstChildIndex;
6796 if (attached) {
6797 if (hierarchyRootData == null) {
6798 throw new IllegalStateException("Cannot unparcel a RemoteCollectionItems that "
6799 + "was parceled as attached without providing data for a root "
6800 + "RemoteViews");
6801 }
6802 mHierarchyRootData = hierarchyRootData;
6803 firstChildIndex = 0;
6804 } else {
6805 mViews[0] = new RemoteViews(in);
6806 mHierarchyRootData = mViews[0].getHierarchyRootData();
6807 firstChildIndex = 1;
6808 }
6809
6810 for (int i = firstChildIndex; i < length; i++) {
6811 mViews[i] = new RemoteViews(
6812 in,
6813 mHierarchyRootData,
6814 /* info= */ null,
6815 /* depth= */ 0);
6816 }
6817 }
6818
6819 void setHierarchyRootData(@NonNull HierarchyRootData rootData) {
6820 mHierarchyRootData = rootData;
6821 for (RemoteViews view : mViews) {
6822 view.configureAsChild(rootData);
6823 }
6824 }
6825
6826 @Override
6827 public int describeContents() {
6828 return 0;
6829 }
6830
6831 @Override
6832 public void writeToParcel(@NonNull Parcel dest, int flags) {
6833 writeToParcel(dest, flags, /* attached= */ false);
6834 }
6835
6836 private void writeToParcel(@NonNull Parcel dest, int flags, boolean attached) {
6837 boolean prevAllowSquashing = dest.allowSquashing();
6838
6839 dest.writeBoolean(mHasStableIds);
6840 dest.writeInt(mViewTypeCount);
6841 dest.writeInt(mIds.length);
6842 dest.writeLongArray(mIds);
6843
6844 if (attached && mHierarchyRootData == null) {
6845 throw new IllegalStateException("Cannot call writeToParcelAttached for a "
6846 + "RemoteCollectionItems without first calling setHierarchyRootData()");
6847 }
6848
6849 // Write whether we parceled as attached or not. This allows cleaner validation and
6850 // proper error messaging when unparceling later.
6851 dest.writeBoolean(attached);
6852 boolean restoreRoot = false;
6853 if (!attached && mViews.length > 0 && !mViews[0].mIsRoot) {
6854 // If we're writing unattached, temporarily set the first item as the root so that
6855 // the bitmap cache is written to the parcel.
6856 restoreRoot = true;
6857 mViews[0].mIsRoot = true;
6858 }
6859
6860 for (RemoteViews view : mViews) {
6861 view.writeToParcel(dest, flags);
6862 }
6863
6864 if (restoreRoot) mViews[0].mIsRoot = false;
6865 dest.restoreAllowSquashing(prevAllowSquashing);
6866 }
6867
6868 /**
6869 * Returns the id for {@code position}. See {@link #hasStableIds()} for whether this id
6870 * should be considered meaningful across collection updates.
6871 *
6872 * @return Id for the position.
6873 */
6874 public long getItemId(int position) {
6875 return mIds[position];
6876 }
6877
6878 /**
6879 * Returns the {@link RemoteViews} to display at {@code position}.
6880 *
6881 * @return RemoteViews for the position.
6882 */
6883 @NonNull
6884 public RemoteViews getItemView(int position) {
6885 return mViews[position];
6886 }
6887
6888 /**
6889 * Returns the number of elements in the collection.
6890 *
6891 * @return Count of items.
6892 */
6893 public int getItemCount() {
6894 return mIds.length;
6895 }
6896
6897 /**
6898 * Returns the view type count for the collection when used in an adapter
6899 *
6900 * @return Count of view types for the collection when used in an adapter.
6901 * @see android.widget.Adapter#getViewTypeCount()
6902 */
6903 public int getViewTypeCount() {
6904 return mViewTypeCount;
6905 }
6906
6907 /**
6908 * Indicates whether the item ids are stable across changes to the underlying data.
6909 *
6910 * @return True if the same id always refers to the same object.
6911 * @see android.widget.Adapter#hasStableIds()
6912 */
6913 public boolean hasStableIds() {
6914 return mHasStableIds;
6915 }
6916
6917 @NonNull
6918 public static final Creator<RemoteCollectionItems> CREATOR =
6919 new Creator<RemoteCollectionItems>() {
6920 @NonNull
6921 @Override
6922 public RemoteCollectionItems createFromParcel(@NonNull Parcel source) {
6923 return new RemoteCollectionItems(source, /* hierarchyRoot= */ null);
6924 }
6925
6926 @NonNull
6927 @Override
6928 public RemoteCollectionItems[] newArray(int size) {
6929 return new RemoteCollectionItems[size];
6930 }
6931 };
6932
6933 /** Builder class for {@link RemoteCollectionItems} objects.*/
6934 public static final class Builder {
6935 private final LongArray mIds = new LongArray();
6936 private final List<RemoteViews> mViews = new ArrayList<>();
6937 private boolean mHasStableIds;
6938 private int mViewTypeCount;
6939
6940 /**
6941 * Adds a {@link RemoteViews} to the collection.
6942 *
6943 * @param id Id to associate with the row. Use {@link #setHasStableIds(boolean)} to
6944 * indicate that ids are stable across changes to the collection.
6945 * @param view RemoteViews to display for the row.
6946 */
6947 @NonNull
6948 // Covered by getItemId, getItemView, getItemCount.
6949 @SuppressLint("MissingGetterMatchingBuilder")
6950 public Builder addItem(long id, @NonNull RemoteViews view) {
6951 if (view == null) throw new NullPointerException();
6952 if (view.hasMultipleLayouts()) {
6953 throw new IllegalArgumentException(
6954 "RemoteViews used in a RemoteCollectionItems cannot specify separate "
6955 + "layouts for orientations or sizes.");
6956 }
6957 mIds.add(id);
6958 mViews.add(view);
6959 return this;
6960 }
6961
6962 /**
6963 * Sets whether the item ids are stable across changes to the underlying data.
6964 *
6965 * @see android.widget.Adapter#hasStableIds()
6966 */
6967 @NonNull
6968 public Builder setHasStableIds(boolean hasStableIds) {
6969 mHasStableIds = hasStableIds;
6970 return this;
6971 }
6972
6973 /**
6974 * Sets the view type count for the collection when used in an adapter. This can be set
6975 * to the maximum number of different layout ids that will be used by RemoteViews in
6976 * this collection.
6977 *
6978 * If this value is not set, then a value will be inferred from the provided items. As
6979 * a result, the adapter may need to be recreated when the list is updated with
6980 * previously unseen RemoteViews layouts for new items.
6981 *
6982 * @see android.widget.Adapter#getViewTypeCount()
6983 */
6984 @NonNull
6985 public Builder setViewTypeCount(int viewTypeCount) {
6986 mViewTypeCount = viewTypeCount;
6987 return this;
6988 }
6989
6990 /** Creates the {@link RemoteCollectionItems} defined by this builder. */
6991 @NonNull
6992 public RemoteCollectionItems build() {
6993 if (mViewTypeCount < 1) {
6994 // If a view type count wasn't specified, set it to be the number of distinct
6995 // layout ids used in the items.
6996 mViewTypeCount = (int) mViews.stream()
6997 .mapToInt(RemoteViews::getLayoutId)
6998 .distinct()
6999 .count();
7000 }
7001 return new RemoteCollectionItems(
7002 mIds.toArray(),
7003 mViews.toArray(new RemoteViews[0]),
7004 mHasStableIds,
7005 Math.max(mViewTypeCount, 1));
7006 }
7007 }
7008 }
7009
7010 /**
7011 * Get the ID of the top-level view of the XML layout, if set using
7012 * {@link RemoteViews#RemoteViews(String, int, int)}.
7013 */
7014 public @IdRes int getViewId() {
7015 return mViewId;
7016 }
7017
7018 /**
7019 * Set the provider instance ID.
7020 *
7021 * This should only be used by {@link com.android.server.appwidget.AppWidgetService}.
7022 * @hide
7023 */
7024 public void setProviderInstanceId(long id) {
7025 mProviderInstanceId = id;
7026 }
7027
7028 /**
7029 * Get the provider instance id.
7030 *
7031 * This should uniquely identifies {@link RemoteViews} coming from a given App Widget
7032 * Provider. This changes each time the App Widget provider update the {@link RemoteViews} of
7033 * its widget. Returns -1 if the {@link RemoteViews} doesn't come from an App Widget provider.
7034 * @hide
7035 */
7036 public long getProviderInstanceId() {
7037 return mProviderInstanceId;
7038 }
7039
7040 /**
7041 * Identify the child of this {@link RemoteViews}, or 0 if this is not a child.
7042 *
7043 * The returned value is always a small integer, currently between 0 and 17.
7044 */
7045 private int getChildId(@NonNull RemoteViews child) {
7046 if (child == this) {
7047 return 0;
7048 }
7049 if (hasSizedRemoteViews()) {
7050 for (int i = 0; i < mSizedRemoteViews.size(); i++) {
7051 if (mSizedRemoteViews.get(i) == child) {
7052 return i + 1;
7053 }
7054 }
7055 }
7056 if (hasLandscapeAndPortraitLayouts()) {
7057 if (mLandscape == child) {
7058 return 1;
7059 } else if (mPortrait == child) {
7060 return 2;
7061 }
7062 }
7063 // This is not a child of this RemoteViews.
7064 return 0;
7065 }
7066
7067 /**
7068 * Identify uniquely this RemoteViews, or returns -1 if not possible.
7069 *
7070 * @param parent If the {@link RemoteViews} is not a root {@link RemoteViews}, this should be
7071 * the parent that contains it.
7072 *
7073 * @hide
7074 */
7075 public long computeUniqueId(@Nullable RemoteViews parent) {
7076 if (mIsRoot) {
7077 long viewId = getProviderInstanceId();
7078 if (viewId != -1) {
7079 viewId <<= 8;
7080 }
7081 return viewId;
7082 }
7083 if (parent == null) {
7084 return -1;
7085 }
7086 long viewId = parent.getProviderInstanceId();
7087 if (viewId == -1) {
7088 return -1;
7089 }
7090 int childId = parent.getChildId(this);
7091 if (childId == -1) {
7092 return -1;
7093 }
7094 viewId <<= 8;
7095 viewId |= childId;
7096 return viewId;
7097 }
7098
7099 @Nullable
7100 private static Pair<String, Integer> getPackageUserKey(@Nullable ApplicationInfo info) {
7101 if (info == null || info.packageName == null) return null;
7102 return Pair.create(info.packageName, info.uid);
7103 }
7104
7105 private HierarchyRootData getHierarchyRootData() {
7106 return new HierarchyRootData(mBitmapCache, mApplicationInfoCache, mClassCookies);
7107 }
7108
7109 private static final class HierarchyRootData {
7110 final BitmapCache mBitmapCache;
7111 final ApplicationInfoCache mApplicationInfoCache;
7112 final Map<Class, Object> mClassCookies;
7113
7114 HierarchyRootData(
7115 BitmapCache bitmapCache,
7116 ApplicationInfoCache applicationInfoCache,
7117 Map<Class, Object> classCookies) {
7118 mBitmapCache = bitmapCache;
7119 mApplicationInfoCache = applicationInfoCache;
7120 mClassCookies = classCookies;
7121 }
7122 }
7123 }