RemoteViews.java revision 976e8bd2017d0263216c62111454438cc0f130e3
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 17package android.widget; 18 19import android.app.ActivityOptions; 20import android.app.ActivityThread; 21import android.app.PendingIntent; 22import android.appwidget.AppWidgetHostView; 23import android.content.Context; 24import android.content.Intent; 25import android.content.IntentSender; 26import android.content.pm.ApplicationInfo; 27import android.content.pm.PackageManager.NameNotFoundException; 28import android.content.res.Configuration; 29import android.graphics.Bitmap; 30import android.graphics.PorterDuff; 31import android.graphics.Rect; 32import android.graphics.drawable.Drawable; 33import android.net.Uri; 34import android.os.Build; 35import android.os.Bundle; 36import android.os.Parcel; 37import android.os.Parcelable; 38import android.os.StrictMode; 39import android.os.UserHandle; 40import android.text.TextUtils; 41import android.util.ArrayMap; 42import android.util.Log; 43import android.view.LayoutInflater; 44import android.view.LayoutInflater.Filter; 45import android.view.RemotableViewMethod; 46import android.view.View; 47import android.view.View.OnClickListener; 48import android.view.ViewGroup; 49import android.widget.AdapterView.OnItemClickListener; 50import libcore.util.Objects; 51 52import java.lang.annotation.ElementType; 53import java.lang.annotation.Retention; 54import java.lang.annotation.RetentionPolicy; 55import java.lang.annotation.Target; 56import java.lang.reflect.Method; 57import java.util.ArrayList; 58import java.util.HashMap; 59 60/** 61 * A class that describes a view hierarchy that can be displayed in 62 * another process. The hierarchy is inflated from a layout resource 63 * file, and this class provides some basic operations for modifying 64 * the content of the inflated hierarchy. 65 */ 66public class RemoteViews implements Parcelable, Filter { 67 68 private static final String LOG_TAG = "RemoteViews"; 69 70 /** 71 * The intent extra that contains the appWidgetId. 72 * @hide 73 */ 74 static final String EXTRA_REMOTEADAPTER_APPWIDGET_ID = "remoteAdapterAppWidgetId"; 75 76 /** 77 * Application that hosts the remote views. 78 * 79 * @hide 80 */ 81 private ApplicationInfo mApplication; 82 83 /** 84 * The package name of the package containing the layout 85 * resource. (Added to the parcel) 86 */ 87 private final String mPackage; 88 89 /** 90 * The resource ID of the layout file. (Added to the parcel) 91 */ 92 private final int mLayoutId; 93 94 /** 95 * An array of actions to perform on the view tree once it has been 96 * inflated 97 */ 98 private ArrayList<Action> mActions; 99 100 /** 101 * A class to keep track of memory usage by this RemoteViews 102 */ 103 private MemoryUsageCounter mMemoryUsageCounter; 104 105 /** 106 * Maps bitmaps to unique indicies to avoid Bitmap duplication. 107 */ 108 private BitmapCache mBitmapCache; 109 110 /** 111 * Indicates whether or not this RemoteViews object is contained as a child of any other 112 * RemoteViews. 113 */ 114 private boolean mIsRoot = true; 115 116 /** 117 * Constants to whether or not this RemoteViews is composed of a landscape and portrait 118 * RemoteViews. 119 */ 120 private static final int MODE_NORMAL = 0; 121 private static final int MODE_HAS_LANDSCAPE_AND_PORTRAIT = 1; 122 123 /** 124 * Used in conjunction with the special constructor 125 * {@link #RemoteViews(RemoteViews, RemoteViews)} to keep track of the landscape and portrait 126 * RemoteViews. 127 */ 128 private RemoteViews mLandscape = null; 129 private RemoteViews mPortrait = null; 130 131 /** 132 * This flag indicates whether this RemoteViews object is being created from a 133 * RemoteViewsService for use as a child of a widget collection. This flag is used 134 * to determine whether or not certain features are available, in particular, 135 * setting on click extras and setting on click pending intents. The former is enabled, 136 * and the latter disabled when this flag is true. 137 */ 138 private boolean mIsWidgetCollectionChild = false; 139 140 private static final OnClickHandler DEFAULT_ON_CLICK_HANDLER = new OnClickHandler(); 141 142 private static final Object[] sMethodsLock = new Object[0]; 143 private static final ArrayMap<Class<? extends View>, ArrayMap<MutablePair<String, Class<?>>, Method>> sMethods = 144 new ArrayMap<Class<? extends View>, ArrayMap<MutablePair<String, Class<?>>, Method>>(); 145 private static final ThreadLocal<Object[]> sInvokeArgsTls = new ThreadLocal<Object[]>() { 146 @Override 147 protected Object[] initialValue() { 148 return new Object[1]; 149 } 150 }; 151 152 /** 153 * Handle with care! 154 */ 155 static class MutablePair<F, S> { 156 F first; 157 S second; 158 159 MutablePair(F first, S second) { 160 this.first = first; 161 this.second = second; 162 } 163 164 @Override 165 public boolean equals(Object o) { 166 if (!(o instanceof MutablePair)) { 167 return false; 168 } 169 MutablePair<?, ?> p = (MutablePair<?, ?>) o; 170 return Objects.equal(p.first, first) && Objects.equal(p.second, second); 171 } 172 173 @Override 174 public int hashCode() { 175 return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); 176 } 177 } 178 179 /** 180 * This pair is used to perform lookups in sMethods without causing allocations. 181 */ 182 private final MutablePair<String, Class<?>> mPair = 183 new MutablePair<String, Class<?>>(null, null); 184 185 /** 186 * This annotation indicates that a subclass of View is alllowed to be used 187 * with the {@link RemoteViews} mechanism. 188 */ 189 @Target({ ElementType.TYPE }) 190 @Retention(RetentionPolicy.RUNTIME) 191 public @interface RemoteView { 192 } 193 194 /** 195 * Exception to send when something goes wrong executing an action 196 * 197 */ 198 public static class ActionException extends RuntimeException { 199 public ActionException(Exception ex) { 200 super(ex); 201 } 202 public ActionException(String message) { 203 super(message); 204 } 205 } 206 207 /** @hide */ 208 public static class OnClickHandler { 209 public boolean onClickHandler(View view, PendingIntent pendingIntent, 210 Intent fillInIntent) { 211 try { 212 // TODO: Unregister this handler if PendingIntent.FLAG_ONE_SHOT? 213 Context context = view.getContext(); 214 ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(view, 215 0, 0, 216 view.getMeasuredWidth(), view.getMeasuredHeight()); 217 context.startIntentSender( 218 pendingIntent.getIntentSender(), fillInIntent, 219 Intent.FLAG_ACTIVITY_NEW_TASK, 220 Intent.FLAG_ACTIVITY_NEW_TASK, 0, opts.toBundle()); 221 } catch (IntentSender.SendIntentException e) { 222 android.util.Log.e(LOG_TAG, "Cannot send pending intent: ", e); 223 return false; 224 } catch (Exception e) { 225 android.util.Log.e(LOG_TAG, "Cannot send pending intent due to " + 226 "unknown exception: ", e); 227 return false; 228 } 229 return true; 230 } 231 } 232 233 /** 234 * Base class for all actions that can be performed on an 235 * inflated view. 236 * 237 * SUBCLASSES MUST BE IMMUTABLE SO CLONE WORKS!!!!! 238 */ 239 private abstract static class Action implements Parcelable { 240 public abstract void apply(View root, ViewGroup rootParent, 241 OnClickHandler handler) throws ActionException; 242 243 public static final int MERGE_REPLACE = 0; 244 public static final int MERGE_APPEND = 1; 245 public static final int MERGE_IGNORE = 2; 246 247 public int describeContents() { 248 return 0; 249 } 250 251 /** 252 * Overridden by each class to report on it's own memory usage 253 */ 254 public void updateMemoryUsageEstimate(MemoryUsageCounter counter) { 255 // We currently only calculate Bitmap memory usage, so by default, 256 // don't do anything here 257 } 258 259 public void setBitmapCache(BitmapCache bitmapCache) { 260 // Do nothing 261 } 262 263 public int mergeBehavior() { 264 return MERGE_REPLACE; 265 } 266 267 public abstract String getActionName(); 268 269 public String getUniqueKey() { 270 return (getActionName() + viewId); 271 } 272 273 int viewId; 274 } 275 276 /** 277 * Merges the passed RemoteViews actions with this RemoteViews actions according to 278 * action-specific merge rules. 279 * 280 * @param newRv 281 * 282 * @hide 283 */ 284 public void mergeRemoteViews(RemoteViews newRv) { 285 if (newRv == null) return; 286 // We first copy the new RemoteViews, as the process of merging modifies the way the actions 287 // reference the bitmap cache. We don't want to modify the object as it may need to 288 // be merged and applied multiple times. 289 RemoteViews copy = newRv.clone(); 290 291 HashMap<String, Action> map = new HashMap<String, Action>(); 292 if (mActions == null) { 293 mActions = new ArrayList<Action>(); 294 } 295 296 int count = mActions.size(); 297 for (int i = 0; i < count; i++) { 298 Action a = mActions.get(i); 299 map.put(a.getUniqueKey(), a); 300 } 301 302 ArrayList<Action> newActions = copy.mActions; 303 if (newActions == null) return; 304 count = newActions.size(); 305 for (int i = 0; i < count; i++) { 306 Action a = newActions.get(i); 307 String key = newActions.get(i).getUniqueKey(); 308 int mergeBehavior = newActions.get(i).mergeBehavior(); 309 if (map.containsKey(key) && mergeBehavior == Action.MERGE_REPLACE) { 310 mActions.remove(map.get(key)); 311 map.remove(key); 312 } 313 314 // If the merge behavior is ignore, we don't bother keeping the extra action 315 if (mergeBehavior == Action.MERGE_REPLACE || mergeBehavior == Action.MERGE_APPEND) { 316 mActions.add(a); 317 } 318 } 319 320 // Because pruning can remove the need for bitmaps, we reconstruct the bitmap cache 321 mBitmapCache = new BitmapCache(); 322 setBitmapCache(mBitmapCache); 323 } 324 325 private class SetEmptyView extends Action { 326 int viewId; 327 int emptyViewId; 328 329 public final static int TAG = 6; 330 331 SetEmptyView(int viewId, int emptyViewId) { 332 this.viewId = viewId; 333 this.emptyViewId = emptyViewId; 334 } 335 336 SetEmptyView(Parcel in) { 337 this.viewId = in.readInt(); 338 this.emptyViewId = in.readInt(); 339 } 340 341 public void writeToParcel(Parcel out, int flags) { 342 out.writeInt(TAG); 343 out.writeInt(this.viewId); 344 out.writeInt(this.emptyViewId); 345 } 346 347 @Override 348 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 349 final View view = root.findViewById(viewId); 350 if (!(view instanceof AdapterView<?>)) return; 351 352 AdapterView<?> adapterView = (AdapterView<?>) view; 353 354 final View emptyView = root.findViewById(emptyViewId); 355 if (emptyView == null) return; 356 357 adapterView.setEmptyView(emptyView); 358 } 359 360 public String getActionName() { 361 return "SetEmptyView"; 362 } 363 } 364 365 private class SetOnClickFillInIntent extends Action { 366 public SetOnClickFillInIntent(int id, Intent fillInIntent) { 367 this.viewId = id; 368 this.fillInIntent = fillInIntent; 369 } 370 371 public SetOnClickFillInIntent(Parcel parcel) { 372 viewId = parcel.readInt(); 373 fillInIntent = Intent.CREATOR.createFromParcel(parcel); 374 } 375 376 public void writeToParcel(Parcel dest, int flags) { 377 dest.writeInt(TAG); 378 dest.writeInt(viewId); 379 fillInIntent.writeToParcel(dest, 0 /* no flags */); 380 } 381 382 @Override 383 public void apply(View root, ViewGroup rootParent, final OnClickHandler handler) { 384 final View target = root.findViewById(viewId); 385 if (target == null) return; 386 387 if (!mIsWidgetCollectionChild) { 388 Log.e(LOG_TAG, "The method setOnClickFillInIntent is available " + 389 "only from RemoteViewsFactory (ie. on collection items)."); 390 return; 391 } 392 if (target == root) { 393 target.setTagInternal(com.android.internal.R.id.fillInIntent, fillInIntent); 394 } else if (fillInIntent != null) { 395 OnClickListener listener = new OnClickListener() { 396 public void onClick(View v) { 397 // Insure that this view is a child of an AdapterView 398 View parent = (View) v.getParent(); 399 while (parent != null && !(parent instanceof AdapterView<?>) 400 && !(parent instanceof AppWidgetHostView)) { 401 parent = (View) parent.getParent(); 402 } 403 404 if (parent instanceof AppWidgetHostView || parent == null) { 405 // Somehow they've managed to get this far without having 406 // and AdapterView as a parent. 407 Log.e(LOG_TAG, "Collection item doesn't have AdapterView parent"); 408 return; 409 } 410 411 // Insure that a template pending intent has been set on an ancestor 412 if (!(parent.getTag() instanceof PendingIntent)) { 413 Log.e(LOG_TAG, "Attempting setOnClickFillInIntent without" + 414 " calling setPendingIntentTemplate on parent."); 415 return; 416 } 417 418 PendingIntent pendingIntent = (PendingIntent) parent.getTag(); 419 420 final Rect rect = getSourceBounds(v); 421 422 fillInIntent.setSourceBounds(rect); 423 handler.onClickHandler(v, pendingIntent, fillInIntent); 424 } 425 426 }; 427 target.setOnClickListener(listener); 428 } 429 } 430 431 public String getActionName() { 432 return "SetOnClickFillInIntent"; 433 } 434 435 Intent fillInIntent; 436 437 public final static int TAG = 9; 438 } 439 440 private class SetPendingIntentTemplate extends Action { 441 public SetPendingIntentTemplate(int id, PendingIntent pendingIntentTemplate) { 442 this.viewId = id; 443 this.pendingIntentTemplate = pendingIntentTemplate; 444 } 445 446 public SetPendingIntentTemplate(Parcel parcel) { 447 viewId = parcel.readInt(); 448 pendingIntentTemplate = PendingIntent.readPendingIntentOrNullFromParcel(parcel); 449 } 450 451 public void writeToParcel(Parcel dest, int flags) { 452 dest.writeInt(TAG); 453 dest.writeInt(viewId); 454 pendingIntentTemplate.writeToParcel(dest, 0 /* no flags */); 455 } 456 457 @Override 458 public void apply(View root, ViewGroup rootParent, final OnClickHandler handler) { 459 final View target = root.findViewById(viewId); 460 if (target == null) return; 461 462 // If the view isn't an AdapterView, setting a PendingIntent template doesn't make sense 463 if (target instanceof AdapterView<?>) { 464 AdapterView<?> av = (AdapterView<?>) target; 465 // The PendingIntent template is stored in the view's tag. 466 OnItemClickListener listener = new OnItemClickListener() { 467 public void onItemClick(AdapterView<?> parent, View view, 468 int position, long id) { 469 // The view should be a frame layout 470 if (view instanceof ViewGroup) { 471 ViewGroup vg = (ViewGroup) view; 472 473 // AdapterViews contain their children in a frame 474 // so we need to go one layer deeper here. 475 if (parent instanceof AdapterViewAnimator) { 476 vg = (ViewGroup) vg.getChildAt(0); 477 } 478 if (vg == null) return; 479 480 Intent fillInIntent = null; 481 int childCount = vg.getChildCount(); 482 for (int i = 0; i < childCount; i++) { 483 Object tag = vg.getChildAt(i).getTag(com.android.internal.R.id.fillInIntent); 484 if (tag instanceof Intent) { 485 fillInIntent = (Intent) tag; 486 break; 487 } 488 } 489 if (fillInIntent == null) return; 490 491 final Rect rect = getSourceBounds(view); 492 493 final Intent intent = new Intent(); 494 intent.setSourceBounds(rect); 495 handler.onClickHandler(view, pendingIntentTemplate, fillInIntent); 496 } 497 } 498 }; 499 av.setOnItemClickListener(listener); 500 av.setTag(pendingIntentTemplate); 501 } else { 502 Log.e(LOG_TAG, "Cannot setPendingIntentTemplate on a view which is not" + 503 "an AdapterView (id: " + viewId + ")"); 504 return; 505 } 506 } 507 508 public String getActionName() { 509 return "SetPendingIntentTemplate"; 510 } 511 512 PendingIntent pendingIntentTemplate; 513 514 public final static int TAG = 8; 515 } 516 517 private class SetRemoteViewsAdapterList extends Action { 518 public SetRemoteViewsAdapterList(int id, ArrayList<RemoteViews> list, int viewTypeCount) { 519 this.viewId = id; 520 this.list = list; 521 this.viewTypeCount = viewTypeCount; 522 } 523 524 public SetRemoteViewsAdapterList(Parcel parcel) { 525 viewId = parcel.readInt(); 526 viewTypeCount = parcel.readInt(); 527 int count = parcel.readInt(); 528 list = new ArrayList<RemoteViews>(); 529 530 for (int i = 0; i < count; i++) { 531 RemoteViews rv = RemoteViews.CREATOR.createFromParcel(parcel); 532 list.add(rv); 533 } 534 } 535 536 public void writeToParcel(Parcel dest, int flags) { 537 dest.writeInt(TAG); 538 dest.writeInt(viewId); 539 dest.writeInt(viewTypeCount); 540 541 if (list == null || list.size() == 0) { 542 dest.writeInt(0); 543 } else { 544 int count = list.size(); 545 dest.writeInt(count); 546 for (int i = 0; i < count; i++) { 547 RemoteViews rv = list.get(i); 548 rv.writeToParcel(dest, flags); 549 } 550 } 551 } 552 553 @Override 554 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 555 final View target = root.findViewById(viewId); 556 if (target == null) return; 557 558 // Ensure that we are applying to an AppWidget root 559 if (!(rootParent instanceof AppWidgetHostView)) { 560 Log.e(LOG_TAG, "SetRemoteViewsAdapterIntent action can only be used for " + 561 "AppWidgets (root id: " + viewId + ")"); 562 return; 563 } 564 // Ensure that we are calling setRemoteAdapter on an AdapterView that supports it 565 if (!(target instanceof AbsListView) && !(target instanceof AdapterViewAnimator)) { 566 Log.e(LOG_TAG, "Cannot setRemoteViewsAdapter on a view which is not " + 567 "an AbsListView or AdapterViewAnimator (id: " + viewId + ")"); 568 return; 569 } 570 571 if (target instanceof AbsListView) { 572 AbsListView v = (AbsListView) target; 573 Adapter a = v.getAdapter(); 574 if (a instanceof RemoteViewsListAdapter && viewTypeCount <= a.getViewTypeCount()) { 575 ((RemoteViewsListAdapter) a).setViewsList(list); 576 } else { 577 v.setAdapter(new RemoteViewsListAdapter(v.getContext(), list, viewTypeCount)); 578 } 579 } else if (target instanceof AdapterViewAnimator) { 580 AdapterViewAnimator v = (AdapterViewAnimator) target; 581 Adapter a = v.getAdapter(); 582 if (a instanceof RemoteViewsListAdapter && viewTypeCount <= a.getViewTypeCount()) { 583 ((RemoteViewsListAdapter) a).setViewsList(list); 584 } else { 585 v.setAdapter(new RemoteViewsListAdapter(v.getContext(), list, viewTypeCount)); 586 } 587 } 588 } 589 590 public String getActionName() { 591 return "SetRemoteViewsAdapterList"; 592 } 593 594 int viewTypeCount; 595 ArrayList<RemoteViews> list; 596 public final static int TAG = 15; 597 } 598 599 private class SetRemoteViewsAdapterIntent extends Action { 600 public SetRemoteViewsAdapterIntent(int id, Intent intent) { 601 this.viewId = id; 602 this.intent = intent; 603 } 604 605 public SetRemoteViewsAdapterIntent(Parcel parcel) { 606 viewId = parcel.readInt(); 607 intent = Intent.CREATOR.createFromParcel(parcel); 608 } 609 610 public void writeToParcel(Parcel dest, int flags) { 611 dest.writeInt(TAG); 612 dest.writeInt(viewId); 613 intent.writeToParcel(dest, flags); 614 } 615 616 @Override 617 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 618 final View target = root.findViewById(viewId); 619 if (target == null) return; 620 621 // Ensure that we are applying to an AppWidget root 622 if (!(rootParent instanceof AppWidgetHostView)) { 623 Log.e(LOG_TAG, "SetRemoteViewsAdapterIntent action can only be used for " + 624 "AppWidgets (root id: " + viewId + ")"); 625 return; 626 } 627 // Ensure that we are calling setRemoteAdapter on an AdapterView that supports it 628 if (!(target instanceof AbsListView) && !(target instanceof AdapterViewAnimator)) { 629 Log.e(LOG_TAG, "Cannot setRemoteViewsAdapter on a view which is not " + 630 "an AbsListView or AdapterViewAnimator (id: " + viewId + ")"); 631 return; 632 } 633 634 // Embed the AppWidget Id for use in RemoteViewsAdapter when connecting to the intent 635 // RemoteViewsService 636 AppWidgetHostView host = (AppWidgetHostView) rootParent; 637 intent.putExtra(EXTRA_REMOTEADAPTER_APPWIDGET_ID, host.getAppWidgetId()); 638 if (target instanceof AbsListView) { 639 AbsListView v = (AbsListView) target; 640 v.setRemoteViewsAdapter(intent); 641 v.setRemoteViewsOnClickHandler(handler); 642 } else if (target instanceof AdapterViewAnimator) { 643 AdapterViewAnimator v = (AdapterViewAnimator) target; 644 v.setRemoteViewsAdapter(intent); 645 v.setRemoteViewsOnClickHandler(handler); 646 } 647 } 648 649 public String getActionName() { 650 return "SetRemoteViewsAdapterIntent"; 651 } 652 653 Intent intent; 654 655 public final static int TAG = 10; 656 } 657 658 /** 659 * Equivalent to calling 660 * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)} 661 * to launch the provided {@link PendingIntent}. 662 */ 663 private class SetOnClickPendingIntent extends Action { 664 public SetOnClickPendingIntent(int id, PendingIntent pendingIntent) { 665 this.viewId = id; 666 this.pendingIntent = pendingIntent; 667 } 668 669 public SetOnClickPendingIntent(Parcel parcel) { 670 viewId = parcel.readInt(); 671 672 // We check a flag to determine if the parcel contains a PendingIntent. 673 if (parcel.readInt() != 0) { 674 pendingIntent = PendingIntent.readPendingIntentOrNullFromParcel(parcel); 675 } 676 } 677 678 public void writeToParcel(Parcel dest, int flags) { 679 dest.writeInt(TAG); 680 dest.writeInt(viewId); 681 682 // We use a flag to indicate whether the parcel contains a valid object. 683 dest.writeInt(pendingIntent != null ? 1 : 0); 684 if (pendingIntent != null) { 685 pendingIntent.writeToParcel(dest, 0 /* no flags */); 686 } 687 } 688 689 @Override 690 public void apply(View root, ViewGroup rootParent, final OnClickHandler handler) { 691 final View target = root.findViewById(viewId); 692 if (target == null) return; 693 694 // If the view is an AdapterView, setting a PendingIntent on click doesn't make much 695 // sense, do they mean to set a PendingIntent template for the AdapterView's children? 696 if (mIsWidgetCollectionChild) { 697 Log.w(LOG_TAG, "Cannot setOnClickPendingIntent for collection item " + 698 "(id: " + viewId + ")"); 699 ApplicationInfo appInfo = root.getContext().getApplicationInfo(); 700 701 // We let this slide for HC and ICS so as to not break compatibility. It should have 702 // been disabled from the outset, but was left open by accident. 703 if (appInfo != null && 704 appInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 705 return; 706 } 707 } 708 709 // If the pendingIntent is null, we clear the onClickListener 710 OnClickListener listener = null; 711 if (pendingIntent != null) { 712 listener = new OnClickListener() { 713 public void onClick(View v) { 714 // Find target view location in screen coordinates and 715 // fill into PendingIntent before sending. 716 final Rect rect = getSourceBounds(v); 717 718 final Intent intent = new Intent(); 719 intent.setSourceBounds(rect); 720 handler.onClickHandler(v, pendingIntent, intent); 721 } 722 }; 723 } 724 target.setOnClickListener(listener); 725 } 726 727 public String getActionName() { 728 return "SetOnClickPendingIntent"; 729 } 730 731 PendingIntent pendingIntent; 732 733 public final static int TAG = 1; 734 } 735 736 private static Rect getSourceBounds(View v) { 737 final float appScale = v.getContext().getResources() 738 .getCompatibilityInfo().applicationScale; 739 final int[] pos = new int[2]; 740 v.getLocationOnScreen(pos); 741 742 final Rect rect = new Rect(); 743 rect.left = (int) (pos[0] * appScale + 0.5f); 744 rect.top = (int) (pos[1] * appScale + 0.5f); 745 rect.right = (int) ((pos[0] + v.getWidth()) * appScale + 0.5f); 746 rect.bottom = (int) ((pos[1] + v.getHeight()) * appScale + 0.5f); 747 return rect; 748 } 749 750 private Method getMethod(View view, String methodName, Class<?> paramType) { 751 Method method; 752 Class<? extends View> klass = view.getClass(); 753 754 synchronized (sMethodsLock) { 755 ArrayMap<MutablePair<String, Class<?>>, Method> methods = sMethods.get(klass); 756 if (methods == null) { 757 methods = new ArrayMap<MutablePair<String, Class<?>>, Method>(); 758 sMethods.put(klass, methods); 759 } 760 761 mPair.first = methodName; 762 mPair.second = paramType; 763 764 method = methods.get(mPair); 765 if (method == null) { 766 try { 767 if (paramType == null) { 768 method = klass.getMethod(methodName); 769 } else { 770 method = klass.getMethod(methodName, paramType); 771 } 772 } catch (NoSuchMethodException ex) { 773 throw new ActionException("view: " + klass.getName() + " doesn't have method: " 774 + methodName + getParameters(paramType)); 775 } 776 777 if (!method.isAnnotationPresent(RemotableViewMethod.class)) { 778 throw new ActionException("view: " + klass.getName() 779 + " can't use method with RemoteViews: " 780 + methodName + getParameters(paramType)); 781 } 782 783 methods.put(new MutablePair<String, Class<?>>(methodName, paramType), method); 784 } 785 } 786 787 return method; 788 } 789 790 private static String getParameters(Class<?> paramType) { 791 if (paramType == null) return "()"; 792 return "(" + paramType + ")"; 793 } 794 795 private static Object[] wrapArg(Object value) { 796 Object[] args = sInvokeArgsTls.get(); 797 args[0] = value; 798 return args; 799 } 800 801 /** 802 * Equivalent to calling a combination of {@link Drawable#setAlpha(int)}, 803 * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)}, 804 * and/or {@link Drawable#setLevel(int)} on the {@link Drawable} of a given view. 805 * <p> 806 * These operations will be performed on the {@link Drawable} returned by the 807 * target {@link View#getBackground()} by default. If targetBackground is false, 808 * we assume the target is an {@link ImageView} and try applying the operations 809 * to {@link ImageView#getDrawable()}. 810 * <p> 811 * You can omit specific calls by marking their values with null or -1. 812 */ 813 private class SetDrawableParameters extends Action { 814 public SetDrawableParameters(int id, boolean targetBackground, int alpha, 815 int colorFilter, PorterDuff.Mode mode, int level) { 816 this.viewId = id; 817 this.targetBackground = targetBackground; 818 this.alpha = alpha; 819 this.colorFilter = colorFilter; 820 this.filterMode = mode; 821 this.level = level; 822 } 823 824 public SetDrawableParameters(Parcel parcel) { 825 viewId = parcel.readInt(); 826 targetBackground = parcel.readInt() != 0; 827 alpha = parcel.readInt(); 828 colorFilter = parcel.readInt(); 829 boolean hasMode = parcel.readInt() != 0; 830 if (hasMode) { 831 filterMode = PorterDuff.Mode.valueOf(parcel.readString()); 832 } else { 833 filterMode = null; 834 } 835 level = parcel.readInt(); 836 } 837 838 public void writeToParcel(Parcel dest, int flags) { 839 dest.writeInt(TAG); 840 dest.writeInt(viewId); 841 dest.writeInt(targetBackground ? 1 : 0); 842 dest.writeInt(alpha); 843 dest.writeInt(colorFilter); 844 if (filterMode != null) { 845 dest.writeInt(1); 846 dest.writeString(filterMode.toString()); 847 } else { 848 dest.writeInt(0); 849 } 850 dest.writeInt(level); 851 } 852 853 @Override 854 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 855 final View target = root.findViewById(viewId); 856 if (target == null) return; 857 858 // Pick the correct drawable to modify for this view 859 Drawable targetDrawable = null; 860 if (targetBackground) { 861 targetDrawable = target.getBackground(); 862 } else if (target instanceof ImageView) { 863 ImageView imageView = (ImageView) target; 864 targetDrawable = imageView.getDrawable(); 865 } 866 867 if (targetDrawable != null) { 868 // Perform modifications only if values are set correctly 869 if (alpha != -1) { 870 targetDrawable.setAlpha(alpha); 871 } 872 if (colorFilter != -1 && filterMode != null) { 873 targetDrawable.setColorFilter(colorFilter, filterMode); 874 } 875 if (level != -1) { 876 targetDrawable.setLevel(level); 877 } 878 } 879 } 880 881 public String getActionName() { 882 return "SetDrawableParameters"; 883 } 884 885 boolean targetBackground; 886 int alpha; 887 int colorFilter; 888 PorterDuff.Mode filterMode; 889 int level; 890 891 public final static int TAG = 3; 892 } 893 894 private final class ReflectionActionWithoutParams extends Action { 895 final String methodName; 896 897 public final static int TAG = 5; 898 899 ReflectionActionWithoutParams(int viewId, String methodName) { 900 this.viewId = viewId; 901 this.methodName = methodName; 902 } 903 904 ReflectionActionWithoutParams(Parcel in) { 905 this.viewId = in.readInt(); 906 this.methodName = in.readString(); 907 } 908 909 public void writeToParcel(Parcel out, int flags) { 910 out.writeInt(TAG); 911 out.writeInt(this.viewId); 912 out.writeString(this.methodName); 913 } 914 915 @Override 916 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 917 final View view = root.findViewById(viewId); 918 if (view == null) return; 919 920 try { 921 getMethod(view, this.methodName, null).invoke(view); 922 } catch (ActionException e) { 923 throw e; 924 } catch (Exception ex) { 925 throw new ActionException(ex); 926 } 927 } 928 929 public int mergeBehavior() { 930 // we don't need to build up showNext or showPrevious calls 931 if (methodName.equals("showNext") || methodName.equals("showPrevious")) { 932 return MERGE_IGNORE; 933 } else { 934 return MERGE_REPLACE; 935 } 936 } 937 938 public String getActionName() { 939 return "ReflectionActionWithoutParams"; 940 } 941 } 942 943 private static class BitmapCache { 944 ArrayList<Bitmap> mBitmaps; 945 946 public BitmapCache() { 947 mBitmaps = new ArrayList<Bitmap>(); 948 } 949 950 public BitmapCache(Parcel source) { 951 int count = source.readInt(); 952 mBitmaps = new ArrayList<Bitmap>(); 953 for (int i = 0; i < count; i++) { 954 Bitmap b = Bitmap.CREATOR.createFromParcel(source); 955 mBitmaps.add(b); 956 } 957 } 958 959 public int getBitmapId(Bitmap b) { 960 if (b == null) { 961 return -1; 962 } else { 963 if (mBitmaps.contains(b)) { 964 return mBitmaps.indexOf(b); 965 } else { 966 mBitmaps.add(b); 967 return (mBitmaps.size() - 1); 968 } 969 } 970 } 971 972 public Bitmap getBitmapForId(int id) { 973 if (id == -1 || id >= mBitmaps.size()) { 974 return null; 975 } else { 976 return mBitmaps.get(id); 977 } 978 } 979 980 public void writeBitmapsToParcel(Parcel dest, int flags) { 981 int count = mBitmaps.size(); 982 dest.writeInt(count); 983 for (int i = 0; i < count; i++) { 984 mBitmaps.get(i).writeToParcel(dest, flags); 985 } 986 } 987 988 public void assimilate(BitmapCache bitmapCache) { 989 ArrayList<Bitmap> bitmapsToBeAdded = bitmapCache.mBitmaps; 990 int count = bitmapsToBeAdded.size(); 991 for (int i = 0; i < count; i++) { 992 Bitmap b = bitmapsToBeAdded.get(i); 993 if (!mBitmaps.contains(b)) { 994 mBitmaps.add(b); 995 } 996 } 997 } 998 999 public void addBitmapMemory(MemoryUsageCounter memoryCounter) { 1000 for (int i = 0; i < mBitmaps.size(); i++) { 1001 memoryCounter.addBitmapMemory(mBitmaps.get(i)); 1002 } 1003 } 1004 } 1005 1006 private class BitmapReflectionAction extends Action { 1007 int bitmapId; 1008 Bitmap bitmap; 1009 String methodName; 1010 1011 BitmapReflectionAction(int viewId, String methodName, Bitmap bitmap) { 1012 this.bitmap = bitmap; 1013 this.viewId = viewId; 1014 this.methodName = methodName; 1015 bitmapId = mBitmapCache.getBitmapId(bitmap); 1016 } 1017 1018 BitmapReflectionAction(Parcel in) { 1019 viewId = in.readInt(); 1020 methodName = in.readString(); 1021 bitmapId = in.readInt(); 1022 bitmap = mBitmapCache.getBitmapForId(bitmapId); 1023 } 1024 1025 @Override 1026 public void writeToParcel(Parcel dest, int flags) { 1027 dest.writeInt(TAG); 1028 dest.writeInt(viewId); 1029 dest.writeString(methodName); 1030 dest.writeInt(bitmapId); 1031 } 1032 1033 @Override 1034 public void apply(View root, ViewGroup rootParent, 1035 OnClickHandler handler) throws ActionException { 1036 ReflectionAction ra = new ReflectionAction(viewId, methodName, ReflectionAction.BITMAP, 1037 bitmap); 1038 ra.apply(root, rootParent, handler); 1039 } 1040 1041 @Override 1042 public void setBitmapCache(BitmapCache bitmapCache) { 1043 bitmapId = bitmapCache.getBitmapId(bitmap); 1044 } 1045 1046 public String getActionName() { 1047 return "BitmapReflectionAction"; 1048 } 1049 1050 public final static int TAG = 12; 1051 } 1052 1053 /** 1054 * Base class for the reflection actions. 1055 */ 1056 private final class ReflectionAction extends Action { 1057 static final int TAG = 2; 1058 1059 static final int BOOLEAN = 1; 1060 static final int BYTE = 2; 1061 static final int SHORT = 3; 1062 static final int INT = 4; 1063 static final int LONG = 5; 1064 static final int FLOAT = 6; 1065 static final int DOUBLE = 7; 1066 static final int CHAR = 8; 1067 static final int STRING = 9; 1068 static final int CHAR_SEQUENCE = 10; 1069 static final int URI = 11; 1070 // BITMAP actions are never stored in the list of actions. They are only used locally 1071 // to implement BitmapReflectionAction, which eliminates duplicates using BitmapCache. 1072 static final int BITMAP = 12; 1073 static final int BUNDLE = 13; 1074 static final int INTENT = 14; 1075 1076 String methodName; 1077 int type; 1078 Object value; 1079 1080 ReflectionAction(int viewId, String methodName, int type, Object value) { 1081 this.viewId = viewId; 1082 this.methodName = methodName; 1083 this.type = type; 1084 this.value = value; 1085 } 1086 1087 ReflectionAction(Parcel in) { 1088 this.viewId = in.readInt(); 1089 this.methodName = in.readString(); 1090 this.type = in.readInt(); 1091 //noinspection ConstantIfStatement 1092 if (false) { 1093 Log.d(LOG_TAG, "read viewId=0x" + Integer.toHexString(this.viewId) 1094 + " methodName=" + this.methodName + " type=" + this.type); 1095 } 1096 1097 // For some values that may have been null, we first check a flag to see if they were 1098 // written to the parcel. 1099 switch (this.type) { 1100 case BOOLEAN: 1101 this.value = in.readInt() != 0; 1102 break; 1103 case BYTE: 1104 this.value = in.readByte(); 1105 break; 1106 case SHORT: 1107 this.value = (short)in.readInt(); 1108 break; 1109 case INT: 1110 this.value = in.readInt(); 1111 break; 1112 case LONG: 1113 this.value = in.readLong(); 1114 break; 1115 case FLOAT: 1116 this.value = in.readFloat(); 1117 break; 1118 case DOUBLE: 1119 this.value = in.readDouble(); 1120 break; 1121 case CHAR: 1122 this.value = (char)in.readInt(); 1123 break; 1124 case STRING: 1125 this.value = in.readString(); 1126 break; 1127 case CHAR_SEQUENCE: 1128 this.value = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 1129 break; 1130 case URI: 1131 if (in.readInt() != 0) { 1132 this.value = Uri.CREATOR.createFromParcel(in); 1133 } 1134 break; 1135 case BITMAP: 1136 if (in.readInt() != 0) { 1137 this.value = Bitmap.CREATOR.createFromParcel(in); 1138 } 1139 break; 1140 case BUNDLE: 1141 this.value = in.readBundle(); 1142 break; 1143 case INTENT: 1144 if (in.readInt() != 0) { 1145 this.value = Intent.CREATOR.createFromParcel(in); 1146 } 1147 break; 1148 default: 1149 break; 1150 } 1151 } 1152 1153 public void writeToParcel(Parcel out, int flags) { 1154 out.writeInt(TAG); 1155 out.writeInt(this.viewId); 1156 out.writeString(this.methodName); 1157 out.writeInt(this.type); 1158 //noinspection ConstantIfStatement 1159 if (false) { 1160 Log.d(LOG_TAG, "write viewId=0x" + Integer.toHexString(this.viewId) 1161 + " methodName=" + this.methodName + " type=" + this.type); 1162 } 1163 1164 // For some values which are null, we record an integer flag to indicate whether 1165 // we have written a valid value to the parcel. 1166 switch (this.type) { 1167 case BOOLEAN: 1168 out.writeInt((Boolean) this.value ? 1 : 0); 1169 break; 1170 case BYTE: 1171 out.writeByte((Byte) this.value); 1172 break; 1173 case SHORT: 1174 out.writeInt((Short) this.value); 1175 break; 1176 case INT: 1177 out.writeInt((Integer) this.value); 1178 break; 1179 case LONG: 1180 out.writeLong((Long) this.value); 1181 break; 1182 case FLOAT: 1183 out.writeFloat((Float) this.value); 1184 break; 1185 case DOUBLE: 1186 out.writeDouble((Double) this.value); 1187 break; 1188 case CHAR: 1189 out.writeInt((int)((Character)this.value).charValue()); 1190 break; 1191 case STRING: 1192 out.writeString((String)this.value); 1193 break; 1194 case CHAR_SEQUENCE: 1195 TextUtils.writeToParcel((CharSequence)this.value, out, flags); 1196 break; 1197 case URI: 1198 out.writeInt(this.value != null ? 1 : 0); 1199 if (this.value != null) { 1200 ((Uri)this.value).writeToParcel(out, flags); 1201 } 1202 break; 1203 case BITMAP: 1204 out.writeInt(this.value != null ? 1 : 0); 1205 if (this.value != null) { 1206 ((Bitmap)this.value).writeToParcel(out, flags); 1207 } 1208 break; 1209 case BUNDLE: 1210 out.writeBundle((Bundle) this.value); 1211 break; 1212 case INTENT: 1213 out.writeInt(this.value != null ? 1 : 0); 1214 if (this.value != null) { 1215 ((Intent)this.value).writeToParcel(out, flags); 1216 } 1217 break; 1218 default: 1219 break; 1220 } 1221 } 1222 1223 private Class<?> getParameterType() { 1224 switch (this.type) { 1225 case BOOLEAN: 1226 return boolean.class; 1227 case BYTE: 1228 return byte.class; 1229 case SHORT: 1230 return short.class; 1231 case INT: 1232 return int.class; 1233 case LONG: 1234 return long.class; 1235 case FLOAT: 1236 return float.class; 1237 case DOUBLE: 1238 return double.class; 1239 case CHAR: 1240 return char.class; 1241 case STRING: 1242 return String.class; 1243 case CHAR_SEQUENCE: 1244 return CharSequence.class; 1245 case URI: 1246 return Uri.class; 1247 case BITMAP: 1248 return Bitmap.class; 1249 case BUNDLE: 1250 return Bundle.class; 1251 case INTENT: 1252 return Intent.class; 1253 default: 1254 return null; 1255 } 1256 } 1257 1258 @Override 1259 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 1260 final View view = root.findViewById(viewId); 1261 if (view == null) return; 1262 1263 Class<?> param = getParameterType(); 1264 if (param == null) { 1265 throw new ActionException("bad type: " + this.type); 1266 } 1267 1268 try { 1269 getMethod(view, this.methodName, param).invoke(view, wrapArg(this.value)); 1270 } catch (ActionException e) { 1271 throw e; 1272 } catch (Exception ex) { 1273 throw new ActionException(ex); 1274 } 1275 } 1276 1277 public int mergeBehavior() { 1278 // smoothScrollBy is cumulative, everything else overwites. 1279 if (methodName.equals("smoothScrollBy")) { 1280 return MERGE_APPEND; 1281 } else { 1282 return MERGE_REPLACE; 1283 } 1284 } 1285 1286 public String getActionName() { 1287 // Each type of reflection action corresponds to a setter, so each should be seen as 1288 // unique from the standpoint of merging. 1289 return "ReflectionAction" + this.methodName + this.type; 1290 } 1291 } 1292 1293 private void configureRemoteViewsAsChild(RemoteViews rv) { 1294 mBitmapCache.assimilate(rv.mBitmapCache); 1295 rv.setBitmapCache(mBitmapCache); 1296 rv.setNotRoot(); 1297 } 1298 1299 void setNotRoot() { 1300 mIsRoot = false; 1301 } 1302 1303 /** 1304 * Equivalent to calling {@link ViewGroup#addView(View)} after inflating the 1305 * given {@link RemoteViews}, or calling {@link ViewGroup#removeAllViews()} 1306 * when null. This allows users to build "nested" {@link RemoteViews}. 1307 */ 1308 private class ViewGroupAction extends Action { 1309 public ViewGroupAction(int viewId, RemoteViews nestedViews) { 1310 this.viewId = viewId; 1311 this.nestedViews = nestedViews; 1312 if (nestedViews != null) { 1313 configureRemoteViewsAsChild(nestedViews); 1314 } 1315 } 1316 1317 public ViewGroupAction(Parcel parcel, BitmapCache bitmapCache) { 1318 viewId = parcel.readInt(); 1319 boolean nestedViewsNull = parcel.readInt() == 0; 1320 if (!nestedViewsNull) { 1321 nestedViews = new RemoteViews(parcel, bitmapCache); 1322 } else { 1323 nestedViews = null; 1324 } 1325 } 1326 1327 public void writeToParcel(Parcel dest, int flags) { 1328 dest.writeInt(TAG); 1329 dest.writeInt(viewId); 1330 if (nestedViews != null) { 1331 dest.writeInt(1); 1332 nestedViews.writeToParcel(dest, flags); 1333 } else { 1334 // signifies null 1335 dest.writeInt(0); 1336 } 1337 } 1338 1339 @Override 1340 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 1341 final Context context = root.getContext(); 1342 final ViewGroup target = (ViewGroup) root.findViewById(viewId); 1343 if (target == null) return; 1344 if (nestedViews != null) { 1345 // Inflate nested views and add as children 1346 target.addView(nestedViews.apply(context, target, handler)); 1347 } else { 1348 // Clear all children when nested views omitted 1349 target.removeAllViews(); 1350 } 1351 } 1352 1353 @Override 1354 public void updateMemoryUsageEstimate(MemoryUsageCounter counter) { 1355 if (nestedViews != null) { 1356 counter.increment(nestedViews.estimateMemoryUsage()); 1357 } 1358 } 1359 1360 @Override 1361 public void setBitmapCache(BitmapCache bitmapCache) { 1362 if (nestedViews != null) { 1363 nestedViews.setBitmapCache(bitmapCache); 1364 } 1365 } 1366 1367 public String getActionName() { 1368 return "ViewGroupAction" + (nestedViews == null ? "Remove" : "Add"); 1369 } 1370 1371 public int mergeBehavior() { 1372 return MERGE_APPEND; 1373 } 1374 1375 RemoteViews nestedViews; 1376 1377 public final static int TAG = 4; 1378 } 1379 1380 /** 1381 * Helper action to set compound drawables on a TextView. Supports relative 1382 * (s/t/e/b) or cardinal (l/t/r/b) arrangement. 1383 */ 1384 private class TextViewDrawableAction extends Action { 1385 public TextViewDrawableAction(int viewId, boolean isRelative, int d1, int d2, int d3, int d4) { 1386 this.viewId = viewId; 1387 this.isRelative = isRelative; 1388 this.d1 = d1; 1389 this.d2 = d2; 1390 this.d3 = d3; 1391 this.d4 = d4; 1392 } 1393 1394 public TextViewDrawableAction(Parcel parcel) { 1395 viewId = parcel.readInt(); 1396 isRelative = (parcel.readInt() != 0); 1397 d1 = parcel.readInt(); 1398 d2 = parcel.readInt(); 1399 d3 = parcel.readInt(); 1400 d4 = parcel.readInt(); 1401 } 1402 1403 public void writeToParcel(Parcel dest, int flags) { 1404 dest.writeInt(TAG); 1405 dest.writeInt(viewId); 1406 dest.writeInt(isRelative ? 1 : 0); 1407 dest.writeInt(d1); 1408 dest.writeInt(d2); 1409 dest.writeInt(d3); 1410 dest.writeInt(d4); 1411 } 1412 1413 @Override 1414 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 1415 final TextView target = (TextView) root.findViewById(viewId); 1416 if (target == null) return; 1417 if (isRelative) { 1418 target.setCompoundDrawablesRelativeWithIntrinsicBounds(d1, d2, d3, d4); 1419 } else { 1420 target.setCompoundDrawablesWithIntrinsicBounds(d1, d2, d3, d4); 1421 } 1422 } 1423 1424 public String getActionName() { 1425 return "TextViewDrawableAction"; 1426 } 1427 1428 boolean isRelative = false; 1429 int d1, d2, d3, d4; 1430 1431 public final static int TAG = 11; 1432 } 1433 1434 /** 1435 * Helper action to set text size on a TextView in any supported units. 1436 */ 1437 private class TextViewSizeAction extends Action { 1438 public TextViewSizeAction(int viewId, int units, float size) { 1439 this.viewId = viewId; 1440 this.units = units; 1441 this.size = size; 1442 } 1443 1444 public TextViewSizeAction(Parcel parcel) { 1445 viewId = parcel.readInt(); 1446 units = parcel.readInt(); 1447 size = parcel.readFloat(); 1448 } 1449 1450 public void writeToParcel(Parcel dest, int flags) { 1451 dest.writeInt(TAG); 1452 dest.writeInt(viewId); 1453 dest.writeInt(units); 1454 dest.writeFloat(size); 1455 } 1456 1457 @Override 1458 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 1459 final TextView target = (TextView) root.findViewById(viewId); 1460 if (target == null) return; 1461 target.setTextSize(units, size); 1462 } 1463 1464 public String getActionName() { 1465 return "TextViewSizeAction"; 1466 } 1467 1468 int units; 1469 float size; 1470 1471 public final static int TAG = 13; 1472 } 1473 1474 /** 1475 * Helper action to set padding on a View. 1476 */ 1477 private class ViewPaddingAction extends Action { 1478 public ViewPaddingAction(int viewId, int left, int top, int right, int bottom) { 1479 this.viewId = viewId; 1480 this.left = left; 1481 this.top = top; 1482 this.right = right; 1483 this.bottom = bottom; 1484 } 1485 1486 public ViewPaddingAction(Parcel parcel) { 1487 viewId = parcel.readInt(); 1488 left = parcel.readInt(); 1489 top = parcel.readInt(); 1490 right = parcel.readInt(); 1491 bottom = parcel.readInt(); 1492 } 1493 1494 public void writeToParcel(Parcel dest, int flags) { 1495 dest.writeInt(TAG); 1496 dest.writeInt(viewId); 1497 dest.writeInt(left); 1498 dest.writeInt(top); 1499 dest.writeInt(right); 1500 dest.writeInt(bottom); 1501 } 1502 1503 @Override 1504 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 1505 final View target = root.findViewById(viewId); 1506 if (target == null) return; 1507 target.setPadding(left, top, right, bottom); 1508 } 1509 1510 public String getActionName() { 1511 return "ViewPaddingAction"; 1512 } 1513 1514 int left, top, right, bottom; 1515 1516 public final static int TAG = 14; 1517 } 1518 1519 /** 1520 * Helper action to set a color filter on a compound drawable on a TextView. Supports relative 1521 * (s/t/e/b) or cardinal (l/t/r/b) arrangement. 1522 */ 1523 private class TextViewDrawableColorFilterAction extends Action { 1524 public TextViewDrawableColorFilterAction(int viewId, boolean isRelative, int index, 1525 int color, PorterDuff.Mode mode) { 1526 this.viewId = viewId; 1527 this.isRelative = isRelative; 1528 this.index = index; 1529 this.color = color; 1530 this.mode = mode; 1531 } 1532 1533 public TextViewDrawableColorFilterAction(Parcel parcel) { 1534 viewId = parcel.readInt(); 1535 isRelative = (parcel.readInt() != 0); 1536 index = parcel.readInt(); 1537 color = parcel.readInt(); 1538 mode = readPorterDuffMode(parcel); 1539 } 1540 1541 private PorterDuff.Mode readPorterDuffMode(Parcel parcel) { 1542 int mode = parcel.readInt(); 1543 if (mode >= 0 && mode < PorterDuff.Mode.values().length) { 1544 return PorterDuff.Mode.values()[mode]; 1545 } else { 1546 return PorterDuff.Mode.CLEAR; 1547 } 1548 } 1549 1550 public void writeToParcel(Parcel dest, int flags) { 1551 dest.writeInt(TAG); 1552 dest.writeInt(viewId); 1553 dest.writeInt(isRelative ? 1 : 0); 1554 dest.writeInt(index); 1555 dest.writeInt(color); 1556 dest.writeInt(mode.ordinal()); 1557 } 1558 1559 @Override 1560 public void apply(View root, ViewGroup rootParent, OnClickHandler handler) { 1561 final TextView target = (TextView) root.findViewById(viewId); 1562 if (target == null) return; 1563 Drawable[] drawables = isRelative 1564 ? target.getCompoundDrawablesRelative() 1565 : target.getCompoundDrawables(); 1566 if (index < 0 || index >= 4) { 1567 throw new IllegalStateException("index must be in range [0, 3]."); 1568 } 1569 Drawable d = drawables[index]; 1570 if (d != null) { 1571 d.mutate(); 1572 d.setColorFilter(color, mode); 1573 } 1574 } 1575 1576 public String getActionName() { 1577 return "TextViewDrawableColorFilterAction"; 1578 } 1579 1580 final boolean isRelative; 1581 final int index; 1582 final int color; 1583 final PorterDuff.Mode mode; 1584 1585 public final static int TAG = 17; 1586 } 1587 1588 /** 1589 * Simple class used to keep track of memory usage in a RemoteViews. 1590 * 1591 */ 1592 private class MemoryUsageCounter { 1593 public void clear() { 1594 mMemoryUsage = 0; 1595 } 1596 1597 public void increment(int numBytes) { 1598 mMemoryUsage += numBytes; 1599 } 1600 1601 public int getMemoryUsage() { 1602 return mMemoryUsage; 1603 } 1604 1605 @SuppressWarnings("deprecation") 1606 public void addBitmapMemory(Bitmap b) { 1607 final Bitmap.Config c = b.getConfig(); 1608 // If we don't know, be pessimistic and assume 4 1609 int bpp = 4; 1610 if (c != null) { 1611 switch (c) { 1612 case ALPHA_8: 1613 bpp = 1; 1614 break; 1615 case RGB_565: 1616 case ARGB_4444: 1617 bpp = 2; 1618 break; 1619 case ARGB_8888: 1620 bpp = 4; 1621 break; 1622 } 1623 } 1624 increment(b.getWidth() * b.getHeight() * bpp); 1625 } 1626 1627 int mMemoryUsage; 1628 } 1629 1630 /** 1631 * Create a new RemoteViews object that will display the views contained 1632 * in the specified layout file. 1633 * 1634 * @param packageName Name of the package that contains the layout resource 1635 * @param layoutId The id of the layout resource 1636 */ 1637 public RemoteViews(String packageName, int layoutId) { 1638 mPackage = packageName; 1639 mLayoutId = layoutId; 1640 mBitmapCache = new BitmapCache(); 1641 mApplication = ActivityThread.currentApplication().getApplicationInfo(); 1642 1643 // setup the memory usage statistics 1644 mMemoryUsageCounter = new MemoryUsageCounter(); 1645 recalculateMemoryUsage(); 1646 } 1647 1648 private boolean hasLandscapeAndPortraitLayouts() { 1649 return (mLandscape != null) && (mPortrait != null); 1650 } 1651 1652 /** 1653 * Create a new RemoteViews object that will inflate as the specified 1654 * landspace or portrait RemoteViews, depending on the current configuration. 1655 * 1656 * @param landscape The RemoteViews to inflate in landscape configuration 1657 * @param portrait The RemoteViews to inflate in portrait configuration 1658 */ 1659 public RemoteViews(RemoteViews landscape, RemoteViews portrait) { 1660 if (landscape == null || portrait == null) { 1661 throw new RuntimeException("Both RemoteViews must be non-null"); 1662 } 1663 if (landscape.getPackage().compareTo(portrait.getPackage()) != 0) { 1664 throw new RuntimeException("Both RemoteViews must share the same package"); 1665 } 1666 mPackage = portrait.getPackage(); 1667 mLayoutId = portrait.getLayoutId(); 1668 1669 mLandscape = landscape; 1670 mPortrait = portrait; 1671 1672 // setup the memory usage statistics 1673 mMemoryUsageCounter = new MemoryUsageCounter(); 1674 1675 mBitmapCache = new BitmapCache(); 1676 configureRemoteViewsAsChild(landscape); 1677 configureRemoteViewsAsChild(portrait); 1678 1679 recalculateMemoryUsage(); 1680 } 1681 1682 /** 1683 * Reads a RemoteViews object from a parcel. 1684 * 1685 * @param parcel 1686 */ 1687 public RemoteViews(Parcel parcel) { 1688 this(parcel, null); 1689 } 1690 1691 private RemoteViews(Parcel parcel, BitmapCache bitmapCache) { 1692 int mode = parcel.readInt(); 1693 1694 // We only store a bitmap cache in the root of the RemoteViews. 1695 if (bitmapCache == null) { 1696 mBitmapCache = new BitmapCache(parcel); 1697 } else { 1698 setBitmapCache(bitmapCache); 1699 setNotRoot(); 1700 } 1701 1702 if (mode == MODE_NORMAL) { 1703 mPackage = parcel.readString(); 1704 mLayoutId = parcel.readInt(); 1705 mIsWidgetCollectionChild = parcel.readInt() == 1; 1706 1707 int count = parcel.readInt(); 1708 if (count > 0) { 1709 mActions = new ArrayList<Action>(count); 1710 for (int i=0; i<count; i++) { 1711 int tag = parcel.readInt(); 1712 switch (tag) { 1713 case SetOnClickPendingIntent.TAG: 1714 mActions.add(new SetOnClickPendingIntent(parcel)); 1715 break; 1716 case SetDrawableParameters.TAG: 1717 mActions.add(new SetDrawableParameters(parcel)); 1718 break; 1719 case ReflectionAction.TAG: 1720 mActions.add(new ReflectionAction(parcel)); 1721 break; 1722 case ViewGroupAction.TAG: 1723 mActions.add(new ViewGroupAction(parcel, mBitmapCache)); 1724 break; 1725 case ReflectionActionWithoutParams.TAG: 1726 mActions.add(new ReflectionActionWithoutParams(parcel)); 1727 break; 1728 case SetEmptyView.TAG: 1729 mActions.add(new SetEmptyView(parcel)); 1730 break; 1731 case SetPendingIntentTemplate.TAG: 1732 mActions.add(new SetPendingIntentTemplate(parcel)); 1733 break; 1734 case SetOnClickFillInIntent.TAG: 1735 mActions.add(new SetOnClickFillInIntent(parcel)); 1736 break; 1737 case SetRemoteViewsAdapterIntent.TAG: 1738 mActions.add(new SetRemoteViewsAdapterIntent(parcel)); 1739 break; 1740 case TextViewDrawableAction.TAG: 1741 mActions.add(new TextViewDrawableAction(parcel)); 1742 break; 1743 case TextViewSizeAction.TAG: 1744 mActions.add(new TextViewSizeAction(parcel)); 1745 break; 1746 case ViewPaddingAction.TAG: 1747 mActions.add(new ViewPaddingAction(parcel)); 1748 break; 1749 case BitmapReflectionAction.TAG: 1750 mActions.add(new BitmapReflectionAction(parcel)); 1751 break; 1752 case SetRemoteViewsAdapterList.TAG: 1753 mActions.add(new SetRemoteViewsAdapterList(parcel)); 1754 break; 1755 case TextViewDrawableColorFilterAction.TAG: 1756 mActions.add(new TextViewDrawableColorFilterAction(parcel)); 1757 break; 1758 default: 1759 throw new ActionException("Tag " + tag + " not found"); 1760 } 1761 } 1762 } 1763 } else { 1764 // MODE_HAS_LANDSCAPE_AND_PORTRAIT 1765 mLandscape = new RemoteViews(parcel, mBitmapCache); 1766 mPortrait = new RemoteViews(parcel, mBitmapCache); 1767 mPackage = mPortrait.getPackage(); 1768 mLayoutId = mPortrait.getLayoutId(); 1769 } 1770 1771 mApplication = parcel.readParcelable(null); 1772 1773 // setup the memory usage statistics 1774 mMemoryUsageCounter = new MemoryUsageCounter(); 1775 recalculateMemoryUsage(); 1776 } 1777 1778 1779 public RemoteViews clone() { 1780 Parcel p = Parcel.obtain(); 1781 writeToParcel(p, 0); 1782 p.setDataPosition(0); 1783 RemoteViews rv = new RemoteViews(p); 1784 p.recycle(); 1785 return rv; 1786 } 1787 1788 public String getPackage() { 1789 return mPackage; 1790 } 1791 1792 /** 1793 * Reutrns the layout id of the root layout associated with this RemoteViews. In the case 1794 * that the RemoteViews has both a landscape and portrait root, this will return the layout 1795 * id associated with the portrait layout. 1796 * 1797 * @return the layout id. 1798 */ 1799 public int getLayoutId() { 1800 return mLayoutId; 1801 } 1802 1803 /* 1804 * This flag indicates whether this RemoteViews object is being created from a 1805 * RemoteViewsService for use as a child of a widget collection. This flag is used 1806 * to determine whether or not certain features are available, in particular, 1807 * setting on click extras and setting on click pending intents. The former is enabled, 1808 * and the latter disabled when this flag is true. 1809 */ 1810 void setIsWidgetCollectionChild(boolean isWidgetCollectionChild) { 1811 mIsWidgetCollectionChild = isWidgetCollectionChild; 1812 } 1813 1814 /** 1815 * Updates the memory usage statistics. 1816 */ 1817 private void recalculateMemoryUsage() { 1818 mMemoryUsageCounter.clear(); 1819 1820 if (!hasLandscapeAndPortraitLayouts()) { 1821 // Accumulate the memory usage for each action 1822 if (mActions != null) { 1823 final int count = mActions.size(); 1824 for (int i= 0; i < count; ++i) { 1825 mActions.get(i).updateMemoryUsageEstimate(mMemoryUsageCounter); 1826 } 1827 } 1828 if (mIsRoot) { 1829 mBitmapCache.addBitmapMemory(mMemoryUsageCounter); 1830 } 1831 } else { 1832 mMemoryUsageCounter.increment(mLandscape.estimateMemoryUsage()); 1833 mMemoryUsageCounter.increment(mPortrait.estimateMemoryUsage()); 1834 mBitmapCache.addBitmapMemory(mMemoryUsageCounter); 1835 } 1836 } 1837 1838 /** 1839 * Recursively sets BitmapCache in the hierarchy and update the bitmap ids. 1840 */ 1841 private void setBitmapCache(BitmapCache bitmapCache) { 1842 mBitmapCache = bitmapCache; 1843 if (!hasLandscapeAndPortraitLayouts()) { 1844 if (mActions != null) { 1845 final int count = mActions.size(); 1846 for (int i= 0; i < count; ++i) { 1847 mActions.get(i).setBitmapCache(bitmapCache); 1848 } 1849 } 1850 } else { 1851 mLandscape.setBitmapCache(bitmapCache); 1852 mPortrait.setBitmapCache(bitmapCache); 1853 } 1854 } 1855 1856 /** 1857 * Returns an estimate of the bitmap heap memory usage for this RemoteViews. 1858 */ 1859 /** @hide */ 1860 public int estimateMemoryUsage() { 1861 return mMemoryUsageCounter.getMemoryUsage(); 1862 } 1863 1864 /** 1865 * Add an action to be executed on the remote side when apply is called. 1866 * 1867 * @param a The action to add 1868 */ 1869 private void addAction(Action a) { 1870 if (hasLandscapeAndPortraitLayouts()) { 1871 throw new RuntimeException("RemoteViews specifying separate landscape and portrait" + 1872 " layouts cannot be modified. Instead, fully configure the landscape and" + 1873 " portrait layouts individually before constructing the combined layout."); 1874 } 1875 if (mActions == null) { 1876 mActions = new ArrayList<Action>(); 1877 } 1878 mActions.add(a); 1879 1880 // update the memory usage stats 1881 a.updateMemoryUsageEstimate(mMemoryUsageCounter); 1882 } 1883 1884 /** 1885 * Equivalent to calling {@link ViewGroup#addView(View)} after inflating the 1886 * given {@link RemoteViews}. This allows users to build "nested" 1887 * {@link RemoteViews}. In cases where consumers of {@link RemoteViews} may 1888 * recycle layouts, use {@link #removeAllViews(int)} to clear any existing 1889 * children. 1890 * 1891 * @param viewId The id of the parent {@link ViewGroup} to add child into. 1892 * @param nestedView {@link RemoteViews} that describes the child. 1893 */ 1894 public void addView(int viewId, RemoteViews nestedView) { 1895 addAction(new ViewGroupAction(viewId, nestedView)); 1896 } 1897 1898 /** 1899 * Equivalent to calling {@link ViewGroup#removeAllViews()}. 1900 * 1901 * @param viewId The id of the parent {@link ViewGroup} to remove all 1902 * children from. 1903 */ 1904 public void removeAllViews(int viewId) { 1905 addAction(new ViewGroupAction(viewId, null)); 1906 } 1907 1908 /** 1909 * Equivalent to calling {@link AdapterViewAnimator#showNext()} 1910 * 1911 * @param viewId The id of the view on which to call {@link AdapterViewAnimator#showNext()} 1912 */ 1913 public void showNext(int viewId) { 1914 addAction(new ReflectionActionWithoutParams(viewId, "showNext")); 1915 } 1916 1917 /** 1918 * Equivalent to calling {@link AdapterViewAnimator#showPrevious()} 1919 * 1920 * @param viewId The id of the view on which to call {@link AdapterViewAnimator#showPrevious()} 1921 */ 1922 public void showPrevious(int viewId) { 1923 addAction(new ReflectionActionWithoutParams(viewId, "showPrevious")); 1924 } 1925 1926 /** 1927 * Equivalent to calling {@link AdapterViewAnimator#setDisplayedChild(int)} 1928 * 1929 * @param viewId The id of the view on which to call 1930 * {@link AdapterViewAnimator#setDisplayedChild(int)} 1931 */ 1932 public void setDisplayedChild(int viewId, int childIndex) { 1933 setInt(viewId, "setDisplayedChild", childIndex); 1934 } 1935 1936 /** 1937 * Equivalent to calling View.setVisibility 1938 * 1939 * @param viewId The id of the view whose visibility should change 1940 * @param visibility The new visibility for the view 1941 */ 1942 public void setViewVisibility(int viewId, int visibility) { 1943 setInt(viewId, "setVisibility", visibility); 1944 } 1945 1946 /** 1947 * Equivalent to calling TextView.setText 1948 * 1949 * @param viewId The id of the view whose text should change 1950 * @param text The new text for the view 1951 */ 1952 public void setTextViewText(int viewId, CharSequence text) { 1953 setCharSequence(viewId, "setText", text); 1954 } 1955 1956 /** 1957 * Equivalent to calling {@link TextView#setTextSize(int, float)} 1958 * 1959 * @param viewId The id of the view whose text size should change 1960 * @param units The units of size (e.g. COMPLEX_UNIT_SP) 1961 * @param size The size of the text 1962 */ 1963 public void setTextViewTextSize(int viewId, int units, float size) { 1964 addAction(new TextViewSizeAction(viewId, units, size)); 1965 } 1966 1967 /** 1968 * Equivalent to calling 1969 * {@link TextView#setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)}. 1970 * 1971 * @param viewId The id of the view whose text should change 1972 * @param left The id of a drawable to place to the left of the text, or 0 1973 * @param top The id of a drawable to place above the text, or 0 1974 * @param right The id of a drawable to place to the right of the text, or 0 1975 * @param bottom The id of a drawable to place below the text, or 0 1976 */ 1977 public void setTextViewCompoundDrawables(int viewId, int left, int top, int right, int bottom) { 1978 addAction(new TextViewDrawableAction(viewId, false, left, top, right, bottom)); 1979 } 1980 1981 /** 1982 * Equivalent to calling {@link 1983 * TextView#setCompoundDrawablesRelativeWithIntrinsicBounds(int, int, int, int)}. 1984 * 1985 * @param viewId The id of the view whose text should change 1986 * @param start The id of a drawable to place before the text (relative to the 1987 * layout direction), or 0 1988 * @param top The id of a drawable to place above the text, or 0 1989 * @param end The id of a drawable to place after the text, or 0 1990 * @param bottom The id of a drawable to place below the text, or 0 1991 */ 1992 public void setTextViewCompoundDrawablesRelative(int viewId, int start, int top, int end, int bottom) { 1993 addAction(new TextViewDrawableAction(viewId, true, start, top, end, bottom)); 1994 } 1995 1996 /** 1997 * Equivalent to applying a color filter on one of the drawables in 1998 * {@link android.widget.TextView#getCompoundDrawablesRelative()}. 1999 * 2000 * @param viewId The id of the view whose text should change. 2001 * @param index The index of the drawable in the array of 2002 * {@link android.widget.TextView#getCompoundDrawablesRelative()} to set the color 2003 * filter on. Must be in [0, 3]. 2004 * @param color The color of the color filter. See 2005 * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)}. 2006 * @param mode The mode of the color filter. See 2007 * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)}. 2008 * @hide 2009 */ 2010 public void setTextViewCompoundDrawablesRelativeColorFilter(int viewId, 2011 int index, int color, PorterDuff.Mode mode) { 2012 if (index < 0 || index >= 4) { 2013 throw new IllegalArgumentException("index must be in range [0, 3]."); 2014 } 2015 addAction(new TextViewDrawableColorFilterAction(viewId, true, index, color, mode)); 2016 } 2017 2018 /** 2019 * Equivalent to calling ImageView.setImageResource 2020 * 2021 * @param viewId The id of the view whose drawable should change 2022 * @param srcId The new resource id for the drawable 2023 */ 2024 public void setImageViewResource(int viewId, int srcId) { 2025 setInt(viewId, "setImageResource", srcId); 2026 } 2027 2028 /** 2029 * Equivalent to calling ImageView.setImageURI 2030 * 2031 * @param viewId The id of the view whose drawable should change 2032 * @param uri The Uri for the image 2033 */ 2034 public void setImageViewUri(int viewId, Uri uri) { 2035 setUri(viewId, "setImageURI", uri); 2036 } 2037 2038 /** 2039 * Equivalent to calling ImageView.setImageBitmap 2040 * 2041 * @param viewId The id of the view whose bitmap should change 2042 * @param bitmap The new Bitmap for the drawable 2043 */ 2044 public void setImageViewBitmap(int viewId, Bitmap bitmap) { 2045 setBitmap(viewId, "setImageBitmap", bitmap); 2046 } 2047 2048 /** 2049 * Equivalent to calling AdapterView.setEmptyView 2050 * 2051 * @param viewId The id of the view on which to set the empty view 2052 * @param emptyViewId The view id of the empty view 2053 */ 2054 public void setEmptyView(int viewId, int emptyViewId) { 2055 addAction(new SetEmptyView(viewId, emptyViewId)); 2056 } 2057 2058 /** 2059 * Equivalent to calling {@link Chronometer#setBase Chronometer.setBase}, 2060 * {@link Chronometer#setFormat Chronometer.setFormat}, 2061 * and {@link Chronometer#start Chronometer.start()} or 2062 * {@link Chronometer#stop Chronometer.stop()}. 2063 * 2064 * @param viewId The id of the {@link Chronometer} to change 2065 * @param base The time at which the timer would have read 0:00. This 2066 * time should be based off of 2067 * {@link android.os.SystemClock#elapsedRealtime SystemClock.elapsedRealtime()}. 2068 * @param format The Chronometer format string, or null to 2069 * simply display the timer value. 2070 * @param started True if you want the clock to be started, false if not. 2071 */ 2072 public void setChronometer(int viewId, long base, String format, boolean started) { 2073 setLong(viewId, "setBase", base); 2074 setString(viewId, "setFormat", format); 2075 setBoolean(viewId, "setStarted", started); 2076 } 2077 2078 /** 2079 * Equivalent to calling {@link ProgressBar#setMax ProgressBar.setMax}, 2080 * {@link ProgressBar#setProgress ProgressBar.setProgress}, and 2081 * {@link ProgressBar#setIndeterminate ProgressBar.setIndeterminate} 2082 * 2083 * If indeterminate is true, then the values for max and progress are ignored. 2084 * 2085 * @param viewId The id of the {@link ProgressBar} to change 2086 * @param max The 100% value for the progress bar 2087 * @param progress The current value of the progress bar. 2088 * @param indeterminate True if the progress bar is indeterminate, 2089 * false if not. 2090 */ 2091 public void setProgressBar(int viewId, int max, int progress, 2092 boolean indeterminate) { 2093 setBoolean(viewId, "setIndeterminate", indeterminate); 2094 if (!indeterminate) { 2095 setInt(viewId, "setMax", max); 2096 setInt(viewId, "setProgress", progress); 2097 } 2098 } 2099 2100 /** 2101 * Equivalent to calling 2102 * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)} 2103 * to launch the provided {@link PendingIntent}. 2104 * 2105 * When setting the on-click action of items within collections (eg. {@link ListView}, 2106 * {@link StackView} etc.), this method will not work. Instead, use {@link 2107 * RemoteViews#setPendingIntentTemplate(int, PendingIntent) in conjunction with 2108 * RemoteViews#setOnClickFillInIntent(int, Intent). 2109 * 2110 * @param viewId The id of the view that will trigger the {@link PendingIntent} when clicked 2111 * @param pendingIntent The {@link PendingIntent} to send when user clicks 2112 */ 2113 public void setOnClickPendingIntent(int viewId, PendingIntent pendingIntent) { 2114 addAction(new SetOnClickPendingIntent(viewId, pendingIntent)); 2115 } 2116 2117 /** 2118 * When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is very 2119 * costly to set PendingIntents on the individual items, and is hence not permitted. Instead 2120 * this method should be used to set a single PendingIntent template on the collection, and 2121 * individual items can differentiate their on-click behavior using 2122 * {@link RemoteViews#setOnClickFillInIntent(int, Intent)}. 2123 * 2124 * @param viewId The id of the collection who's children will use this PendingIntent template 2125 * when clicked 2126 * @param pendingIntentTemplate The {@link PendingIntent} to be combined with extras specified 2127 * by a child of viewId and executed when that child is clicked 2128 */ 2129 public void setPendingIntentTemplate(int viewId, PendingIntent pendingIntentTemplate) { 2130 addAction(new SetPendingIntentTemplate(viewId, pendingIntentTemplate)); 2131 } 2132 2133 /** 2134 * When using collections (eg. {@link ListView}, {@link StackView} etc.) in widgets, it is very 2135 * costly to set PendingIntents on the individual items, and is hence not permitted. Instead 2136 * a single PendingIntent template can be set on the collection, see {@link 2137 * RemoteViews#setPendingIntentTemplate(int, PendingIntent)}, and the individual on-click 2138 * action of a given item can be distinguished by setting a fillInIntent on that item. The 2139 * fillInIntent is then combined with the PendingIntent template in order to determine the final 2140 * intent which will be executed when the item is clicked. This works as follows: any fields 2141 * which are left blank in the PendingIntent template, but are provided by the fillInIntent 2142 * will be overwritten, and the resulting PendingIntent will be used. 2143 * 2144 * 2145 * of the PendingIntent template will then be filled in with the associated fields that are 2146 * set in fillInIntent. See {@link Intent#fillIn(Intent, int)} for more details. 2147 * 2148 * @param viewId The id of the view on which to set the fillInIntent 2149 * @param fillInIntent The intent which will be combined with the parent's PendingIntent 2150 * in order to determine the on-click behavior of the view specified by viewId 2151 */ 2152 public void setOnClickFillInIntent(int viewId, Intent fillInIntent) { 2153 addAction(new SetOnClickFillInIntent(viewId, fillInIntent)); 2154 } 2155 2156 /** 2157 * @hide 2158 * Equivalent to calling a combination of {@link Drawable#setAlpha(int)}, 2159 * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)}, 2160 * and/or {@link Drawable#setLevel(int)} on the {@link Drawable} of a given 2161 * view. 2162 * <p> 2163 * You can omit specific calls by marking their values with null or -1. 2164 * 2165 * @param viewId The id of the view that contains the target 2166 * {@link Drawable} 2167 * @param targetBackground If true, apply these parameters to the 2168 * {@link Drawable} returned by 2169 * {@link android.view.View#getBackground()}. Otherwise, assume 2170 * the target view is an {@link ImageView} and apply them to 2171 * {@link ImageView#getDrawable()}. 2172 * @param alpha Specify an alpha value for the drawable, or -1 to leave 2173 * unchanged. 2174 * @param colorFilter Specify a color for a 2175 * {@link android.graphics.ColorFilter} for this drawable, or -1 2176 * to leave unchanged. 2177 * @param mode Specify a PorterDuff mode for this drawable, or null to leave 2178 * unchanged. 2179 * @param level Specify the level for the drawable, or -1 to leave 2180 * unchanged. 2181 */ 2182 public void setDrawableParameters(int viewId, boolean targetBackground, int alpha, 2183 int colorFilter, PorterDuff.Mode mode, int level) { 2184 addAction(new SetDrawableParameters(viewId, targetBackground, alpha, 2185 colorFilter, mode, level)); 2186 } 2187 2188 /** 2189 * Equivalent to calling {@link android.widget.TextView#setTextColor(int)}. 2190 * 2191 * @param viewId The id of the view whose text color should change 2192 * @param color Sets the text color for all the states (normal, selected, 2193 * focused) to be this color. 2194 */ 2195 public void setTextColor(int viewId, int color) { 2196 setInt(viewId, "setTextColor", color); 2197 } 2198 2199 /** 2200 * Equivalent to calling {@link android.widget.AbsListView#setRemoteViewsAdapter(Intent)}. 2201 * 2202 * @param appWidgetId The id of the app widget which contains the specified view. (This 2203 * parameter is ignored in this deprecated method) 2204 * @param viewId The id of the {@link AdapterView} 2205 * @param intent The intent of the service which will be 2206 * providing data to the RemoteViewsAdapter 2207 * @deprecated This method has been deprecated. See 2208 * {@link android.widget.RemoteViews#setRemoteAdapter(int, Intent)} 2209 */ 2210 @Deprecated 2211 public void setRemoteAdapter(int appWidgetId, int viewId, Intent intent) { 2212 setRemoteAdapter(viewId, intent); 2213 } 2214 2215 /** 2216 * Equivalent to calling {@link android.widget.AbsListView#setRemoteViewsAdapter(Intent)}. 2217 * Can only be used for App Widgets. 2218 * 2219 * @param viewId The id of the {@link AdapterView} 2220 * @param intent The intent of the service which will be 2221 * providing data to the RemoteViewsAdapter 2222 */ 2223 public void setRemoteAdapter(int viewId, Intent intent) { 2224 addAction(new SetRemoteViewsAdapterIntent(viewId, intent)); 2225 } 2226 2227 /** 2228 * Creates a simple Adapter for the viewId specified. The viewId must point to an AdapterView, 2229 * ie. {@link ListView}, {@link GridView}, {@link StackView} or {@link AdapterViewAnimator}. 2230 * This is a simpler but less flexible approach to populating collection widgets. Its use is 2231 * encouraged for most scenarios, as long as the total memory within the list of RemoteViews 2232 * is relatively small (ie. doesn't contain large or numerous Bitmaps, see {@link 2233 * RemoteViews#setImageViewBitmap}). In the case of numerous images, the use of API is still 2234 * possible by setting image URIs instead of Bitmaps, see {@link RemoteViews#setImageViewUri}. 2235 * 2236 * This API is supported in the compatibility library for previous API levels, see 2237 * RemoteViewsCompat. 2238 * 2239 * @param viewId The id of the {@link AdapterView} 2240 * @param list The list of RemoteViews which will populate the view specified by viewId. 2241 * @param viewTypeCount The maximum number of unique layout id's used to construct the list of 2242 * RemoteViews. This count cannot change during the life-cycle of a given widget, so this 2243 * parameter should account for the maximum possible number of types that may appear in the 2244 * See {@link Adapter#getViewTypeCount()}. 2245 * 2246 * @hide 2247 */ 2248 public void setRemoteAdapter(int viewId, ArrayList<RemoteViews> list, int viewTypeCount) { 2249 addAction(new SetRemoteViewsAdapterList(viewId, list, viewTypeCount)); 2250 } 2251 2252 /** 2253 * Equivalent to calling {@link android.widget.AbsListView#smoothScrollToPosition(int, int)}. 2254 * 2255 * @param viewId The id of the view to change 2256 * @param position Scroll to this adapter position 2257 */ 2258 public void setScrollPosition(int viewId, int position) { 2259 setInt(viewId, "smoothScrollToPosition", position); 2260 } 2261 2262 /** 2263 * Equivalent to calling {@link android.widget.AbsListView#smoothScrollToPosition(int, int)}. 2264 * 2265 * @param viewId The id of the view to change 2266 * @param offset Scroll by this adapter position offset 2267 */ 2268 public void setRelativeScrollPosition(int viewId, int offset) { 2269 setInt(viewId, "smoothScrollByOffset", offset); 2270 } 2271 2272 /** 2273 * Equivalent to calling {@link android.view.View#setPadding(int, int, int, int)}. 2274 * 2275 * @param viewId The id of the view to change 2276 * @param left the left padding in pixels 2277 * @param top the top padding in pixels 2278 * @param right the right padding in pixels 2279 * @param bottom the bottom padding in pixels 2280 */ 2281 public void setViewPadding(int viewId, int left, int top, int right, int bottom) { 2282 addAction(new ViewPaddingAction(viewId, left, top, right, bottom)); 2283 } 2284 2285 /** 2286 * Call a method taking one boolean on a view in the layout for this RemoteViews. 2287 * 2288 * @param viewId The id of the view on which to call the method. 2289 * @param methodName The name of the method to call. 2290 * @param value The value to pass to the method. 2291 */ 2292 public void setBoolean(int viewId, String methodName, boolean value) { 2293 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.BOOLEAN, value)); 2294 } 2295 2296 /** 2297 * Call a method taking one byte on a view in the layout for this RemoteViews. 2298 * 2299 * @param viewId The id of the view on which to call the method. 2300 * @param methodName The name of the method to call. 2301 * @param value The value to pass to the method. 2302 */ 2303 public void setByte(int viewId, String methodName, byte value) { 2304 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.BYTE, value)); 2305 } 2306 2307 /** 2308 * Call a method taking one short on a view in the layout for this RemoteViews. 2309 * 2310 * @param viewId The id of the view on which to call the method. 2311 * @param methodName The name of the method to call. 2312 * @param value The value to pass to the method. 2313 */ 2314 public void setShort(int viewId, String methodName, short value) { 2315 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.SHORT, value)); 2316 } 2317 2318 /** 2319 * Call a method taking one int on a view in the layout for this RemoteViews. 2320 * 2321 * @param viewId The id of the view on which to call the method. 2322 * @param methodName The name of the method to call. 2323 * @param value The value to pass to the method. 2324 */ 2325 public void setInt(int viewId, String methodName, int value) { 2326 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.INT, value)); 2327 } 2328 2329 /** 2330 * Call a method taking one long on a view in the layout for this RemoteViews. 2331 * 2332 * @param viewId The id of the view on which to call the method. 2333 * @param methodName The name of the method to call. 2334 * @param value The value to pass to the method. 2335 */ 2336 public void setLong(int viewId, String methodName, long value) { 2337 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.LONG, value)); 2338 } 2339 2340 /** 2341 * Call a method taking one float on a view in the layout for this RemoteViews. 2342 * 2343 * @param viewId The id of the view on which to call the method. 2344 * @param methodName The name of the method to call. 2345 * @param value The value to pass to the method. 2346 */ 2347 public void setFloat(int viewId, String methodName, float value) { 2348 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.FLOAT, value)); 2349 } 2350 2351 /** 2352 * Call a method taking one double on a view in the layout for this RemoteViews. 2353 * 2354 * @param viewId The id of the view on which to call the method. 2355 * @param methodName The name of the method to call. 2356 * @param value The value to pass to the method. 2357 */ 2358 public void setDouble(int viewId, String methodName, double value) { 2359 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.DOUBLE, value)); 2360 } 2361 2362 /** 2363 * Call a method taking one char on a view in the layout for this RemoteViews. 2364 * 2365 * @param viewId The id of the view on which to call the method. 2366 * @param methodName The name of the method to call. 2367 * @param value The value to pass to the method. 2368 */ 2369 public void setChar(int viewId, String methodName, char value) { 2370 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR, value)); 2371 } 2372 2373 /** 2374 * Call a method taking one String on a view in the layout for this RemoteViews. 2375 * 2376 * @param viewId The id of the view on which to call the method. 2377 * @param methodName The name of the method to call. 2378 * @param value The value to pass to the method. 2379 */ 2380 public void setString(int viewId, String methodName, String value) { 2381 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.STRING, value)); 2382 } 2383 2384 /** 2385 * Call a method taking one CharSequence on a view in the layout for this RemoteViews. 2386 * 2387 * @param viewId The id of the view on which to call the method. 2388 * @param methodName The name of the method to call. 2389 * @param value The value to pass to the method. 2390 */ 2391 public void setCharSequence(int viewId, String methodName, CharSequence value) { 2392 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR_SEQUENCE, value)); 2393 } 2394 2395 /** 2396 * Call a method taking one Uri on a view in the layout for this RemoteViews. 2397 * 2398 * @param viewId The id of the view on which to call the method. 2399 * @param methodName The name of the method to call. 2400 * @param value The value to pass to the method. 2401 */ 2402 public void setUri(int viewId, String methodName, Uri value) { 2403 if (value != null) { 2404 // Resolve any filesystem path before sending remotely 2405 value = value.getCanonicalUri(); 2406 if (StrictMode.vmFileUriExposureEnabled()) { 2407 value.checkFileUriExposed("RemoteViews.setUri()"); 2408 } 2409 } 2410 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.URI, value)); 2411 } 2412 2413 /** 2414 * Call a method taking one Bitmap on a view in the layout for this RemoteViews. 2415 * @more 2416 * <p class="note">The bitmap will be flattened into the parcel if this object is 2417 * sent across processes, so it may end up using a lot of memory, and may be fairly slow.</p> 2418 * 2419 * @param viewId The id of the view on which to call the method. 2420 * @param methodName The name of the method to call. 2421 * @param value The value to pass to the method. 2422 */ 2423 public void setBitmap(int viewId, String methodName, Bitmap value) { 2424 addAction(new BitmapReflectionAction(viewId, methodName, value)); 2425 } 2426 2427 /** 2428 * Call a method taking one Bundle on a view in the layout for this RemoteViews. 2429 * 2430 * @param viewId The id of the view on which to call the method. 2431 * @param methodName The name of the method to call. 2432 * @param value The value to pass to the method. 2433 */ 2434 public void setBundle(int viewId, String methodName, Bundle value) { 2435 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.BUNDLE, value)); 2436 } 2437 2438 /** 2439 * Call a method taking one Intent on a view in the layout for this RemoteViews. 2440 * 2441 * @param viewId The id of the view on which to call the method. 2442 * @param methodName The name of the method to call. 2443 * @param value The {@link android.content.Intent} to pass the method. 2444 */ 2445 public void setIntent(int viewId, String methodName, Intent value) { 2446 addAction(new ReflectionAction(viewId, methodName, ReflectionAction.INTENT, value)); 2447 } 2448 2449 /** 2450 * Equivalent to calling View.setContentDescription(CharSequence). 2451 * 2452 * @param viewId The id of the view whose content description should change. 2453 * @param contentDescription The new content description for the view. 2454 */ 2455 public void setContentDescription(int viewId, CharSequence contentDescription) { 2456 setCharSequence(viewId, "setContentDescription", contentDescription); 2457 } 2458 2459 /** 2460 * Equivalent to calling View.setLabelFor(int). 2461 * 2462 * @param viewId The id of the view whose property to set. 2463 * @param labeledId The id of a view for which this view serves as a label. 2464 */ 2465 public void setLabelFor(int viewId, int labeledId) { 2466 setInt(viewId, "setLabelFor", labeledId); 2467 } 2468 2469 private RemoteViews getRemoteViewsToApply(Context context) { 2470 if (hasLandscapeAndPortraitLayouts()) { 2471 int orientation = context.getResources().getConfiguration().orientation; 2472 if (orientation == Configuration.ORIENTATION_LANDSCAPE) { 2473 return mLandscape; 2474 } else { 2475 return mPortrait; 2476 } 2477 } 2478 return this; 2479 } 2480 2481 /** 2482 * Inflates the view hierarchy represented by this object and applies 2483 * all of the actions. 2484 * 2485 * <p><strong>Caller beware: this may throw</strong> 2486 * 2487 * @param context Default context to use 2488 * @param parent Parent that the resulting view hierarchy will be attached to. This method 2489 * does <strong>not</strong> attach the hierarchy. The caller should do so when appropriate. 2490 * @return The inflated view hierarchy 2491 */ 2492 public View apply(Context context, ViewGroup parent) { 2493 return apply(context, parent, null); 2494 } 2495 2496 /** @hide */ 2497 public View apply(Context context, ViewGroup parent, OnClickHandler handler) { 2498 RemoteViews rvToApply = getRemoteViewsToApply(context); 2499 2500 View result; 2501 2502 Context c = prepareContext(context); 2503 2504 LayoutInflater inflater = (LayoutInflater) 2505 c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 2506 2507 inflater = inflater.cloneInContext(c); 2508 inflater.setFilter(this); 2509 2510 result = inflater.inflate(rvToApply.getLayoutId(), parent, false); 2511 2512 rvToApply.performApply(result, parent, handler); 2513 2514 return result; 2515 } 2516 2517 /** 2518 * Applies all of the actions to the provided view. 2519 * 2520 * <p><strong>Caller beware: this may throw</strong> 2521 * 2522 * @param v The view to apply the actions to. This should be the result of 2523 * the {@link #apply(Context,ViewGroup)} call. 2524 */ 2525 public void reapply(Context context, View v) { 2526 reapply(context, v, null); 2527 } 2528 2529 /** @hide */ 2530 public void reapply(Context context, View v, OnClickHandler handler) { 2531 RemoteViews rvToApply = getRemoteViewsToApply(context); 2532 2533 // In the case that a view has this RemoteViews applied in one orientation, is persisted 2534 // across orientation change, and has the RemoteViews re-applied in the new orientation, 2535 // we throw an exception, since the layouts may be completely unrelated. 2536 if (hasLandscapeAndPortraitLayouts()) { 2537 if (v.getId() != rvToApply.getLayoutId()) { 2538 throw new RuntimeException("Attempting to re-apply RemoteViews to a view that" + 2539 " that does not share the same root layout id."); 2540 } 2541 } 2542 2543 prepareContext(context); 2544 rvToApply.performApply(v, (ViewGroup) v.getParent(), handler); 2545 } 2546 2547 private void performApply(View v, ViewGroup parent, OnClickHandler handler) { 2548 if (mActions != null) { 2549 handler = handler == null ? DEFAULT_ON_CLICK_HANDLER : handler; 2550 final int count = mActions.size(); 2551 for (int i = 0; i < count; i++) { 2552 Action a = mActions.get(i); 2553 a.apply(v, parent, handler); 2554 } 2555 } 2556 } 2557 2558 private Context prepareContext(Context context) { 2559 if (mApplication != null) { 2560 if (context.getUserId() == UserHandle.getUserId(mApplication.uid) 2561 && context.getPackageName().equals(mApplication.packageName)) { 2562 return context; 2563 } 2564 try { 2565 return context.createApplicationContext(mApplication, 2566 Context.CONTEXT_RESTRICTED); 2567 } catch (NameNotFoundException e) { 2568 Log.e(LOG_TAG, "Package name " + mPackage + " not found"); 2569 } 2570 } 2571 2572 if (mPackage != null) { 2573 if (context.getPackageName().equals(mPackage)) { 2574 return context; 2575 } 2576 try { 2577 return context.createPackageContext( 2578 mPackage, Context.CONTEXT_RESTRICTED); 2579 } catch (NameNotFoundException e) { 2580 Log.e(LOG_TAG, "Package name " + mPackage + " not found"); 2581 } 2582 } 2583 2584 return context; 2585 } 2586 2587 /** 2588 * Returns the number of actions in this RemoteViews. Can be used as a sequence number. 2589 * 2590 * @hide 2591 */ 2592 public int getSequenceNumber() { 2593 return (mActions == null) ? 0 : mActions.size(); 2594 } 2595 2596 /* (non-Javadoc) 2597 * Used to restrict the views which can be inflated 2598 * 2599 * @see android.view.LayoutInflater.Filter#onLoadClass(java.lang.Class) 2600 */ 2601 public boolean onLoadClass(Class clazz) { 2602 return clazz.isAnnotationPresent(RemoteView.class); 2603 } 2604 2605 public int describeContents() { 2606 return 0; 2607 } 2608 2609 public void writeToParcel(Parcel dest, int flags) { 2610 if (!hasLandscapeAndPortraitLayouts()) { 2611 dest.writeInt(MODE_NORMAL); 2612 // We only write the bitmap cache if we are the root RemoteViews, as this cache 2613 // is shared by all children. 2614 if (mIsRoot) { 2615 mBitmapCache.writeBitmapsToParcel(dest, flags); 2616 } 2617 dest.writeString(mPackage); 2618 dest.writeInt(mLayoutId); 2619 dest.writeInt(mIsWidgetCollectionChild ? 1 : 0); 2620 int count; 2621 if (mActions != null) { 2622 count = mActions.size(); 2623 } else { 2624 count = 0; 2625 } 2626 dest.writeInt(count); 2627 for (int i=0; i<count; i++) { 2628 Action a = mActions.get(i); 2629 a.writeToParcel(dest, 0); 2630 } 2631 } else { 2632 dest.writeInt(MODE_HAS_LANDSCAPE_AND_PORTRAIT); 2633 // We only write the bitmap cache if we are the root RemoteViews, as this cache 2634 // is shared by all children. 2635 if (mIsRoot) { 2636 mBitmapCache.writeBitmapsToParcel(dest, flags); 2637 } 2638 mLandscape.writeToParcel(dest, flags); 2639 mPortrait.writeToParcel(dest, flags); 2640 } 2641 2642 dest.writeParcelable(mApplication, 0); 2643 } 2644 2645 /** 2646 * Parcelable.Creator that instantiates RemoteViews objects 2647 */ 2648 public static final Parcelable.Creator<RemoteViews> CREATOR = new Parcelable.Creator<RemoteViews>() { 2649 public RemoteViews createFromParcel(Parcel parcel) { 2650 return new RemoteViews(parcel); 2651 } 2652 2653 public RemoteViews[] newArray(int size) { 2654 return new RemoteViews[size]; 2655 } 2656 }; 2657} 2658