/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.widget; import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED; import android.annotation.ColorInt; import android.annotation.DimenRes; import android.annotation.NonNull; import android.app.ActivityOptions; import android.app.ActivityThread; import android.app.Application; import android.app.PendingIntent; import android.app.RemoteInput; import android.appwidget.AppWidgetHostView; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentSender; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.ColorStateList; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.Icon; import android.net.Uri; import android.os.AsyncTask; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.os.CancellationSignal; import android.os.Parcel; import android.os.Parcelable; import android.os.Process; import android.os.StrictMode; import android.os.UserHandle; import android.text.TextUtils; import android.util.ArrayMap; import android.util.Log; import android.view.LayoutInflater; import android.view.LayoutInflater.Filter; import android.view.RemotableViewMethod; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewStub; import android.widget.AdapterView.OnItemClickListener; import com.android.internal.R; import com.android.internal.util.NotificationColorUtil; import com.android.internal.util.Preconditions; import libcore.util.Objects; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.concurrent.Executor; /** * A class that describes a view hierarchy that can be displayed in * another process. The hierarchy is inflated from a layout resource * file, and this class provides some basic operations for modifying * the content of the inflated hierarchy. * *
{@code RemoteViews} is limited to support for the following layouts:
*And the following widgets:
*Descendants of these classes are not supported.
*/ public class RemoteViews implements Parcelable, Filter { private static final String LOG_TAG = "RemoteViews"; /** * The intent extra that contains the appWidgetId. * @hide */ static final String EXTRA_REMOTEADAPTER_APPWIDGET_ID = "remoteAdapterAppWidgetId"; /** * Maximum depth of nested views calls from {@link #addView(int, RemoteViews)} and * {@link #RemoteViews(RemoteViews, RemoteViews)}. */ private static final int MAX_NESTED_VIEWS = 10; // The unique identifiers for each custom {@link Action}. private static final int SET_ON_CLICK_PENDING_INTENT_TAG = 1; private static final int REFLECTION_ACTION_TAG = 2; private static final int SET_DRAWABLE_TINT_TAG = 3; private static final int VIEW_GROUP_ACTION_ADD_TAG = 4; private static final int VIEW_CONTENT_NAVIGATION_TAG = 5; private static final int SET_EMPTY_VIEW_ACTION_TAG = 6; private static final int VIEW_GROUP_ACTION_REMOVE_TAG = 7; private static final int SET_PENDING_INTENT_TEMPLATE_TAG = 8; private static final int SET_ON_CLICK_FILL_IN_INTENT_TAG = 9; private static final int SET_REMOTE_VIEW_ADAPTER_INTENT_TAG = 10; private static final int TEXT_VIEW_DRAWABLE_ACTION_TAG = 11; private static final int BITMAP_REFLECTION_ACTION_TAG = 12; private static final int TEXT_VIEW_SIZE_ACTION_TAG = 13; private static final int VIEW_PADDING_ACTION_TAG = 14; private static final int SET_REMOTE_VIEW_ADAPTER_LIST_TAG = 15; private static final int SET_REMOTE_INPUTS_ACTION_TAG = 18; private static final int LAYOUT_PARAM_ACTION_TAG = 19; private static final int OVERRIDE_TEXT_COLORS_TAG = 20; /** * Application that hosts the remote views. * * @hide */ public ApplicationInfo mApplication; /** * The resource ID of the layout file. (Added to the parcel) */ private final int mLayoutId; /** * An array of actions to perform on the view tree once it has been * inflated */ private ArrayList* The operation will be performed on the {@link Drawable} returned by the * target {@link View#getBackground()} by default. If targetBackground is false, * we assume the target is an {@link ImageView} and try applying the operations * to {@link ImageView#getDrawable()}. *
*/
private class SetDrawableTint extends Action {
SetDrawableTint(int id, boolean targetBackground,
int colorFilter, @NonNull PorterDuff.Mode mode) {
this.viewId = id;
this.targetBackground = targetBackground;
this.colorFilter = colorFilter;
this.filterMode = mode;
}
SetDrawableTint(Parcel parcel) {
viewId = parcel.readInt();
targetBackground = parcel.readInt() != 0;
colorFilter = parcel.readInt();
filterMode = PorterDuff.intToMode(parcel.readInt());
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(targetBackground ? 1 : 0);
dest.writeInt(colorFilter);
dest.writeInt(PorterDuff.modeToInt(filterMode));
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final View target = root.findViewById(viewId);
if (target == null) return;
// Pick the correct drawable to modify for this view
Drawable targetDrawable = null;
if (targetBackground) {
targetDrawable = target.getBackground();
} else if (target instanceof ImageView) {
ImageView imageView = (ImageView) target;
targetDrawable = imageView.getDrawable();
}
if (targetDrawable != null) {
targetDrawable.mutate().setColorFilter(colorFilter, filterMode);
}
}
@Override
public int getActionTag() {
return SET_DRAWABLE_TINT_TAG;
}
boolean targetBackground;
int colorFilter;
PorterDuff.Mode filterMode;
}
private final class ViewContentNavigation extends Action {
final boolean mNext;
ViewContentNavigation(int viewId, boolean next) {
this.viewId = viewId;
this.mNext = next;
}
ViewContentNavigation(Parcel in) {
this.viewId = in.readInt();
this.mNext = in.readBoolean();
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(this.viewId);
out.writeBoolean(this.mNext);
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final View view = root.findViewById(viewId);
if (view == null) return;
try {
getMethod(view,
mNext ? "showNext" : "showPrevious", null, false /* async */).invoke(view);
} catch (Throwable ex) {
throw new ActionException(ex);
}
}
public int mergeBehavior() {
return MERGE_IGNORE;
}
@Override
public int getActionTag() {
return VIEW_CONTENT_NAVIGATION_TAG;
}
}
private static class BitmapCache {
ArrayList Using -2 because the default id is -1. This avoids accidentally matching that.
*/
private static final int REMOVE_ALL_VIEWS_ID = -2;
private int mViewIdToKeep;
ViewGroupActionRemove(int viewId) {
this(viewId, REMOVE_ALL_VIEWS_ID);
}
ViewGroupActionRemove(int viewId, int viewIdToKeep) {
this.viewId = viewId;
mViewIdToKeep = viewIdToKeep;
}
ViewGroupActionRemove(Parcel parcel) {
viewId = parcel.readInt();
mViewIdToKeep = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(mViewIdToKeep);
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final ViewGroup target = root.findViewById(viewId);
if (target == null) {
return;
}
if (mViewIdToKeep == REMOVE_ALL_VIEWS_ID) {
target.removeAllViews();
return;
}
removeAllViewsExceptIdToKeep(target);
}
@Override
public Action initActionAsync(ViewTree root, ViewGroup rootParent, OnClickHandler handler) {
// In the async implementation, update the view tree so that subsequent calls to
// findViewById return the current view.
root.createTree();
ViewTree target = root.findViewTreeById(viewId);
if ((target == null) || !(target.mRoot instanceof ViewGroup)) {
return ACTION_NOOP;
}
final ViewGroup targetVg = (ViewGroup) target.mRoot;
// Clear all children when nested views omitted
target.mChildren = null;
return new RuntimeAction() {
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler)
throws ActionException {
if (mViewIdToKeep == REMOVE_ALL_VIEWS_ID) {
targetVg.removeAllViews();
return;
}
removeAllViewsExceptIdToKeep(targetVg);
}
};
}
/**
* Iterates through the children in the given ViewGroup and removes all the views that
* do not have an id of {@link #mViewIdToKeep}.
*/
private void removeAllViewsExceptIdToKeep(ViewGroup viewGroup) {
// Otherwise, remove all the views that do not match the id to keep.
int index = viewGroup.getChildCount() - 1;
while (index >= 0) {
if (viewGroup.getChildAt(index).getId() != mViewIdToKeep) {
viewGroup.removeViewAt(index);
}
index--;
}
}
@Override
public int getActionTag() {
return VIEW_GROUP_ACTION_REMOVE_TAG;
}
@Override
public int mergeBehavior() {
return MERGE_APPEND;
}
}
/**
* Helper action to set compound drawables on a TextView. Supports relative
* (s/t/e/b) or cardinal (l/t/r/b) arrangement.
*/
private class TextViewDrawableAction extends Action {
public TextViewDrawableAction(int viewId, boolean isRelative, int d1, int d2, int d3, int d4) {
this.viewId = viewId;
this.isRelative = isRelative;
this.useIcons = false;
this.d1 = d1;
this.d2 = d2;
this.d3 = d3;
this.d4 = d4;
}
public TextViewDrawableAction(int viewId, boolean isRelative,
Icon i1, Icon i2, Icon i3, Icon i4) {
this.viewId = viewId;
this.isRelative = isRelative;
this.useIcons = true;
this.i1 = i1;
this.i2 = i2;
this.i3 = i3;
this.i4 = i4;
}
public TextViewDrawableAction(Parcel parcel) {
viewId = parcel.readInt();
isRelative = (parcel.readInt() != 0);
useIcons = (parcel.readInt() != 0);
if (useIcons) {
i1 = parcel.readTypedObject(Icon.CREATOR);
i2 = parcel.readTypedObject(Icon.CREATOR);
i3 = parcel.readTypedObject(Icon.CREATOR);
i4 = parcel.readTypedObject(Icon.CREATOR);
} else {
d1 = parcel.readInt();
d2 = parcel.readInt();
d3 = parcel.readInt();
d4 = parcel.readInt();
}
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(isRelative ? 1 : 0);
dest.writeInt(useIcons ? 1 : 0);
if (useIcons) {
dest.writeTypedObject(i1, 0);
dest.writeTypedObject(i2, 0);
dest.writeTypedObject(i3, 0);
dest.writeTypedObject(i4, 0);
} else {
dest.writeInt(d1);
dest.writeInt(d2);
dest.writeInt(d3);
dest.writeInt(d4);
}
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final TextView target = root.findViewById(viewId);
if (target == null) return;
if (drawablesLoaded) {
if (isRelative) {
target.setCompoundDrawablesRelativeWithIntrinsicBounds(id1, id2, id3, id4);
} else {
target.setCompoundDrawablesWithIntrinsicBounds(id1, id2, id3, id4);
}
} else if (useIcons) {
final Context ctx = target.getContext();
final Drawable id1 = i1 == null ? null : i1.loadDrawable(ctx);
final Drawable id2 = i2 == null ? null : i2.loadDrawable(ctx);
final Drawable id3 = i3 == null ? null : i3.loadDrawable(ctx);
final Drawable id4 = i4 == null ? null : i4.loadDrawable(ctx);
if (isRelative) {
target.setCompoundDrawablesRelativeWithIntrinsicBounds(id1, id2, id3, id4);
} else {
target.setCompoundDrawablesWithIntrinsicBounds(id1, id2, id3, id4);
}
} else {
if (isRelative) {
target.setCompoundDrawablesRelativeWithIntrinsicBounds(d1, d2, d3, d4);
} else {
target.setCompoundDrawablesWithIntrinsicBounds(d1, d2, d3, d4);
}
}
}
@Override
public Action initActionAsync(ViewTree root, ViewGroup rootParent, OnClickHandler handler) {
final TextView target = root.findViewById(viewId);
if (target == null) return ACTION_NOOP;
TextViewDrawableAction copy = useIcons ?
new TextViewDrawableAction(viewId, isRelative, i1, i2, i3, i4) :
new TextViewDrawableAction(viewId, isRelative, d1, d2, d3, d4);
// Load the drawables on the background thread.
copy.drawablesLoaded = true;
final Context ctx = target.getContext();
if (useIcons) {
copy.id1 = i1 == null ? null : i1.loadDrawable(ctx);
copy.id2 = i2 == null ? null : i2.loadDrawable(ctx);
copy.id3 = i3 == null ? null : i3.loadDrawable(ctx);
copy.id4 = i4 == null ? null : i4.loadDrawable(ctx);
} else {
copy.id1 = d1 == 0 ? null : ctx.getDrawable(d1);
copy.id2 = d2 == 0 ? null : ctx.getDrawable(d2);
copy.id3 = d3 == 0 ? null : ctx.getDrawable(d3);
copy.id4 = d4 == 0 ? null : ctx.getDrawable(d4);
}
return copy;
}
@Override
public boolean prefersAsyncApply() {
return useIcons;
}
@Override
public int getActionTag() {
return TEXT_VIEW_DRAWABLE_ACTION_TAG;
}
boolean isRelative = false;
boolean useIcons = false;
int d1, d2, d3, d4;
Icon i1, i2, i3, i4;
boolean drawablesLoaded = false;
Drawable id1, id2, id3, id4;
}
/**
* Helper action to set text size on a TextView in any supported units.
*/
private class TextViewSizeAction extends Action {
public TextViewSizeAction(int viewId, int units, float size) {
this.viewId = viewId;
this.units = units;
this.size = size;
}
public TextViewSizeAction(Parcel parcel) {
viewId = parcel.readInt();
units = parcel.readInt();
size = parcel.readFloat();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(units);
dest.writeFloat(size);
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final TextView target = root.findViewById(viewId);
if (target == null) return;
target.setTextSize(units, size);
}
@Override
public int getActionTag() {
return TEXT_VIEW_SIZE_ACTION_TAG;
}
int units;
float size;
}
/**
* Helper action to set padding on a View.
*/
private class ViewPaddingAction extends Action {
public ViewPaddingAction(int viewId, int left, int top, int right, int bottom) {
this.viewId = viewId;
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public ViewPaddingAction(Parcel parcel) {
viewId = parcel.readInt();
left = parcel.readInt();
top = parcel.readInt();
right = parcel.readInt();
bottom = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(left);
dest.writeInt(top);
dest.writeInt(right);
dest.writeInt(bottom);
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final View target = root.findViewById(viewId);
if (target == null) return;
target.setPadding(left, top, right, bottom);
}
@Override
public int getActionTag() {
return VIEW_PADDING_ACTION_TAG;
}
int left, top, right, bottom;
}
/**
* Helper action to set layout params on a View.
*/
private static class LayoutParamAction extends Action {
/** Set marginEnd */
public static final int LAYOUT_MARGIN_END_DIMEN = 1;
/** Set width */
public static final int LAYOUT_WIDTH = 2;
public static final int LAYOUT_MARGIN_BOTTOM_DIMEN = 3;
final int mProperty;
final int mValue;
/**
* @param viewId ID of the view alter
* @param property which layout parameter to alter
* @param value new value of the layout parameter
*/
public LayoutParamAction(int viewId, int property, int value) {
this.viewId = viewId;
this.mProperty = property;
this.mValue = value;
}
public LayoutParamAction(Parcel parcel) {
viewId = parcel.readInt();
mProperty = parcel.readInt();
mValue = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeInt(mProperty);
dest.writeInt(mValue);
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final View target = root.findViewById(viewId);
if (target == null) {
return;
}
ViewGroup.LayoutParams layoutParams = target.getLayoutParams();
if (layoutParams == null) {
return;
}
switch (mProperty) {
case LAYOUT_MARGIN_END_DIMEN:
if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
int resolved = resolveDimenPixelOffset(target, mValue);
((ViewGroup.MarginLayoutParams) layoutParams).setMarginEnd(resolved);
target.setLayoutParams(layoutParams);
}
break;
case LAYOUT_MARGIN_BOTTOM_DIMEN:
if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
int resolved = resolveDimenPixelOffset(target, mValue);
((ViewGroup.MarginLayoutParams) layoutParams).bottomMargin = resolved;
target.setLayoutParams(layoutParams);
}
break;
case LAYOUT_WIDTH:
layoutParams.width = mValue;
target.setLayoutParams(layoutParams);
break;
default:
throw new IllegalArgumentException("Unknown property " + mProperty);
}
}
private static int resolveDimenPixelOffset(View target, int value) {
if (value == 0) {
return 0;
}
return target.getContext().getResources().getDimensionPixelOffset(value);
}
@Override
public int getActionTag() {
return LAYOUT_PARAM_ACTION_TAG;
}
@Override
public String getUniqueKey() {
return super.getUniqueKey() + mProperty;
}
}
/**
* Helper action to add a view tag with RemoteInputs.
*/
private class SetRemoteInputsAction extends Action {
public SetRemoteInputsAction(int viewId, RemoteInput[] remoteInputs) {
this.viewId = viewId;
this.remoteInputs = remoteInputs;
}
public SetRemoteInputsAction(Parcel parcel) {
viewId = parcel.readInt();
remoteInputs = parcel.createTypedArray(RemoteInput.CREATOR);
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(viewId);
dest.writeTypedArray(remoteInputs, flags);
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final View target = root.findViewById(viewId);
if (target == null) return;
target.setTagInternal(R.id.remote_input_tag, remoteInputs);
}
@Override
public int getActionTag() {
return SET_REMOTE_INPUTS_ACTION_TAG;
}
final Parcelable[] remoteInputs;
}
/**
* Helper action to override all textViewColors
*/
private class OverrideTextColorsAction extends Action {
private final int textColor;
public OverrideTextColorsAction(int textColor) {
this.textColor = textColor;
}
public OverrideTextColorsAction(Parcel parcel) {
textColor = parcel.readInt();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(textColor);
}
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
// Let's traverse the viewtree and override all textColors!
Stack
*
* @param viewId The id of the view that contains the target
* {@link Drawable}
* @param targetBackground If true, apply these parameters to the
* {@link Drawable} returned by
* {@link android.view.View#getBackground()}. Otherwise, assume
* the target view is an {@link ImageView} and apply them to
* {@link ImageView#getDrawable()}.
* @param colorFilter Specify a color for a
* {@link android.graphics.ColorFilter} for this drawable. This will be ignored if
* {@code mode} is {@code null}.
* @param mode Specify a PorterDuff mode for this drawable, or null to leave
* unchanged.
*/
public void setDrawableTint(int viewId, boolean targetBackground,
int colorFilter, @NonNull PorterDuff.Mode mode) {
addAction(new SetDrawableTint(viewId, targetBackground, colorFilter, mode));
}
/**
* @hide
* Equivalent to calling {@link android.widget.ProgressBar#setProgressTintList}.
*
* @param viewId The id of the view whose tint should change
* @param tint the tint to apply, may be {@code null} to clear tint
*/
public void setProgressTintList(int viewId, ColorStateList tint) {
addAction(new ReflectionAction(viewId, "setProgressTintList",
ReflectionAction.COLOR_STATE_LIST, tint));
}
/**
* @hide
* Equivalent to calling {@link android.widget.ProgressBar#setProgressBackgroundTintList}.
*
* @param viewId The id of the view whose tint should change
* @param tint the tint to apply, may be {@code null} to clear tint
*/
public void setProgressBackgroundTintList(int viewId, ColorStateList tint) {
addAction(new ReflectionAction(viewId, "setProgressBackgroundTintList",
ReflectionAction.COLOR_STATE_LIST, tint));
}
/**
* @hide
* Equivalent to calling {@link android.widget.ProgressBar#setIndeterminateTintList}.
*
* @param viewId The id of the view whose tint should change
* @param tint the tint to apply, may be {@code null} to clear tint
*/
public void setProgressIndeterminateTintList(int viewId, ColorStateList tint) {
addAction(new ReflectionAction(viewId, "setIndeterminateTintList",
ReflectionAction.COLOR_STATE_LIST, tint));
}
/**
* Equivalent to calling {@link android.widget.TextView#setTextColor(int)}.
*
* @param viewId The id of the view whose text color should change
* @param color Sets the text color for all the states (normal, selected,
* focused) to be this color.
*/
public void setTextColor(int viewId, @ColorInt int color) {
setInt(viewId, "setTextColor", color);
}
/**
* @hide
* Equivalent to calling {@link android.widget.TextView#setTextColor(ColorStateList)}.
*
* @param viewId The id of the view whose text color should change
* @param colors the text colors to set
*/
public void setTextColor(int viewId, @ColorInt ColorStateList colors) {
addAction(new ReflectionAction(viewId, "setTextColor", ReflectionAction.COLOR_STATE_LIST,
colors));
}
/**
* Equivalent to calling {@link android.widget.AbsListView#setRemoteViewsAdapter(Intent)}.
*
* @param appWidgetId The id of the app widget which contains the specified view. (This
* parameter is ignored in this deprecated method)
* @param viewId The id of the {@link AdapterView}
* @param intent The intent of the service which will be
* providing data to the RemoteViewsAdapter
* @deprecated This method has been deprecated. See
* {@link android.widget.RemoteViews#setRemoteAdapter(int, Intent)}
*/
@Deprecated
public void setRemoteAdapter(int appWidgetId, int viewId, Intent intent) {
setRemoteAdapter(viewId, intent);
}
/**
* Equivalent to calling {@link android.widget.AbsListView#setRemoteViewsAdapter(Intent)}.
* Can only be used for App Widgets.
*
* @param viewId The id of the {@link AdapterView}
* @param intent The intent of the service which will be
* providing data to the RemoteViewsAdapter
*/
public void setRemoteAdapter(int viewId, Intent intent) {
addAction(new SetRemoteViewsAdapterIntent(viewId, intent));
}
/**
* Creates a simple Adapter for the viewId specified. The viewId must point to an AdapterView,
* ie. {@link ListView}, {@link GridView}, {@link StackView} or {@link AdapterViewAnimator}.
* This is a simpler but less flexible approach to populating collection widgets. Its use is
* encouraged for most scenarios, as long as the total memory within the list of RemoteViews
* is relatively small (ie. doesn't contain large or numerous Bitmaps, see {@link
* RemoteViews#setImageViewBitmap}). In the case of numerous images, the use of API is still
* possible by setting image URIs instead of Bitmaps, see {@link RemoteViews#setImageViewUri}.
*
* This API is supported in the compatibility library for previous API levels, see
* RemoteViewsCompat.
*
* @param viewId The id of the {@link AdapterView}
* @param list The list of RemoteViews which will populate the view specified by viewId.
* @param viewTypeCount The maximum number of unique layout id's used to construct the list of
* RemoteViews. This count cannot change during the life-cycle of a given widget, so this
* parameter should account for the maximum possible number of types that may appear in the
* See {@link Adapter#getViewTypeCount()}.
*
* @hide
*/
public void setRemoteAdapter(int viewId, ArrayList The bitmap will be flattened into the parcel if this object is
* sent across processes, so it may end up using a lot of memory, and may be fairly slow. Caller beware: this may throw
*
* @param context Default context to use
* @param parent Parent that the resulting view hierarchy will be attached to. This method
* does not attach the hierarchy. The caller should do so when appropriate.
* @return The inflated view hierarchy
*/
public View apply(Context context, ViewGroup parent) {
return apply(context, parent, null);
}
/** @hide */
public View apply(Context context, ViewGroup parent, OnClickHandler handler) {
RemoteViews rvToApply = getRemoteViewsToApply(context);
View result = inflateView(context, rvToApply, parent);
loadTransitionOverride(context, handler);
rvToApply.performApply(result, parent, handler);
return result;
}
private View inflateView(Context context, RemoteViews rv, ViewGroup parent) {
// RemoteViews may be built by an application installed in another
// user. So build a context that loads resources from that user but
// still returns the current users userId so settings like data / time formats
// are loaded without requiring cross user persmissions.
final Context contextForResources = getContextForResources(context);
Context inflationContext = new RemoteViewsContextWrapper(context, contextForResources);
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Clone inflater so we load resources from correct context and
// we don't add a filter to the static version returned by getSystemService.
inflater = inflater.cloneInContext(inflationContext);
inflater.setFilter(this);
View v = inflater.inflate(rv.getLayoutId(), parent, false);
v.setTagInternal(R.id.widget_frame, rv.getLayoutId());
return v;
}
private static void loadTransitionOverride(Context context,
RemoteViews.OnClickHandler handler) {
if (handler != null && context.getResources().getBoolean(
com.android.internal.R.bool.config_overrideRemoteViewsActivityTransition)) {
TypedArray windowStyle = context.getTheme().obtainStyledAttributes(
com.android.internal.R.styleable.Window);
int windowAnimations = windowStyle.getResourceId(
com.android.internal.R.styleable.Window_windowAnimationStyle, 0);
TypedArray windowAnimationStyle = context.obtainStyledAttributes(
windowAnimations, com.android.internal.R.styleable.WindowAnimation);
handler.setEnterAnimationId(windowAnimationStyle.getResourceId(
com.android.internal.R.styleable.
WindowAnimation_activityOpenRemoteViewsEnterAnimation, 0));
windowStyle.recycle();
windowAnimationStyle.recycle();
}
}
/**
* Implement this interface to receive a callback when
* {@link #applyAsync} or {@link #reapplyAsync} is finished.
* @hide
*/
public interface OnViewAppliedListener {
void onViewApplied(View v);
void onError(Exception e);
}
/**
* Applies the views asynchronously, moving as much of the task on the background
* thread as possible.
*
* @see #apply(Context, ViewGroup)
* @param context Default context to use
* @param parent Parent that the resulting view hierarchy will be attached to. This method
* does not attach the hierarchy. The caller should do so when appropriate.
* @param listener the callback to run when all actions have been applied. May be null.
* @param executor The executor to use. If null {@link AsyncTask#THREAD_POOL_EXECUTOR} is used.
* @return CancellationSignal
* @hide
*/
public CancellationSignal applyAsync(
Context context, ViewGroup parent, Executor executor, OnViewAppliedListener listener) {
return applyAsync(context, parent, executor, listener, null);
}
private CancellationSignal startTaskOnExecutor(AsyncApplyTask task, Executor executor) {
CancellationSignal cancelSignal = new CancellationSignal();
cancelSignal.setOnCancelListener(task);
task.executeOnExecutor(executor == null ? AsyncTask.THREAD_POOL_EXECUTOR : executor);
return cancelSignal;
}
/** @hide */
public CancellationSignal applyAsync(Context context, ViewGroup parent,
Executor executor, OnViewAppliedListener listener, OnClickHandler handler) {
return startTaskOnExecutor(getAsyncApplyTask(context, parent, listener, handler), executor);
}
private AsyncApplyTask getAsyncApplyTask(Context context, ViewGroup parent,
OnViewAppliedListener listener, OnClickHandler handler) {
return new AsyncApplyTask(getRemoteViewsToApply(context), parent, context, listener,
handler, null);
}
private class AsyncApplyTask extends AsyncTask Caller beware: this may throw
*
* @param v The view to apply the actions to. This should be the result of
* the {@link #apply(Context,ViewGroup)} call.
*/
public void reapply(Context context, View v) {
reapply(context, v, null);
}
/** @hide */
public void reapply(Context context, View v, OnClickHandler handler) {
RemoteViews rvToApply = getRemoteViewsToApply(context);
// In the case that a view has this RemoteViews applied in one orientation, is persisted
// across orientation change, and has the RemoteViews re-applied in the new orientation,
// we throw an exception, since the layouts may be completely unrelated.
if (hasLandscapeAndPortraitLayouts()) {
if ((Integer) v.getTag(R.id.widget_frame) != rvToApply.getLayoutId()) {
throw new RuntimeException("Attempting to re-apply RemoteViews to a view that" +
" that does not share the same root layout id.");
}
}
rvToApply.performApply(v, (ViewGroup) v.getParent(), handler);
}
/**
* Applies all the actions to the provided view, moving as much of the task on the background
* thread as possible.
*
* @see #reapply(Context, View)
* @param context Default context to use
* @param v The view to apply the actions to. This should be the result of
* the {@link #apply(Context,ViewGroup)} call.
* @param listener the callback to run when all actions have been applied. May be null.
* @param executor The executor to use. If null {@link AsyncTask#THREAD_POOL_EXECUTOR} is used
* @return CancellationSignal
* @hide
*/
public CancellationSignal reapplyAsync(
Context context, View v, Executor executor, OnViewAppliedListener listener) {
return reapplyAsync(context, v, executor, listener, null);
}
/** @hide */
public CancellationSignal reapplyAsync(Context context, View v, Executor executor,
OnViewAppliedListener listener, OnClickHandler handler) {
RemoteViews rvToApply = getRemoteViewsToApply(context);
// In the case that a view has this RemoteViews applied in one orientation, is persisted
// across orientation change, and has the RemoteViews re-applied in the new orientation,
// we throw an exception, since the layouts may be completely unrelated.
if (hasLandscapeAndPortraitLayouts()) {
if ((Integer) v.getTag(R.id.widget_frame) != rvToApply.getLayoutId()) {
throw new RuntimeException("Attempting to re-apply RemoteViews to a view that" +
" that does not share the same root layout id.");
}
}
return startTaskOnExecutor(new AsyncApplyTask(rvToApply, (ViewGroup) v.getParent(),
context, listener, handler, v), executor);
}
private void performApply(View v, ViewGroup parent, OnClickHandler handler) {
if (mActions != null) {
handler = handler == null ? DEFAULT_ON_CLICK_HANDLER : handler;
final int count = mActions.size();
for (int i = 0; i < count; i++) {
Action a = mActions.get(i);
a.apply(v, parent, handler);
}
}
}
/**
* Returns true if the RemoteViews contains potentially costly operations and should be
* applied asynchronously.
*
* @hide
*/
public boolean prefersAsyncApply() {
if (mActions != null) {
final int count = mActions.size();
for (int i = 0; i < count; i++) {
if (mActions.get(i).prefersAsyncApply()) {
return true;
}
}
}
return false;
}
private Context getContextForResources(Context context) {
if (mApplication != null) {
if (context.getUserId() == UserHandle.getUserId(mApplication.uid)
&& context.getPackageName().equals(mApplication.packageName)) {
return context;
}
try {
return context.createApplicationContext(mApplication,
Context.CONTEXT_RESTRICTED);
} catch (NameNotFoundException e) {
Log.e(LOG_TAG, "Package name " + mApplication.packageName + " not found");
}
}
return context;
}
/**
* Returns the number of actions in this RemoteViews. Can be used as a sequence number.
*
* @hide
*/
public int getSequenceNumber() {
return (mActions == null) ? 0 : mActions.size();
}
/* (non-Javadoc)
* Used to restrict the views which can be inflated
*
* @see android.view.LayoutInflater.Filter#onLoadClass(java.lang.Class)
*/
public boolean onLoadClass(Class clazz) {
return clazz.isAnnotationPresent(RemoteView.class);
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
if (!hasLandscapeAndPortraitLayouts()) {
dest.writeInt(MODE_NORMAL);
// We only write the bitmap cache if we are the root RemoteViews, as this cache
// is shared by all children.
if (mIsRoot) {
mBitmapCache.writeBitmapsToParcel(dest, flags);
}
if (!mIsRoot && (flags & PARCELABLE_ELIDE_DUPLICATES) != 0) {
dest.writeInt(0);
} else {
dest.writeInt(1);
mApplication.writeToParcel(dest, flags);
}
dest.writeInt(mLayoutId);
dest.writeInt(mIsWidgetCollectionChild ? 1 : 0);
writeActionsToParcel(dest);
} else {
dest.writeInt(MODE_HAS_LANDSCAPE_AND_PORTRAIT);
// We only write the bitmap cache if we are the root RemoteViews, as this cache
// is shared by all children.
if (mIsRoot) {
mBitmapCache.writeBitmapsToParcel(dest, flags);
}
mLandscape.writeToParcel(dest, flags);
// Both RemoteViews already share the same package and user
mPortrait.writeToParcel(dest, flags | PARCELABLE_ELIDE_DUPLICATES);
}
dest.writeInt(mReapplyDisallowed ? 1 : 0);
}
private void writeActionsToParcel(Parcel parcel) {
int count;
if (mActions != null) {
count = mActions.size();
} else {
count = 0;
}
parcel.writeInt(count);
for (int i = 0; i < count; i++) {
Action a = mActions.get(i);
parcel.writeInt(a.getActionTag());
a.writeToParcel(parcel, a.hasSameAppInfo(mApplication)
? PARCELABLE_ELIDE_DUPLICATES : 0);
}
}
private static ApplicationInfo getApplicationInfo(String packageName, int userId) {
if (packageName == null) {
return null;
}
// Get the application for the passed in package and user.
Application application = ActivityThread.currentApplication();
if (application == null) {
throw new IllegalStateException("Cannot create remote views out of an aplication.");
}
ApplicationInfo applicationInfo = application.getApplicationInfo();
if (UserHandle.getUserId(applicationInfo.uid) != userId
|| !applicationInfo.packageName.equals(packageName)) {
try {
Context context = application.getBaseContext().createPackageContextAsUser(
packageName, 0, new UserHandle(userId));
applicationInfo = context.getApplicationInfo();
} catch (NameNotFoundException nnfe) {
throw new IllegalArgumentException("No such package " + packageName);
}
}
return applicationInfo;
}
/**
* Returns true if the {@link #mApplication} is same as the provided info.
*
* @hide
*/
public boolean hasSameAppInfo(ApplicationInfo info) {
return mApplication.packageName.equals(info.packageName) && mApplication.uid == info.uid;
}
/**
* Parcelable.Creator that instantiates RemoteViews objects
*/
public static final Parcelable.Creator