Debian Codegraph @

core/java/android/appwidget/AppWidgetHostView.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2008 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.appwidget;
18
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.app.Activity;
22 import android.app.ActivityOptions;
23 import android.app.LoadedApk;
24 import android.compat.annotation.UnsupportedAppUsage;
25 import android.content.ComponentName;
26 import android.content.Context;
27 import android.content.ContextWrapper;
28 import android.content.Intent;
29 import android.content.pm.ApplicationInfo;
30 import android.content.pm.LauncherActivityInfo;
31 import android.content.pm.LauncherApps;
32 import android.content.pm.PackageManager.NameNotFoundException;
33 import android.content.res.Resources;
34 import android.graphics.Color;
35 import android.graphics.PointF;
36 import android.graphics.Rect;
37 import android.os.Build;
38 import android.os.Bundle;
39 import android.os.CancellationSignal;
40 import android.os.Parcelable;
41 import android.util.AttributeSet;
42 import android.util.Log;
43 import android.util.Pair;
44 import android.util.SizeF;
45 import android.util.SparseArray;
46 import android.util.SparseIntArray;
47 import android.view.Gravity;
48 import android.view.LayoutInflater;
49 import android.view.View;
50 import android.view.accessibility.AccessibilityNodeInfo;
51 import android.widget.Adapter;
52 import android.widget.AdapterView;
53 import android.widget.BaseAdapter;
54 import android.widget.FrameLayout;
55 import android.widget.RemoteViews;
56 import android.widget.RemoteViews.InteractionHandler;
57 import android.widget.RemoteViewsAdapter.RemoteAdapterConnectionCallback;
58 import android.widget.TextView;
59
60 import java.util.ArrayList;
61 import java.util.List;
62 import java.util.concurrent.Executor;
63
64 /**
65 * Provides the glue to show AppWidget views. This class offers automatic animation
66 * between updates, and will try recycling old views for each incoming
67 * {@link RemoteViews}.
68 */
69 public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppWidgetHostListener {
70
71 static final String TAG = "AppWidgetHostView";
72 private static final String KEY_JAILED_ARRAY = "jail";
73 private static final String KEY_INFLATION_ID = "inflation_id";
74
75 static final boolean LOGD = false;
76
77 static final int VIEW_MODE_NOINIT = 0;
78 static final int VIEW_MODE_CONTENT = 1;
79 static final int VIEW_MODE_ERROR = 2;
80 static final int VIEW_MODE_DEFAULT = 3;
81
82 // Set of valid colors resources.
83 private static final int FIRST_RESOURCE_COLOR_ID = android.R.color.system_neutral1_0;
84 private static final int LAST_RESOURCE_COLOR_ID = android.R.color.system_accent3_1000;
85
86 // When we're inflating the initialLayout for a AppWidget, we only allow
87 // views that are allowed in RemoteViews.
88 private static final LayoutInflater.Filter INFLATER_FILTER =
89 (clazz) -> clazz.isAnnotationPresent(RemoteViews.RemoteView.class);
90
91 Context mContext;
92 Context mRemoteContext;
93
94 @UnsupportedAppUsage
95 int mAppWidgetId;
96 @UnsupportedAppUsage
97 AppWidgetProviderInfo mInfo;
98 View mView;
99 int mViewMode = VIEW_MODE_NOINIT;
100 // If true, we should not try to re-apply the RemoteViews on the next inflation.
101 boolean mColorMappingChanged = false;
102 private InteractionHandler mInteractionHandler;
103 private boolean mOnLightBackground;
104 private SizeF mCurrentSize = null;
105 private RemoteViews.ColorResources mColorResources = null;
106 // Stores the last remote views last inflated.
107 private RemoteViews mLastInflatedRemoteViews = null;
108 private long mLastInflatedRemoteViewsId = -1;
109
110 private Executor mAsyncExecutor;
111 private CancellationSignal mLastExecutionSignal;
112 private SparseArray<Parcelable> mDelayedRestoredState;
113 private long mDelayedRestoredInflationId;
114
115 /**
116 * Create a host view. Uses default fade animations.
117 */
118 public AppWidgetHostView(Context context) {
119 this(context, android.R.anim.fade_in, android.R.anim.fade_out);
120 }
121
122 /**
123 * @hide
124 */
125 public AppWidgetHostView(Context context, InteractionHandler handler) {
126 this(context, android.R.anim.fade_in, android.R.anim.fade_out);
127 mInteractionHandler = getHandler(handler);
128 }
129
130 /**
131 * Create a host view. Uses specified animations when pushing
132 * {@link #updateAppWidget(RemoteViews)}.
133 *
134 * @param animationIn Resource ID of in animation to use
135 * @param animationOut Resource ID of out animation to use
136 */
137 @SuppressWarnings({"UnusedDeclaration"})
138 public AppWidgetHostView(Context context, int animationIn, int animationOut) {
139 super(context);
140 mContext = context;
141 // We want to segregate the view ids within AppWidgets to prevent
142 // problems when those ids collide with view ids in the AppWidgetHost.
143 setIsRootNamespace(true);
144 }
145
146 /**
147 * Pass the given handler to RemoteViews when updating this widget. Unless this
148 * is done immediatly after construction, a call to {@link #updateAppWidget(RemoteViews)}
149 * should be made.
150 * @param handler
151 * @hide
152 */
153 public void setInteractionHandler(InteractionHandler handler) {
154 mInteractionHandler = getHandler(handler);
155 }
156
157 /**
158 * Set the AppWidget that will be displayed by this view. This method also adds default padding
159 * to widgets, as described in {@link #getDefaultPaddingForWidget(Context, ComponentName, Rect)}
160 * and can be overridden in order to add custom padding.
161 */
162 public void setAppWidget(int appWidgetId, AppWidgetProviderInfo info) {
163 mAppWidgetId = appWidgetId;
164 mInfo = info;
165
166 // We add padding to the AppWidgetHostView if necessary
167 Rect padding = getDefaultPadding();
168 setPadding(padding.left, padding.top, padding.right, padding.bottom);
169
170 // Sometimes the AppWidgetManager returns a null AppWidgetProviderInfo object for
171 // a widget, eg. for some widgets in safe mode.
172 if (info != null) {
173 String description = info.loadLabel(getContext().getPackageManager());
174 if ((info.providerInfo.applicationInfo.flags & ApplicationInfo.FLAG_SUSPENDED) != 0) {
175 description = Resources.getSystem().getString(
176 com.android.internal.R.string.suspended_widget_accessibility, description);
177 }
178 setContentDescription(description);
179 }
180 }
181
182 /**
183 * As of ICE_CREAM_SANDWICH we are automatically adding padding to widgets targeting
184 * ICE_CREAM_SANDWICH and higher. The new widget design guidelines strongly recommend
185 * that widget developers do not add extra padding to their widgets. This will help
186 * achieve consistency among widgets.
187 *
188 * Note: this method is only needed by developers of AppWidgetHosts. The method is provided in
189 * order for the AppWidgetHost to account for the automatic padding when computing the number
190 * of cells to allocate to a particular widget.
191 *
192 * @param context the current context
193 * @param component the component name of the widget
194 * @param padding Rect in which to place the output, if null, a new Rect will be allocated and
195 * returned
196 * @return default padding for this widget, in pixels
197 */
198 public static Rect getDefaultPaddingForWidget(Context context, ComponentName component,
199 Rect padding) {
200 return getDefaultPaddingForWidget(context, padding);
201 }
202
203 private static Rect getDefaultPaddingForWidget(Context context, Rect padding) {
204 if (padding == null) {
205 padding = new Rect(0, 0, 0, 0);
206 } else {
207 padding.set(0, 0, 0, 0);
208 }
209 Resources r = context.getResources();
210 padding.left = r.getDimensionPixelSize(
211 com.android.internal.R.dimen.default_app_widget_padding_left);
212 padding.right = r.getDimensionPixelSize(
213 com.android.internal.R.dimen.default_app_widget_padding_right);
214 padding.top = r.getDimensionPixelSize(
215 com.android.internal.R.dimen.default_app_widget_padding_top);
216 padding.bottom = r.getDimensionPixelSize(
217 com.android.internal.R.dimen.default_app_widget_padding_bottom);
218 return padding;
219 }
220
221 private Rect getDefaultPadding() {
222 return getDefaultPaddingForWidget(mContext, null);
223 }
224
225 public int getAppWidgetId() {
226 return mAppWidgetId;
227 }
228
229 public AppWidgetProviderInfo getAppWidgetInfo() {
230 return mInfo;
231 }
232
233 @Override
234 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
235 final SparseArray<Parcelable> jail = new SparseArray<>();
236 super.dispatchSaveInstanceState(jail);
237
238 Bundle bundle = new Bundle();
239 bundle.putSparseParcelableArray(KEY_JAILED_ARRAY, jail);
240 bundle.putLong(KEY_INFLATION_ID, mLastInflatedRemoteViewsId);
241 container.put(generateId(), bundle);
242 container.put(generateId(), bundle);
243 }
244
245 private int generateId() {
246 final int id = getId();
247 return id == View.NO_ID ? mAppWidgetId : id;
248 }
249
250 @Override
251 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
252 final Parcelable parcelable = container.get(generateId());
253
254 SparseArray<Parcelable> jail = null;
255 long inflationId = -1;
256 if (parcelable instanceof Bundle) {
257 Bundle bundle = (Bundle) parcelable;
258 jail = bundle.getSparseParcelableArray(KEY_JAILED_ARRAY);
259 inflationId = bundle.getLong(KEY_INFLATION_ID, -1);
260 }
261
262 if (jail == null) jail = new SparseArray<>();
263
264 mDelayedRestoredState = jail;
265 mDelayedRestoredInflationId = inflationId;
266 restoreInstanceState();
267 }
268
269 void restoreInstanceState() {
270 long inflationId = mDelayedRestoredInflationId;
271 SparseArray<Parcelable> state = mDelayedRestoredState;
272 if (inflationId == -1 || inflationId != mLastInflatedRemoteViewsId) {
273 return; // We don't restore.
274 }
275 mDelayedRestoredInflationId = -1;
276 mDelayedRestoredState = null;
277 try {
278 super.dispatchRestoreInstanceState(state);
279 } catch (Exception e) {
280 Log.e(TAG, "failed to restoreInstanceState for widget id: " + mAppWidgetId + ", "
281 + (mInfo == null ? "null" : mInfo.provider), e);
282 }
283 }
284
285 private SizeF computeSizeFromLayout(int left, int top, int right, int bottom) {
286 float density = getResources().getDisplayMetrics().density;
287 return new SizeF(
288 (right - left - getPaddingLeft() - getPaddingRight()) / density,
289 (bottom - top - getPaddingTop() - getPaddingBottom()) / density
290 );
291 }
292
293 @Override
294 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
295 try {
296 SizeF oldSize = mCurrentSize;
297 SizeF newSize = computeSizeFromLayout(left, top, right, bottom);
298 mCurrentSize = newSize;
299 if (mLastInflatedRemoteViews != null) {
300 RemoteViews toApply = mLastInflatedRemoteViews.getRemoteViewsToApplyIfDifferent(
301 oldSize, newSize);
302 if (toApply != null) {
303 applyRemoteViews(toApply, false);
304 measureChildWithMargins(mView,
305 MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
306 0 /* widthUsed */,
307 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY),
308 0 /* heightUsed */);
309 }
310 }
311 super.onLayout(changed, left, top, right, bottom);
312 } catch (final RuntimeException e) {
313 Log.e(TAG, "Remote provider threw runtime exception, using error view instead.", e);
314 removeViewInLayout(mView);
315 View child = getErrorView();
316 prepareView(child);
317 addViewInLayout(child, 0, child.getLayoutParams());
318 measureChild(child, MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
319 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
320 child.layout(0, 0, child.getMeasuredWidth() + mPaddingLeft + mPaddingRight,
321 child.getMeasuredHeight() + mPaddingTop + mPaddingBottom);
322 mView = child;
323 mViewMode = VIEW_MODE_ERROR;
324 }
325 }
326
327 /**
328 * Provide guidance about the size of this widget to the AppWidgetManager. The widths and
329 * heights should correspond to the full area the AppWidgetHostView is given. Padding added by
330 * the framework will be accounted for automatically. This information gets embedded into the
331 * AppWidget options and causes a callback to the AppWidgetProvider. In addition, the list of
332 * sizes is explicitly set to an empty list.
333 * @see AppWidgetProvider#onAppWidgetOptionsChanged(Context, AppWidgetManager, int, Bundle)
334 *
335 * @param newOptions The bundle of options, in addition to the size information,
336 * can be null.
337 * @param minWidth The minimum width in dips that the widget will be displayed at.
338 * @param minHeight The maximum height in dips that the widget will be displayed at.
339 * @param maxWidth The maximum width in dips that the widget will be displayed at.
340 * @param maxHeight The maximum height in dips that the widget will be displayed at.
341 * @deprecated use {@link AppWidgetHostView#updateAppWidgetSize(Bundle, List)} instead.
342 */
343 @Deprecated
344 public void updateAppWidgetSize(Bundle newOptions, int minWidth, int minHeight, int maxWidth,
345 int maxHeight) {
346 updateAppWidgetSize(newOptions, minWidth, minHeight, maxWidth, maxHeight, false);
347 }
348
349 /**
350 * Provide guidance about the size of this widget to the AppWidgetManager. The sizes should
351 * correspond to the full area the AppWidgetHostView is given. Padding added by the framework
352 * will be accounted for automatically.
353 *
354 * This method will update the option bundle with the list of sizes and the min/max bounds for
355 * width and height.
356 *
357 * @see AppWidgetProvider#onAppWidgetOptionsChanged(Context, AppWidgetManager, int, Bundle)
358 *
359 * @param newOptions The bundle of options, in addition to the size information.
360 * @param sizes Sizes, in dips, the widget may be displayed at without calling the provider
361 * again. Typically, this will be size of the widget in landscape and portrait.
362 * On some foldables, this might include the size on the outer and inner screens.
363 */
364 public void updateAppWidgetSize(@NonNull Bundle newOptions, @NonNull List<SizeF> sizes) {
365 AppWidgetManager widgetManager = AppWidgetManager.getInstance(mContext);
366
367 Rect padding = getDefaultPadding();
368 float density = getResources().getDisplayMetrics().density;
369
370 float xPaddingDips = (padding.left + padding.right) / density;
371 float yPaddingDips = (padding.top + padding.bottom) / density;
372
373 ArrayList<SizeF> paddedSizes = new ArrayList<>(sizes.size());
374 float minWidth = Float.MAX_VALUE;
375 float maxWidth = 0;
376 float minHeight = Float.MAX_VALUE;
377 float maxHeight = 0;
378 for (int i = 0; i < sizes.size(); i++) {
379 SizeF size = sizes.get(i);
380 SizeF paddedSize = new SizeF(Math.max(0.f, size.getWidth() - xPaddingDips),
381 Math.max(0.f, size.getHeight() - yPaddingDips));
382 paddedSizes.add(paddedSize);
383 minWidth = Math.min(minWidth, paddedSize.getWidth());
384 maxWidth = Math.max(maxWidth, paddedSize.getWidth());
385 minHeight = Math.min(minHeight, paddedSize.getHeight());
386 maxHeight = Math.max(maxHeight, paddedSize.getHeight());
387 }
388 if (paddedSizes.equals(
389 widgetManager.getAppWidgetOptions(mAppWidgetId).<SizeF>getParcelableArrayList(
390 AppWidgetManager.OPTION_APPWIDGET_SIZES))) {
391 return;
392 }
393 Bundle options = newOptions.deepCopy();
394 options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, (int) minWidth);
395 options.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, (int) minHeight);
396 options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, (int) maxWidth);
397 options.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, (int) maxHeight);
398 options.putParcelableArrayList(AppWidgetManager.OPTION_APPWIDGET_SIZES, paddedSizes);
399 updateAppWidgetOptions(options);
400 }
401
402 /**
403 * @hide
404 */
405 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
406 public void updateAppWidgetSize(Bundle newOptions, int minWidth, int minHeight, int maxWidth,
407 int maxHeight, boolean ignorePadding) {
408 if (newOptions == null) {
409 newOptions = new Bundle();
410 }
411
412 Rect padding = getDefaultPadding();
413 float density = getResources().getDisplayMetrics().density;
414
415 int xPaddingDips = (int) ((padding.left + padding.right) / density);
416 int yPaddingDips = (int) ((padding.top + padding.bottom) / density);
417
418 int newMinWidth = minWidth - (ignorePadding ? 0 : xPaddingDips);
419 int newMinHeight = minHeight - (ignorePadding ? 0 : yPaddingDips);
420 int newMaxWidth = maxWidth - (ignorePadding ? 0 : xPaddingDips);
421 int newMaxHeight = maxHeight - (ignorePadding ? 0 : yPaddingDips);
422
423 AppWidgetManager widgetManager = AppWidgetManager.getInstance(mContext);
424
425 // We get the old options to see if the sizes have changed
426 Bundle oldOptions = widgetManager.getAppWidgetOptions(mAppWidgetId);
427 boolean needsUpdate = false;
428 if (newMinWidth != oldOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH) ||
429 newMinHeight != oldOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT) ||
430 newMaxWidth != oldOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH) ||
431 newMaxHeight != oldOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)) {
432 needsUpdate = true;
433 }
434
435 if (needsUpdate) {
436 newOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, newMinWidth);
437 newOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, newMinHeight);
438 newOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, newMaxWidth);
439 newOptions.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, newMaxHeight);
440 newOptions.putParcelableArrayList(AppWidgetManager.OPTION_APPWIDGET_SIZES,
441 new ArrayList<PointF>());
442 updateAppWidgetOptions(newOptions);
443 }
444 }
445
446 /**
447 * Specify some extra information for the widget provider. Causes a callback to the
448 * AppWidgetProvider.
449 * @see AppWidgetProvider#onAppWidgetOptionsChanged(Context, AppWidgetManager, int, Bundle)
450 *
451 * @param options The bundle of options information.
452 */
453 public void updateAppWidgetOptions(Bundle options) {
454 AppWidgetManager.getInstance(mContext).updateAppWidgetOptions(mAppWidgetId, options);
455 }
456
457 /** {@inheritDoc} */
458 @Override
459 public LayoutParams generateLayoutParams(AttributeSet attrs) {
460 // We're being asked to inflate parameters, probably by a LayoutInflater
461 // in a remote Context. To help resolve any remote references, we
462 // inflate through our last mRemoteContext when it exists.
463 final Context context = mRemoteContext != null ? mRemoteContext : mContext;
464 return new FrameLayout.LayoutParams(context, attrs);
465 }
466
467 /**
468 * Sets an executor which can be used for asynchronously inflating. CPU intensive tasks like
469 * view inflation or loading images will be performed on the executor. The updates will still
470 * be applied on the UI thread.
471 *
472 * @param executor the executor to use or null.
473 */
474 public void setExecutor(Executor executor) {
475 if (mLastExecutionSignal != null) {
476 mLastExecutionSignal.cancel();
477 mLastExecutionSignal = null;
478 }
479
480 mAsyncExecutor = executor;
481 }
482
483 /**
484 * Sets whether the widget is being displayed on a light/white background and use an
485 * alternate UI if available.
486 * @see RemoteViews#setLightBackgroundLayoutId(int)
487 */
488 public void setOnLightBackground(boolean onLightBackground) {
489 mOnLightBackground = onLightBackground;
490 }
491
492 /**
493 * Update the AppWidgetProviderInfo for this view, and reset it to the
494 * initial layout.
495 *
496 * @hide
497 */
498 @Override
499 public void onUpdateProviderInfo(@Nullable AppWidgetProviderInfo info) {
500 setAppWidget(mAppWidgetId, info);
501 mViewMode = VIEW_MODE_NOINIT;
502 updateAppWidget(null);
503 }
504
505 /**
506 * Process a set of {@link RemoteViews} coming in as an update from the
507 * AppWidget provider. Will animate into these new views as needed
508 */
509 @Override
510 public void updateAppWidget(RemoteViews remoteViews) {
511 mLastInflatedRemoteViews = remoteViews;
512 applyRemoteViews(remoteViews, true);
513 }
514
515 /**
516 * Reapply the last inflated remote views, or the default view is none was inflated.
517 */
518 private void reapplyLastRemoteViews() {
519 SparseArray<Parcelable> savedState = new SparseArray<>();
520 saveHierarchyState(savedState);
521 applyRemoteViews(mLastInflatedRemoteViews, true);
522 restoreHierarchyState(savedState);
523 }
524
525 /**
526 * @hide
527 */
528 protected void applyRemoteViews(@Nullable RemoteViews remoteViews, boolean useAsyncIfPossible) {
529 boolean recycled = false;
530 View content = null;
531 Exception exception = null;
532
533 // Block state restore until the end of the apply.
534 mLastInflatedRemoteViewsId = -1;
535
536 if (mLastExecutionSignal != null) {
537 mLastExecutionSignal.cancel();
538 mLastExecutionSignal = null;
539 }
540
541 if (remoteViews == null) {
542 if (mViewMode == VIEW_MODE_DEFAULT) {
543 // We've already done this -- nothing to do.
544 return;
545 }
546 content = getDefaultView();
547 mViewMode = VIEW_MODE_DEFAULT;
548 } else {
549 // Select the remote view we are actually going to apply.
550 RemoteViews rvToApply = remoteViews.getRemoteViewsToApply(mContext, mCurrentSize);
551 if (mOnLightBackground) {
552 rvToApply = rvToApply.getDarkTextViews();
553 }
554
555 if (mAsyncExecutor != null && useAsyncIfPossible) {
556 inflateAsync(rvToApply);
557 return;
558 }
559 // Prepare a local reference to the remote Context so we're ready to
560 // inflate any requested LayoutParams.
561 mRemoteContext = getRemoteContextEnsuringCorrectCachedApkPath();
562
563 if (!mColorMappingChanged && rvToApply.canRecycleView(mView)) {
564 try {
565 rvToApply.reapply(mContext, mView, mInteractionHandler, mCurrentSize,
566 mColorResources);
567 content = mView;
568 mLastInflatedRemoteViewsId = rvToApply.computeUniqueId(remoteViews);
569 recycled = true;
570 if (LOGD) Log.d(TAG, "was able to recycle existing layout");
571 } catch (RuntimeException e) {
572 exception = e;
573 }
574 }
575
576 // Try normal RemoteView inflation
577 if (content == null) {
578 try {
579 content = rvToApply.apply(mContext, this, mInteractionHandler,
580 mCurrentSize, mColorResources);
581 mLastInflatedRemoteViewsId = rvToApply.computeUniqueId(remoteViews);
582 if (LOGD) Log.d(TAG, "had to inflate new layout");
583 } catch (RuntimeException e) {
584 exception = e;
585 }
586 }
587
588 mViewMode = VIEW_MODE_CONTENT;
589 }
590
591 applyContent(content, recycled, exception);
592 }
593
594 private void applyContent(View content, boolean recycled, Exception exception) {
595 mColorMappingChanged = false;
596 if (content == null) {
597 if (mViewMode == VIEW_MODE_ERROR) {
598 // We've already done this -- nothing to do.
599 return ;
600 }
601 if (exception != null) {
602 Log.w(TAG, "Error inflating RemoteViews", exception);
603 }
604 content = getErrorView();
605 mViewMode = VIEW_MODE_ERROR;
606 }
607
608 if (!recycled) {
609 prepareView(content);
610 addView(content);
611 }
612
613 if (mView != content) {
614 removeView(mView);
615 mView = content;
616 }
617 }
618
619 private void inflateAsync(@NonNull RemoteViews remoteViews) {
620 // Prepare a local reference to the remote Context so we're ready to
621 // inflate any requested LayoutParams.
622 mRemoteContext = getRemoteContextEnsuringCorrectCachedApkPath();
623 int layoutId = remoteViews.getLayoutId();
624
625 if (mLastExecutionSignal != null) {
626 mLastExecutionSignal.cancel();
627 }
628
629 // If our stale view has been prepared to match active, and the new
630 // layout matches, try recycling it
631 if (!mColorMappingChanged && remoteViews.canRecycleView(mView)) {
632 try {
633 mLastExecutionSignal = remoteViews.reapplyAsync(mContext,
634 mView,
635 mAsyncExecutor,
636 new ViewApplyListener(remoteViews, layoutId, true),
637 mInteractionHandler,
638 mCurrentSize,
639 mColorResources);
640 } catch (Exception e) {
641 // Reapply failed. Try apply
642 }
643 }
644 if (mLastExecutionSignal == null) {
645 mLastExecutionSignal = remoteViews.applyAsync(mContext,
646 this,
647 mAsyncExecutor,
648 new ViewApplyListener(remoteViews, layoutId, false),
649 mInteractionHandler,
650 mCurrentSize,
651 mColorResources);
652 }
653 }
654
655 private class ViewApplyListener implements RemoteViews.OnViewAppliedListener {
656 private final RemoteViews mViews;
657 private final boolean mIsReapply;
658 private final int mLayoutId;
659
660 ViewApplyListener(
661 RemoteViews views,
662 int layoutId,
663 boolean isReapply) {
664 mViews = views;
665 mLayoutId = layoutId;
666 mIsReapply = isReapply;
667 }
668
669 @Override
670 public void onViewApplied(View v) {
671 mViewMode = VIEW_MODE_CONTENT;
672
673 applyContent(v, mIsReapply, null);
674
675 mLastInflatedRemoteViewsId = mViews.computeUniqueId(mLastInflatedRemoteViews);
676 restoreInstanceState();
677 mLastExecutionSignal = null;
678 }
679
680 @Override
681 public void onError(Exception e) {
682 if (mIsReapply) {
683 // Try a fresh replay
684 mLastExecutionSignal = mViews.applyAsync(mContext,
685 AppWidgetHostView.this,
686 mAsyncExecutor,
687 new ViewApplyListener(mViews, mLayoutId, false),
688 mInteractionHandler,
689 mCurrentSize);
690 } else {
691 applyContent(null, false, e);
692 }
693 mLastExecutionSignal = null;
694 }
695 }
696
697 /**
698 * Process data-changed notifications for the specified view in the specified
699 * set of {@link RemoteViews} views.
700 *
701 * @hide
702 */
703 @Override
704 public void onViewDataChanged(int viewId) {
705 View v = findViewById(viewId);
706 if ((v != null) && (v instanceof AdapterView<?>)) {
707 AdapterView<?> adapterView = (AdapterView<?>) v;
708 Adapter adapter = adapterView.getAdapter();
709 if (adapter instanceof BaseAdapter) {
710 BaseAdapter baseAdapter = (BaseAdapter) adapter;
711 baseAdapter.notifyDataSetChanged();
712 } else if (adapter == null && adapterView instanceof RemoteAdapterConnectionCallback) {
713 // If the adapter is null, it may mean that the RemoteViewsAapter has not yet
714 // connected to its associated service, and hence the adapter hasn't been set.
715 // In this case, we need to defer the notify call until it has been set.
716 ((RemoteAdapterConnectionCallback) adapterView).deferNotifyDataSetChanged();
717 }
718 }
719 }
720
721 /**
722 * Build a {@link Context} cloned into another package name, usually for the
723 * purposes of reading remote resources.
724 * @hide
725 */
726 protected Context getRemoteContextEnsuringCorrectCachedApkPath() {
727 try {
728 ApplicationInfo expectedAppInfo = mInfo.providerInfo.applicationInfo;
729 LoadedApk.checkAndUpdateApkPaths(expectedAppInfo);
730 // Return if cloned successfully, otherwise default
731 Context newContext = mContext.createApplicationContext(
732 mInfo.providerInfo.applicationInfo,
733 Context.CONTEXT_RESTRICTED);
734 if (mColorResources != null) {
735 mColorResources.apply(newContext);
736 }
737 return newContext;
738 } catch (NameNotFoundException e) {
739 Log.e(TAG, "Package name " + mInfo.providerInfo.packageName + " not found");
740 return mContext;
741 } catch (NullPointerException e) {
742 Log.e(TAG, "Error trying to create the remote context.", e);
743 return mContext;
744 }
745 }
746
747 /**
748 * Prepare the given view to be shown. This might include adjusting
749 * {@link FrameLayout.LayoutParams} before inserting.
750 */
751 protected void prepareView(View view) {
752 // Take requested dimensions from child, but apply default gravity.
753 FrameLayout.LayoutParams requested = (FrameLayout.LayoutParams)view.getLayoutParams();
754 if (requested == null) {
755 requested = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,
756 LayoutParams.MATCH_PARENT);
757 }
758
759 requested.gravity = Gravity.CENTER;
760 view.setLayoutParams(requested);
761 }
762
763 /**
764 * Inflate and return the default layout requested by AppWidget provider.
765 */
766 protected View getDefaultView() {
767 if (LOGD) {
768 Log.d(TAG, "getDefaultView");
769 }
770 View defaultView = null;
771 Exception exception = null;
772
773 try {
774 if (mInfo != null) {
775 Context theirContext = getRemoteContextEnsuringCorrectCachedApkPath();
776 mRemoteContext = theirContext;
777 LayoutInflater inflater = (LayoutInflater)
778 theirContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
779 inflater = inflater.cloneInContext(theirContext);
780 inflater.setFilter(INFLATER_FILTER);
781 AppWidgetManager manager = AppWidgetManager.getInstance(mContext);
782 Bundle options = manager.getAppWidgetOptions(mAppWidgetId);
783
784 int layoutId = mInfo.initialLayout;
785 if (options.containsKey(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY)) {
786 int category = options.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY);
787 if (category == AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD) {
788 int kgLayoutId = mInfo.initialKeyguardLayout;
789 // If a default keyguard layout is not specified, use the standard
790 // default layout.
791 layoutId = kgLayoutId == 0 ? layoutId : kgLayoutId;
792 }
793 }
794 defaultView = inflater.inflate(layoutId, this, false);
795 if (!(defaultView instanceof AdapterView)) {
796 // AdapterView does not support onClickListener
797 defaultView.setOnClickListener(this::onDefaultViewClicked);
798 }
799 } else {
800 Log.w(TAG, "can't inflate defaultView because mInfo is missing");
801 }
802 } catch (RuntimeException e) {
803 exception = e;
804 }
805
806 if (exception != null) {
807 Log.w(TAG, "Error inflating AppWidget " + mInfo, exception);
808 }
809
810 if (defaultView == null) {
811 if (LOGD) Log.d(TAG, "getDefaultView couldn't find any view, so inflating error");
812 defaultView = getErrorView();
813 }
814
815 return defaultView;
816 }
817
818 private void onDefaultViewClicked(View view) {
819 if (mInfo != null) {
820 LauncherApps launcherApps = getContext().getSystemService(LauncherApps.class);
821 List<LauncherActivityInfo> activities = launcherApps.getActivityList(
822 mInfo.provider.getPackageName(), mInfo.getProfile());
823 if (!activities.isEmpty()) {
824 LauncherActivityInfo ai = activities.get(0);
825 launcherApps.startMainActivity(ai.getComponentName(), ai.getUser(),
826 RemoteViews.getSourceBounds(view), null);
827 }
828 }
829 }
830
831 /**
832 * Inflate and return a view that represents an error state.
833 */
834 protected View getErrorView() {
835 TextView tv = new TextView(mContext);
836 tv.setText(com.android.internal.R.string.gadget_host_error_inflating);
837 // TODO: get this color from somewhere.
838 tv.setBackgroundColor(Color.argb(127, 0, 0, 0));
839 return tv;
840 }
841
842 /** @hide */
843 @Override
844 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
845 super.onInitializeAccessibilityNodeInfoInternal(info);
846 info.setClassName(AppWidgetHostView.class.getName());
847 }
848
849 /** @hide */
850 public ActivityOptions createSharedElementActivityOptions(
851 int[] sharedViewIds, String[] sharedViewNames, Intent fillInIntent) {
852 Context parentContext = getContext();
853 while ((parentContext instanceof ContextWrapper)
854 && !(parentContext instanceof Activity)) {
855 parentContext = ((ContextWrapper) parentContext).getBaseContext();
856 }
857 if (!(parentContext instanceof Activity)) {
858 return null;
859 }
860
861 List<Pair<View, String>> sharedElements = new ArrayList<>();
862 Bundle extras = new Bundle();
863
864 for (int i = 0; i < sharedViewIds.length; i++) {
865 View view = findViewById(sharedViewIds[i]);
866 if (view != null) {
867 sharedElements.add(Pair.create(view, sharedViewNames[i]));
868
869 extras.putParcelable(sharedViewNames[i], RemoteViews.getSourceBounds(view));
870 }
871 }
872
873 if (!sharedElements.isEmpty()) {
874 fillInIntent.putExtra(RemoteViews.EXTRA_SHARED_ELEMENT_BOUNDS, extras);
875 final ActivityOptions opts = ActivityOptions.makeSceneTransitionAnimation(
876 (Activity) parentContext,
877 sharedElements.toArray(new Pair[sharedElements.size()]));
878 opts.setPendingIntentLaunchFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
879 return opts;
880 }
881 return null;
882 }
883
884 private InteractionHandler getHandler(InteractionHandler handler) {
885 return (view, pendingIntent, response) -> {
886 AppWidgetManager.getInstance(mContext).noteAppWidgetTapped(mAppWidgetId);
887 if (handler != null) {
888 return handler.onInteraction(view, pendingIntent, response);
889 } else {
890 return RemoteViews.startPendingIntent(view, pendingIntent,
891 response.getLaunchOptions(view));
892 }
893 };
894 }
895
896 /**
897 * Set the dynamically overloaded color resources.
898 *
899 * {@code colorMapping} maps a predefined set of color resources to their ARGB
900 * representation. Any entry not in the predefined set of colors will be ignored.
901 *
902 * Calling this method will trigger a full re-inflation of the App Widget.
903 *
904 * The color resources that can be overloaded are the ones whose name is prefixed with
905 * {@code system_neutral} or {@code system_accent}, for example
906 * {@link android.R.color#system_neutral1_500}.
907 */
908 public void setColorResources(@NonNull SparseIntArray colorMapping) {
909 if (mColorResources != null
910 && isSameColorMapping(mColorResources.getColorMapping(), colorMapping)) {
911 return;
912 }
913 setColorResources(RemoteViews.ColorResources.create(mContext, colorMapping));
914 }
915
916 /** @hide **/
917 public void setColorResources(RemoteViews.ColorResources colorResources) {
918 if (colorResources == mColorResources) {
919 return;
920 }
921 mColorResources = colorResources;
922 mColorMappingChanged = true;
923 mViewMode = VIEW_MODE_NOINIT;
924 reapplyLastRemoteViews();
925 }
926
927 /** Check if, in the current context, the two color mappings are equivalent. */
928 private boolean isSameColorMapping(SparseIntArray oldColors, SparseIntArray newColors) {
929 if (oldColors.size() != newColors.size()) {
930 return false;
931 }
932 for (int i = 0; i < oldColors.size(); i++) {
933 if (oldColors.keyAt(i) != newColors.keyAt(i)
934 || oldColors.valueAt(i) != newColors.valueAt(i)) {
935 return false;
936 }
937 }
938 return true;
939 }
940
941 /**
942 * Reset the dynamically overloaded resources, reverting to the default values for
943 * all the colors.
944 *
945 * If colors were defined before, calling this method will trigger a full re-inflation of the
946 * App Widget.
947 */
948 public void resetColorResources() {
949 if (mColorResources != null) {
950 mColorResources = null;
951 mColorMappingChanged = true;
952 mViewMode = VIEW_MODE_NOINIT;
953 reapplyLastRemoteViews();
954 }
955 }
956 }