Notification.java revision f35284804b4f04b91d772b913d9a6ae1c8a5f65a
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.app; 18 19import android.annotation.IntDef; 20import android.annotation.SdkConstant; 21import android.annotation.SdkConstant.SdkConstantType; 22import android.content.Context; 23import android.content.Intent; 24import android.content.pm.ApplicationInfo; 25import android.content.pm.PackageManager.NameNotFoundException; 26import android.content.res.ColorStateList; 27import android.graphics.Bitmap; 28import android.graphics.Canvas; 29import android.graphics.PorterDuff; 30import android.graphics.drawable.Drawable; 31import android.media.AudioAttributes; 32import android.media.AudioManager; 33import android.media.session.MediaSession; 34import android.net.Uri; 35import android.os.BadParcelableException; 36import android.os.Build; 37import android.os.Bundle; 38import android.os.Parcel; 39import android.os.Parcelable; 40import android.os.SystemClock; 41import android.os.UserHandle; 42import android.text.TextUtils; 43import android.util.Log; 44import android.util.MathUtils; 45import android.util.TypedValue; 46import android.view.Gravity; 47import android.view.View; 48import android.widget.ProgressBar; 49import android.widget.RemoteViews; 50 51import com.android.internal.R; 52import com.android.internal.util.NotificationColorUtil; 53 54import java.lang.annotation.Retention; 55import java.lang.annotation.RetentionPolicy; 56import java.lang.reflect.Constructor; 57import java.text.NumberFormat; 58import java.util.ArrayList; 59import java.util.Arrays; 60import java.util.Collections; 61import java.util.List; 62 63/** 64 * A class that represents how a persistent notification is to be presented to 65 * the user using the {@link android.app.NotificationManager}. 66 * 67 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it 68 * easier to construct Notifications.</p> 69 * 70 * <div class="special reference"> 71 * <h3>Developer Guides</h3> 72 * <p>For a guide to creating notifications, read the 73 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a> 74 * developer guide.</p> 75 * </div> 76 */ 77public class Notification implements Parcelable 78{ 79 private static final String TAG = "Notification"; 80 81 /** 82 * An activity that provides a user interface for adjusting notification preferences for its 83 * containing application. Optional but recommended for apps that post 84 * {@link android.app.Notification Notifications}. 85 */ 86 @SdkConstant(SdkConstantType.INTENT_CATEGORY) 87 public static final String INTENT_CATEGORY_NOTIFICATION_PREFERENCES 88 = "android.intent.category.NOTIFICATION_PREFERENCES"; 89 90 /** 91 * Use all default values (where applicable). 92 */ 93 public static final int DEFAULT_ALL = ~0; 94 95 /** 96 * Use the default notification sound. This will ignore any given 97 * {@link #sound}. 98 * 99 * <p> 100 * A notification that is noisy is more likely to be presented as a heads-up notification. 101 * </p> 102 * 103 * @see #defaults 104 */ 105 106 public static final int DEFAULT_SOUND = 1; 107 108 /** 109 * Use the default notification vibrate. This will ignore any given 110 * {@link #vibrate}. Using phone vibration requires the 111 * {@link android.Manifest.permission#VIBRATE VIBRATE} permission. 112 * 113 * <p> 114 * A notification that vibrates is more likely to be presented as a heads-up notification. 115 * </p> 116 * 117 * @see #defaults 118 */ 119 120 public static final int DEFAULT_VIBRATE = 2; 121 122 /** 123 * Use the default notification lights. This will ignore the 124 * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or 125 * {@link #ledOnMS}. 126 * 127 * @see #defaults 128 */ 129 130 public static final int DEFAULT_LIGHTS = 4; 131 132 /** 133 * Maximum length of CharSequences accepted by Builder and friends. 134 * 135 * <p> 136 * Avoids spamming the system with overly large strings such as full e-mails. 137 */ 138 private static final int MAX_CHARSEQUENCE_LENGTH = 5 * 1024; 139 140 /** 141 * A timestamp related to this notification, in milliseconds since the epoch. 142 * 143 * Default value: {@link System#currentTimeMillis() Now}. 144 * 145 * Choose a timestamp that will be most relevant to the user. For most finite events, this 146 * corresponds to the time the event happened (or will happen, in the case of events that have 147 * yet to occur but about which the user is being informed). Indefinite events should be 148 * timestamped according to when the activity began. 149 * 150 * Some examples: 151 * 152 * <ul> 153 * <li>Notification of a new chat message should be stamped when the message was received.</li> 154 * <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li> 155 * <li>Notification of a completed file download should be stamped when the download finished.</li> 156 * <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li> 157 * <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time. 158 * <li>Notification of an ongoing countdown timer should be stamped with the timer's end time. 159 * </ul> 160 * 161 */ 162 public long when; 163 164 /** 165 * The resource id of a drawable to use as the icon in the status bar. 166 * This is required; notifications with an invalid icon resource will not be shown. 167 */ 168 public int icon; 169 170 /** 171 * If the icon in the status bar is to have more than one level, you can set this. Otherwise, 172 * leave it at its default value of 0. 173 * 174 * @see android.widget.ImageView#setImageLevel 175 * @see android.graphics.drawable.Drawable#setLevel 176 */ 177 public int iconLevel; 178 179 /** 180 * The number of events that this notification represents. For example, in a new mail 181 * notification, this could be the number of unread messages. 182 * 183 * The system may or may not use this field to modify the appearance of the notification. For 184 * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was 185 * superimposed over the icon in the status bar. Starting with 186 * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by 187 * {@link Notification.Builder} has displayed the number in the expanded notification view. 188 * 189 * If the number is 0 or negative, it is never shown. 190 */ 191 public int number; 192 193 /** 194 * The intent to execute when the expanded status entry is clicked. If 195 * this is an activity, it must include the 196 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires 197 * that you take care of task management as described in the 198 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back 199 * Stack</a> document. In particular, make sure to read the notification section 200 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling 201 * Notifications</a> for the correct ways to launch an application from a 202 * notification. 203 */ 204 public PendingIntent contentIntent; 205 206 /** 207 * The intent to execute when the notification is explicitly dismissed by the user, either with 208 * the "Clear All" button or by swiping it away individually. 209 * 210 * This probably shouldn't be launching an activity since several of those will be sent 211 * at the same time. 212 */ 213 public PendingIntent deleteIntent; 214 215 /** 216 * An intent to launch instead of posting the notification to the status bar. 217 * 218 * <p> 219 * The system UI may choose to display a heads-up notification, instead of 220 * launching this intent, while the user is using the device. 221 * </p> 222 * 223 * @see Notification.Builder#setFullScreenIntent 224 */ 225 public PendingIntent fullScreenIntent; 226 227 /** 228 * Text that summarizes this notification for accessibility services. 229 * 230 * As of the L release, this text is no longer shown on screen, but it is still useful to 231 * accessibility services (where it serves as an audible announcement of the notification's 232 * appearance). 233 * 234 * @see #tickerView 235 */ 236 public CharSequence tickerText; 237 238 /** 239 * Formerly, a view showing the {@link #tickerText}. 240 * 241 * No longer displayed in the status bar as of API 21. 242 */ 243 @Deprecated 244 public RemoteViews tickerView; 245 246 /** 247 * The view that will represent this notification in the expanded status bar. 248 */ 249 public RemoteViews contentView; 250 251 /** 252 * A large-format version of {@link #contentView}, giving the Notification an 253 * opportunity to show more detail. The system UI may choose to show this 254 * instead of the normal content view at its discretion. 255 */ 256 public RemoteViews bigContentView; 257 258 259 /** 260 * A medium-format version of {@link #contentView}, providing the Notification an 261 * opportunity to add action buttons to contentView. At its discretion, the system UI may 262 * choose to show this as a heads-up notification, which will pop up so the user can see 263 * it without leaving their current activity. 264 */ 265 public RemoteViews headsUpContentView; 266 267 /** 268 * The bitmap that may escape the bounds of the panel and bar. 269 */ 270 public Bitmap largeIcon; 271 272 /** 273 * The sound to play. 274 * 275 * <p> 276 * A notification that is noisy is more likely to be presented as a heads-up notification. 277 * </p> 278 * 279 * <p> 280 * To play the default notification sound, see {@link #defaults}. 281 * </p> 282 */ 283 public Uri sound; 284 285 /** 286 * Use this constant as the value for audioStreamType to request that 287 * the default stream type for notifications be used. Currently the 288 * default stream type is {@link AudioManager#STREAM_NOTIFICATION}. 289 * 290 * @deprecated Use {@link #audioAttributes} instead. 291 */ 292 @Deprecated 293 public static final int STREAM_DEFAULT = -1; 294 295 /** 296 * The audio stream type to use when playing the sound. 297 * Should be one of the STREAM_ constants from 298 * {@link android.media.AudioManager}. 299 * 300 * @deprecated Use {@link #audioAttributes} instead. 301 */ 302 @Deprecated 303 public int audioStreamType = STREAM_DEFAULT; 304 305 /** 306 * The default value of {@link #audioAttributes}. 307 */ 308 public static final AudioAttributes AUDIO_ATTRIBUTES_DEFAULT = new AudioAttributes.Builder() 309 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) 310 .setUsage(AudioAttributes.USAGE_NOTIFICATION) 311 .build(); 312 313 /** 314 * The {@link AudioAttributes audio attributes} to use when playing the sound. 315 */ 316 public AudioAttributes audioAttributes = AUDIO_ATTRIBUTES_DEFAULT; 317 318 /** 319 * The pattern with which to vibrate. 320 * 321 * <p> 322 * To vibrate the default pattern, see {@link #defaults}. 323 * </p> 324 * 325 * <p> 326 * A notification that vibrates is more likely to be presented as a heads-up notification. 327 * </p> 328 * 329 * @see android.os.Vibrator#vibrate(long[],int) 330 */ 331 public long[] vibrate; 332 333 /** 334 * The color of the led. The hardware will do its best approximation. 335 * 336 * @see #FLAG_SHOW_LIGHTS 337 * @see #flags 338 */ 339 public int ledARGB; 340 341 /** 342 * The number of milliseconds for the LED to be on while it's flashing. 343 * The hardware will do its best approximation. 344 * 345 * @see #FLAG_SHOW_LIGHTS 346 * @see #flags 347 */ 348 public int ledOnMS; 349 350 /** 351 * The number of milliseconds for the LED to be off while it's flashing. 352 * The hardware will do its best approximation. 353 * 354 * @see #FLAG_SHOW_LIGHTS 355 * @see #flags 356 */ 357 public int ledOffMS; 358 359 /** 360 * Specifies which values should be taken from the defaults. 361 * <p> 362 * To set, OR the desired from {@link #DEFAULT_SOUND}, 363 * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default 364 * values, use {@link #DEFAULT_ALL}. 365 * </p> 366 */ 367 public int defaults; 368 369 /** 370 * Bit to be bitwise-ored into the {@link #flags} field that should be 371 * set if you want the LED on for this notification. 372 * <ul> 373 * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB 374 * or 0 for both ledOnMS and ledOffMS.</li> 375 * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li> 376 * <li>To flash the LED, pass the number of milliseconds that it should 377 * be on and off to ledOnMS and ledOffMS.</li> 378 * </ul> 379 * <p> 380 * Since hardware varies, you are not guaranteed that any of the values 381 * you pass are honored exactly. Use the system defaults (TODO) if possible 382 * because they will be set to values that work on any given hardware. 383 * <p> 384 * The alpha channel must be set for forward compatibility. 385 * 386 */ 387 public static final int FLAG_SHOW_LIGHTS = 0x00000001; 388 389 /** 390 * Bit to be bitwise-ored into the {@link #flags} field that should be 391 * set if this notification is in reference to something that is ongoing, 392 * like a phone call. It should not be set if this notification is in 393 * reference to something that happened at a particular point in time, 394 * like a missed phone call. 395 */ 396 public static final int FLAG_ONGOING_EVENT = 0x00000002; 397 398 /** 399 * Bit to be bitwise-ored into the {@link #flags} field that if set, 400 * the audio will be repeated until the notification is 401 * cancelled or the notification window is opened. 402 */ 403 public static final int FLAG_INSISTENT = 0x00000004; 404 405 /** 406 * Bit to be bitwise-ored into the {@link #flags} field that should be 407 * set if you would only like the sound, vibrate and ticker to be played 408 * if the notification was not already showing. 409 */ 410 public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008; 411 412 /** 413 * Bit to be bitwise-ored into the {@link #flags} field that should be 414 * set if the notification should be canceled when it is clicked by the 415 * user. 416 417 */ 418 public static final int FLAG_AUTO_CANCEL = 0x00000010; 419 420 /** 421 * Bit to be bitwise-ored into the {@link #flags} field that should be 422 * set if the notification should not be canceled when the user clicks 423 * the Clear all button. 424 */ 425 public static final int FLAG_NO_CLEAR = 0x00000020; 426 427 /** 428 * Bit to be bitwise-ored into the {@link #flags} field that should be 429 * set if this notification represents a currently running service. This 430 * will normally be set for you by {@link Service#startForeground}. 431 */ 432 public static final int FLAG_FOREGROUND_SERVICE = 0x00000040; 433 434 /** 435 * Obsolete flag indicating high-priority notifications; use the priority field instead. 436 * 437 * @deprecated Use {@link #priority} with a positive value. 438 */ 439 public static final int FLAG_HIGH_PRIORITY = 0x00000080; 440 441 /** 442 * Bit to be bitswise-ored into the {@link #flags} field that should be 443 * set if this notification is relevant to the current device only 444 * and it is not recommended that it bridge to other devices. 445 */ 446 public static final int FLAG_LOCAL_ONLY = 0x00000100; 447 448 /** 449 * Bit to be bitswise-ored into the {@link #flags} field that should be 450 * set if this notification is the group summary for a group of notifications. 451 * Grouped notifications may display in a cluster or stack on devices which 452 * support such rendering. Requires a group key also be set using {@link Builder#setGroup}. 453 */ 454 public static final int FLAG_GROUP_SUMMARY = 0x00000200; 455 456 public int flags; 457 458 /** @hide */ 459 @IntDef({PRIORITY_DEFAULT,PRIORITY_LOW,PRIORITY_MIN,PRIORITY_HIGH,PRIORITY_MAX}) 460 @Retention(RetentionPolicy.SOURCE) 461 public @interface Priority {} 462 463 /** 464 * Default notification {@link #priority}. If your application does not prioritize its own 465 * notifications, use this value for all notifications. 466 */ 467 public static final int PRIORITY_DEFAULT = 0; 468 469 /** 470 * Lower {@link #priority}, for items that are less important. The UI may choose to show these 471 * items smaller, or at a different position in the list, compared with your app's 472 * {@link #PRIORITY_DEFAULT} items. 473 */ 474 public static final int PRIORITY_LOW = -1; 475 476 /** 477 * Lowest {@link #priority}; these items might not be shown to the user except under special 478 * circumstances, such as detailed notification logs. 479 */ 480 public static final int PRIORITY_MIN = -2; 481 482 /** 483 * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to 484 * show these items larger, or at a different position in notification lists, compared with 485 * your app's {@link #PRIORITY_DEFAULT} items. 486 */ 487 public static final int PRIORITY_HIGH = 1; 488 489 /** 490 * Highest {@link #priority}, for your application's most important items that require the 491 * user's prompt attention or input. 492 */ 493 public static final int PRIORITY_MAX = 2; 494 495 /** 496 * Relative priority for this notification. 497 * 498 * Priority is an indication of how much of the user's valuable attention should be consumed by 499 * this notification. Low-priority notifications may be hidden from the user in certain 500 * situations, while the user might be interrupted for a higher-priority notification. The 501 * system will make a determination about how to interpret this priority when presenting 502 * the notification. 503 * 504 * <p> 505 * A notification that is at least {@link #PRIORITY_HIGH} is more likely to be presented 506 * as a heads-up notification. 507 * </p> 508 * 509 */ 510 @Priority 511 public int priority; 512 513 /** 514 * Accent color (an ARGB integer like the constants in {@link android.graphics.Color}) 515 * to be applied by the standard Style templates when presenting this notification. 516 * 517 * The current template design constructs a colorful header image by overlaying the 518 * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are 519 * ignored. 520 */ 521 public int color = COLOR_DEFAULT; 522 523 /** 524 * Special value of {@link #color} telling the system not to decorate this notification with 525 * any special color but instead use default colors when presenting this notification. 526 */ 527 public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT 528 529 /** 530 * Sphere of visibility of this notification, which affects how and when the SystemUI reveals 531 * the notification's presence and contents in untrusted situations (namely, on the secure 532 * lockscreen). 533 * 534 * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always 535 * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are 536 * shown in all situations, but the contents are only available if the device is unlocked for 537 * the appropriate user. 538 * 539 * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification 540 * can be read even in an "insecure" context (that is, above a secure lockscreen). 541 * To modify the public version of this notification—for example, to redact some portions—see 542 * {@link Builder#setPublicVersion(Notification)}. 543 * 544 * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon 545 * and ticker until the user has bypassed the lockscreen. 546 */ 547 public int visibility; 548 549 /** 550 * Notification visibility: Show this notification in its entirety on all lockscreens. 551 * 552 * {@see #visibility} 553 */ 554 public static final int VISIBILITY_PUBLIC = 1; 555 556 /** 557 * Notification visibility: Show this notification on all lockscreens, but conceal sensitive or 558 * private information on secure lockscreens. 559 * 560 * {@see #visibility} 561 */ 562 public static final int VISIBILITY_PRIVATE = 0; 563 564 /** 565 * Notification visibility: Do not reveal any part of this notification on a secure lockscreen. 566 * 567 * {@see #visibility} 568 */ 569 public static final int VISIBILITY_SECRET = -1; 570 571 /** 572 * Notification category: incoming call (voice or video) or similar synchronous communication request. 573 */ 574 public static final String CATEGORY_CALL = "call"; 575 576 /** 577 * Notification category: incoming direct message (SMS, instant message, etc.). 578 */ 579 public static final String CATEGORY_MESSAGE = "msg"; 580 581 /** 582 * Notification category: asynchronous bulk message (email). 583 */ 584 public static final String CATEGORY_EMAIL = "email"; 585 586 /** 587 * Notification category: calendar event. 588 */ 589 public static final String CATEGORY_EVENT = "event"; 590 591 /** 592 * Notification category: promotion or advertisement. 593 */ 594 public static final String CATEGORY_PROMO = "promo"; 595 596 /** 597 * Notification category: alarm or timer. 598 */ 599 public static final String CATEGORY_ALARM = "alarm"; 600 601 /** 602 * Notification category: progress of a long-running background operation. 603 */ 604 public static final String CATEGORY_PROGRESS = "progress"; 605 606 /** 607 * Notification category: social network or sharing update. 608 */ 609 public static final String CATEGORY_SOCIAL = "social"; 610 611 /** 612 * Notification category: error in background operation or authentication status. 613 */ 614 public static final String CATEGORY_ERROR = "err"; 615 616 /** 617 * Notification category: media transport control for playback. 618 */ 619 public static final String CATEGORY_TRANSPORT = "transport"; 620 621 /** 622 * Notification category: system or device status update. Reserved for system use. 623 */ 624 public static final String CATEGORY_SYSTEM = "sys"; 625 626 /** 627 * Notification category: indication of running background service. 628 */ 629 public static final String CATEGORY_SERVICE = "service"; 630 631 /** 632 * Notification category: a specific, timely recommendation for a single thing. 633 * For example, a news app might want to recommend a news story it believes the user will 634 * want to read next. 635 */ 636 public static final String CATEGORY_RECOMMENDATION = "recommendation"; 637 638 /** 639 * Notification category: ongoing information about device or contextual status. 640 */ 641 public static final String CATEGORY_STATUS = "status"; 642 643 /** 644 * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants) 645 * that best describes this Notification. May be used by the system for ranking and filtering. 646 */ 647 public String category; 648 649 private String mGroupKey; 650 651 /** 652 * Get the key used to group this notification into a cluster or stack 653 * with other notifications on devices which support such rendering. 654 */ 655 public String getGroup() { 656 return mGroupKey; 657 } 658 659 private String mSortKey; 660 661 /** 662 * Get a sort key that orders this notification among other notifications from the 663 * same package. This can be useful if an external sort was already applied and an app 664 * would like to preserve this. Notifications will be sorted lexicographically using this 665 * value, although providing different priorities in addition to providing sort key may 666 * cause this value to be ignored. 667 * 668 * <p>This sort key can also be used to order members of a notification group. See 669 * {@link Builder#setGroup}. 670 * 671 * @see String#compareTo(String) 672 */ 673 public String getSortKey() { 674 return mSortKey; 675 } 676 677 /** 678 * Additional semantic data to be carried around with this Notification. 679 * <p> 680 * The extras keys defined here are intended to capture the original inputs to {@link Builder} 681 * APIs, and are intended to be used by 682 * {@link android.service.notification.NotificationListenerService} implementations to extract 683 * detailed information from notification objects. 684 */ 685 public Bundle extras = new Bundle(); 686 687 /** 688 * {@link #extras} key: this is the title of the notification, 689 * as supplied to {@link Builder#setContentTitle(CharSequence)}. 690 */ 691 public static final String EXTRA_TITLE = "android.title"; 692 693 /** 694 * {@link #extras} key: this is the title of the notification when shown in expanded form, 695 * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}. 696 */ 697 public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big"; 698 699 /** 700 * {@link #extras} key: this is the main text payload, as supplied to 701 * {@link Builder#setContentText(CharSequence)}. 702 */ 703 public static final String EXTRA_TEXT = "android.text"; 704 705 /** 706 * {@link #extras} key: this is a third line of text, as supplied to 707 * {@link Builder#setSubText(CharSequence)}. 708 */ 709 public static final String EXTRA_SUB_TEXT = "android.subText"; 710 711 /** 712 * {@link #extras} key: this is a small piece of additional text as supplied to 713 * {@link Builder#setContentInfo(CharSequence)}. 714 */ 715 public static final String EXTRA_INFO_TEXT = "android.infoText"; 716 717 /** 718 * {@link #extras} key: this is a line of summary information intended to be shown 719 * alongside expanded notifications, as supplied to (e.g.) 720 * {@link BigTextStyle#setSummaryText(CharSequence)}. 721 */ 722 public static final String EXTRA_SUMMARY_TEXT = "android.summaryText"; 723 724 /** 725 * {@link #extras} key: this is the longer text shown in the big form of a 726 * {@link BigTextStyle} notification, as supplied to 727 * {@link BigTextStyle#bigText(CharSequence)}. 728 */ 729 public static final String EXTRA_BIG_TEXT = "android.bigText"; 730 731 /** 732 * {@link #extras} key: this is the resource ID of the notification's main small icon, as 733 * supplied to {@link Builder#setSmallIcon(int)}. 734 */ 735 public static final String EXTRA_SMALL_ICON = "android.icon"; 736 737 /** 738 * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the 739 * notification payload, as 740 * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}. 741 */ 742 public static final String EXTRA_LARGE_ICON = "android.largeIcon"; 743 744 /** 745 * {@link #extras} key: this is a bitmap to be used instead of the one from 746 * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is 747 * shown in its expanded form, as supplied to 748 * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}. 749 */ 750 public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big"; 751 752 /** 753 * {@link #extras} key: this is the progress value supplied to 754 * {@link Builder#setProgress(int, int, boolean)}. 755 */ 756 public static final String EXTRA_PROGRESS = "android.progress"; 757 758 /** 759 * {@link #extras} key: this is the maximum value supplied to 760 * {@link Builder#setProgress(int, int, boolean)}. 761 */ 762 public static final String EXTRA_PROGRESS_MAX = "android.progressMax"; 763 764 /** 765 * {@link #extras} key: whether the progress bar is indeterminate, supplied to 766 * {@link Builder#setProgress(int, int, boolean)}. 767 */ 768 public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate"; 769 770 /** 771 * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically 772 * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to 773 * {@link Builder#setUsesChronometer(boolean)}. 774 */ 775 public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer"; 776 777 /** 778 * {@link #extras} key: whether {@link #when} should be shown, 779 * as supplied to {@link Builder#setShowWhen(boolean)}. 780 */ 781 public static final String EXTRA_SHOW_WHEN = "android.showWhen"; 782 783 /** 784 * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded 785 * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}. 786 */ 787 public static final String EXTRA_PICTURE = "android.picture"; 788 789 /** 790 * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded 791 * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}. 792 */ 793 public static final String EXTRA_TEXT_LINES = "android.textLines"; 794 795 /** 796 * {@link #extras} key: A string representing the name of the specific 797 * {@link android.app.Notification.Style} used to create this notification. 798 */ 799 public static final String EXTRA_TEMPLATE = "android.template"; 800 801 /** 802 * {@link #extras} key: A String array containing the people that this notification relates to, 803 * each of which was supplied to {@link Builder#addPerson(String)}. 804 */ 805 public static final String EXTRA_PEOPLE = "android.people"; 806 807 /** 808 * {@link #extras} key: used to provide hints about the appropriateness of 809 * displaying this notification as a heads-up notification. 810 * @hide 811 */ 812 public static final String EXTRA_AS_HEADS_UP = "headsup"; 813 814 /** 815 * Allow certain system-generated notifications to appear before the device is provisioned. 816 * Only available to notifications coming from the android package. 817 * @hide 818 */ 819 public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup"; 820 821 /** 822 * {@link #extras} key: A 823 * {@link android.content.ContentUris content URI} pointing to an image that can be displayed 824 * in the background when the notification is selected. The URI must point to an image stream 825 * suitable for passing into 826 * {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream) 827 * BitmapFactory.decodeStream}; all other content types will be ignored. The content provider 828 * URI used for this purpose must require no permissions to read the image data. 829 */ 830 public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri"; 831 832 /** 833 * {@link #extras} key: A 834 * {@link android.media.session.MediaSession.Token} associated with a 835 * {@link android.app.Notification.MediaStyle} notification. 836 */ 837 public static final String EXTRA_MEDIA_SESSION = "android.mediaSession"; 838 839 /** 840 * {@link #extras} key: the indices of actions to be shown in the compact view, 841 * as supplied to (e.g.) {@link MediaStyle#setShowActionsInCompactView(int...)}. 842 */ 843 public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions"; 844 845 /** 846 * {@link #extras} key: the user that built the notification. 847 * 848 * @hide 849 */ 850 public static final String EXTRA_ORIGINATING_USERID = "android.originatingUserId"; 851 852 /** 853 * Value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification should not be 854 * displayed in the heads up space. 855 * 856 * <p> 857 * If this notification has a {@link #fullScreenIntent}, then it will always launch the 858 * full-screen intent when posted. 859 * </p> 860 * @hide 861 */ 862 public static final int HEADS_UP_NEVER = 0; 863 864 /** 865 * Default value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification may be 866 * displayed as a heads up. 867 * @hide 868 */ 869 public static final int HEADS_UP_ALLOWED = 1; 870 871 /** 872 * Value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification is a 873 * good candidate for display as a heads up. 874 * @hide 875 */ 876 public static final int HEADS_UP_REQUESTED = 2; 877 878 /** 879 * Structure to encapsulate a named action that can be shown as part of this notification. 880 * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is 881 * selected by the user. 882 * <p> 883 * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)} 884 * or {@link Notification.Builder#addAction(Notification.Action)} 885 * to attach actions. 886 */ 887 public static class Action implements Parcelable { 888 private final Bundle mExtras; 889 private final RemoteInput[] mRemoteInputs; 890 891 /** 892 * Small icon representing the action. 893 */ 894 public int icon; 895 896 /** 897 * Title of the action. 898 */ 899 public CharSequence title; 900 901 /** 902 * Intent to send when the user invokes this action. May be null, in which case the action 903 * may be rendered in a disabled presentation by the system UI. 904 */ 905 public PendingIntent actionIntent; 906 907 private Action(Parcel in) { 908 icon = in.readInt(); 909 title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 910 if (in.readInt() == 1) { 911 actionIntent = PendingIntent.CREATOR.createFromParcel(in); 912 } 913 mExtras = in.readBundle(); 914 mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR); 915 } 916 917 /** 918 * Use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}. 919 */ 920 public Action(int icon, CharSequence title, PendingIntent intent) { 921 this(icon, title, intent, new Bundle(), null); 922 } 923 924 private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras, 925 RemoteInput[] remoteInputs) { 926 this.icon = icon; 927 this.title = title; 928 this.actionIntent = intent; 929 this.mExtras = extras != null ? extras : new Bundle(); 930 this.mRemoteInputs = remoteInputs; 931 } 932 933 /** 934 * Get additional metadata carried around with this Action. 935 */ 936 public Bundle getExtras() { 937 return mExtras; 938 } 939 940 /** 941 * Get the list of inputs to be collected from the user when this action is sent. 942 * May return null if no remote inputs were added. 943 */ 944 public RemoteInput[] getRemoteInputs() { 945 return mRemoteInputs; 946 } 947 948 /** 949 * Builder class for {@link Action} objects. 950 */ 951 public static final class Builder { 952 private final int mIcon; 953 private final CharSequence mTitle; 954 private final PendingIntent mIntent; 955 private final Bundle mExtras; 956 private ArrayList<RemoteInput> mRemoteInputs; 957 958 /** 959 * Construct a new builder for {@link Action} object. 960 * @param icon icon to show for this action 961 * @param title the title of the action 962 * @param intent the {@link PendingIntent} to fire when users trigger this action 963 */ 964 public Builder(int icon, CharSequence title, PendingIntent intent) { 965 this(icon, title, intent, new Bundle(), null); 966 } 967 968 /** 969 * Construct a new builder for {@link Action} object using the fields from an 970 * {@link Action}. 971 * @param action the action to read fields from. 972 */ 973 public Builder(Action action) { 974 this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras), 975 action.getRemoteInputs()); 976 } 977 978 private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras, 979 RemoteInput[] remoteInputs) { 980 mIcon = icon; 981 mTitle = title; 982 mIntent = intent; 983 mExtras = extras; 984 if (remoteInputs != null) { 985 mRemoteInputs = new ArrayList<RemoteInput>(remoteInputs.length); 986 Collections.addAll(mRemoteInputs, remoteInputs); 987 } 988 } 989 990 /** 991 * Merge additional metadata into this builder. 992 * 993 * <p>Values within the Bundle will replace existing extras values in this Builder. 994 * 995 * @see Notification.Action#extras 996 */ 997 public Builder addExtras(Bundle extras) { 998 if (extras != null) { 999 mExtras.putAll(extras); 1000 } 1001 return this; 1002 } 1003 1004 /** 1005 * Get the metadata Bundle used by this Builder. 1006 * 1007 * <p>The returned Bundle is shared with this Builder. 1008 */ 1009 public Bundle getExtras() { 1010 return mExtras; 1011 } 1012 1013 /** 1014 * Add an input to be collected from the user when this action is sent. 1015 * Response values can be retrieved from the fired intent by using the 1016 * {@link RemoteInput#getResultsFromIntent} function. 1017 * @param remoteInput a {@link RemoteInput} to add to the action 1018 * @return this object for method chaining 1019 */ 1020 public Builder addRemoteInput(RemoteInput remoteInput) { 1021 if (mRemoteInputs == null) { 1022 mRemoteInputs = new ArrayList<RemoteInput>(); 1023 } 1024 mRemoteInputs.add(remoteInput); 1025 return this; 1026 } 1027 1028 /** 1029 * Apply an extender to this action builder. Extenders may be used to add 1030 * metadata or change options on this builder. 1031 */ 1032 public Builder extend(Extender extender) { 1033 extender.extend(this); 1034 return this; 1035 } 1036 1037 /** 1038 * Combine all of the options that have been set and return a new {@link Action} 1039 * object. 1040 * @return the built action 1041 */ 1042 public Action build() { 1043 RemoteInput[] remoteInputs = mRemoteInputs != null 1044 ? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null; 1045 return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs); 1046 } 1047 } 1048 1049 @Override 1050 public Action clone() { 1051 return new Action( 1052 icon, 1053 title, 1054 actionIntent, // safe to alias 1055 new Bundle(mExtras), 1056 getRemoteInputs()); 1057 } 1058 @Override 1059 public int describeContents() { 1060 return 0; 1061 } 1062 @Override 1063 public void writeToParcel(Parcel out, int flags) { 1064 out.writeInt(icon); 1065 TextUtils.writeToParcel(title, out, flags); 1066 if (actionIntent != null) { 1067 out.writeInt(1); 1068 actionIntent.writeToParcel(out, flags); 1069 } else { 1070 out.writeInt(0); 1071 } 1072 out.writeBundle(mExtras); 1073 out.writeTypedArray(mRemoteInputs, flags); 1074 } 1075 public static final Parcelable.Creator<Action> CREATOR = 1076 new Parcelable.Creator<Action>() { 1077 public Action createFromParcel(Parcel in) { 1078 return new Action(in); 1079 } 1080 public Action[] newArray(int size) { 1081 return new Action[size]; 1082 } 1083 }; 1084 1085 /** 1086 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add 1087 * metadata or change options on an action builder. 1088 */ 1089 public interface Extender { 1090 /** 1091 * Apply this extender to a notification action builder. 1092 * @param builder the builder to be modified. 1093 * @return the build object for chaining. 1094 */ 1095 public Builder extend(Builder builder); 1096 } 1097 1098 /** 1099 * Wearable extender for notification actions. To add extensions to an action, 1100 * create a new {@link android.app.Notification.Action.WearableExtender} object using 1101 * the {@code WearableExtender()} constructor and apply it to a 1102 * {@link android.app.Notification.Action.Builder} using 1103 * {@link android.app.Notification.Action.Builder#extend}. 1104 * 1105 * <pre class="prettyprint"> 1106 * Notification.Action action = new Notification.Action.Builder( 1107 * R.drawable.archive_all, "Archive all", actionIntent) 1108 * .extend(new Notification.Action.WearableExtender() 1109 * .setAvailableOffline(false)) 1110 * .build();</pre> 1111 */ 1112 public static final class WearableExtender implements Extender { 1113 /** Notification action extra which contains wearable extensions */ 1114 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS"; 1115 1116 // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options. 1117 private static final String KEY_FLAGS = "flags"; 1118 private static final String KEY_IN_PROGRESS_LABEL = "inProgressLabel"; 1119 private static final String KEY_CONFIRM_LABEL = "confirmLabel"; 1120 private static final String KEY_CANCEL_LABEL = "cancelLabel"; 1121 1122 // Flags bitwise-ored to mFlags 1123 private static final int FLAG_AVAILABLE_OFFLINE = 0x1; 1124 1125 // Default value for flags integer 1126 private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE; 1127 1128 private int mFlags = DEFAULT_FLAGS; 1129 1130 private CharSequence mInProgressLabel; 1131 private CharSequence mConfirmLabel; 1132 private CharSequence mCancelLabel; 1133 1134 /** 1135 * Create a {@link android.app.Notification.Action.WearableExtender} with default 1136 * options. 1137 */ 1138 public WearableExtender() { 1139 } 1140 1141 /** 1142 * Create a {@link android.app.Notification.Action.WearableExtender} by reading 1143 * wearable options present in an existing notification action. 1144 * @param action the notification action to inspect. 1145 */ 1146 public WearableExtender(Action action) { 1147 Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS); 1148 if (wearableBundle != null) { 1149 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS); 1150 mInProgressLabel = wearableBundle.getCharSequence(KEY_IN_PROGRESS_LABEL); 1151 mConfirmLabel = wearableBundle.getCharSequence(KEY_CONFIRM_LABEL); 1152 mCancelLabel = wearableBundle.getCharSequence(KEY_CANCEL_LABEL); 1153 } 1154 } 1155 1156 /** 1157 * Apply wearable extensions to a notification action that is being built. This is 1158 * typically called by the {@link android.app.Notification.Action.Builder#extend} 1159 * method of {@link android.app.Notification.Action.Builder}. 1160 */ 1161 @Override 1162 public Action.Builder extend(Action.Builder builder) { 1163 Bundle wearableBundle = new Bundle(); 1164 1165 if (mFlags != DEFAULT_FLAGS) { 1166 wearableBundle.putInt(KEY_FLAGS, mFlags); 1167 } 1168 if (mInProgressLabel != null) { 1169 wearableBundle.putCharSequence(KEY_IN_PROGRESS_LABEL, mInProgressLabel); 1170 } 1171 if (mConfirmLabel != null) { 1172 wearableBundle.putCharSequence(KEY_CONFIRM_LABEL, mConfirmLabel); 1173 } 1174 if (mCancelLabel != null) { 1175 wearableBundle.putCharSequence(KEY_CANCEL_LABEL, mCancelLabel); 1176 } 1177 1178 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle); 1179 return builder; 1180 } 1181 1182 @Override 1183 public WearableExtender clone() { 1184 WearableExtender that = new WearableExtender(); 1185 that.mFlags = this.mFlags; 1186 that.mInProgressLabel = this.mInProgressLabel; 1187 that.mConfirmLabel = this.mConfirmLabel; 1188 that.mCancelLabel = this.mCancelLabel; 1189 return that; 1190 } 1191 1192 /** 1193 * Set whether this action is available when the wearable device is not connected to 1194 * a companion device. The user can still trigger this action when the wearable device is 1195 * offline, but a visual hint will indicate that the action may not be available. 1196 * Defaults to true. 1197 */ 1198 public WearableExtender setAvailableOffline(boolean availableOffline) { 1199 setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline); 1200 return this; 1201 } 1202 1203 /** 1204 * Get whether this action is available when the wearable device is not connected to 1205 * a companion device. The user can still trigger this action when the wearable device is 1206 * offline, but a visual hint will indicate that the action may not be available. 1207 * Defaults to true. 1208 */ 1209 public boolean isAvailableOffline() { 1210 return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0; 1211 } 1212 1213 private void setFlag(int mask, boolean value) { 1214 if (value) { 1215 mFlags |= mask; 1216 } else { 1217 mFlags &= ~mask; 1218 } 1219 } 1220 1221 /** 1222 * Set a label to display while the wearable is preparing to automatically execute the 1223 * action. This is usually a 'ing' verb ending in ellipsis like "Sending..." 1224 * 1225 * @param label the label to display while the action is being prepared to execute 1226 * @return this object for method chaining 1227 */ 1228 public WearableExtender setInProgressLabel(CharSequence label) { 1229 mInProgressLabel = label; 1230 return this; 1231 } 1232 1233 /** 1234 * Get the label to display while the wearable is preparing to automatically execute 1235 * the action. This is usually a 'ing' verb ending in ellipsis like "Sending..." 1236 * 1237 * @return the label to display while the action is being prepared to execute 1238 */ 1239 public CharSequence getInProgressLabel() { 1240 return mInProgressLabel; 1241 } 1242 1243 /** 1244 * Set a label to display to confirm that the action should be executed. 1245 * This is usually an imperative verb like "Send". 1246 * 1247 * @param label the label to confirm the action should be executed 1248 * @return this object for method chaining 1249 */ 1250 public WearableExtender setConfirmLabel(CharSequence label) { 1251 mConfirmLabel = label; 1252 return this; 1253 } 1254 1255 /** 1256 * Get the label to display to confirm that the action should be executed. 1257 * This is usually an imperative verb like "Send". 1258 * 1259 * @return the label to confirm the action should be executed 1260 */ 1261 public CharSequence getConfirmLabel() { 1262 return mConfirmLabel; 1263 } 1264 1265 /** 1266 * Set a label to display to cancel the action. 1267 * This is usually an imperative verb, like "Cancel". 1268 * 1269 * @param label the label to display to cancel the action 1270 * @return this object for method chaining 1271 */ 1272 public WearableExtender setCancelLabel(CharSequence label) { 1273 mCancelLabel = label; 1274 return this; 1275 } 1276 1277 /** 1278 * Get the label to display to cancel the action. 1279 * This is usually an imperative verb like "Cancel". 1280 * 1281 * @return the label to display to cancel the action 1282 */ 1283 public CharSequence getCancelLabel() { 1284 return mCancelLabel; 1285 } 1286 } 1287 } 1288 1289 /** 1290 * Array of all {@link Action} structures attached to this notification by 1291 * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of 1292 * {@link android.service.notification.NotificationListenerService} that provide an alternative 1293 * interface for invoking actions. 1294 */ 1295 public Action[] actions; 1296 1297 /** 1298 * Replacement version of this notification whose content will be shown 1299 * in an insecure context such as atop a secure keyguard. See {@link #visibility} 1300 * and {@link #VISIBILITY_PUBLIC}. 1301 */ 1302 public Notification publicVersion; 1303 1304 /** 1305 * Constructs a Notification object with default values. 1306 * You might want to consider using {@link Builder} instead. 1307 */ 1308 public Notification() 1309 { 1310 this.when = System.currentTimeMillis(); 1311 this.priority = PRIORITY_DEFAULT; 1312 } 1313 1314 /** 1315 * @hide 1316 */ 1317 public Notification(Context context, int icon, CharSequence tickerText, long when, 1318 CharSequence contentTitle, CharSequence contentText, Intent contentIntent) 1319 { 1320 this.when = when; 1321 this.icon = icon; 1322 this.tickerText = tickerText; 1323 setLatestEventInfo(context, contentTitle, contentText, 1324 PendingIntent.getActivity(context, 0, contentIntent, 0)); 1325 } 1326 1327 /** 1328 * Constructs a Notification object with the information needed to 1329 * have a status bar icon without the standard expanded view. 1330 * 1331 * @param icon The resource id of the icon to put in the status bar. 1332 * @param tickerText The text that flows by in the status bar when the notification first 1333 * activates. 1334 * @param when The time to show in the time field. In the System.currentTimeMillis 1335 * timebase. 1336 * 1337 * @deprecated Use {@link Builder} instead. 1338 */ 1339 @Deprecated 1340 public Notification(int icon, CharSequence tickerText, long when) 1341 { 1342 this.icon = icon; 1343 this.tickerText = tickerText; 1344 this.when = when; 1345 } 1346 1347 /** 1348 * Unflatten the notification from a parcel. 1349 */ 1350 public Notification(Parcel parcel) 1351 { 1352 int version = parcel.readInt(); 1353 1354 when = parcel.readLong(); 1355 icon = parcel.readInt(); 1356 number = parcel.readInt(); 1357 if (parcel.readInt() != 0) { 1358 contentIntent = PendingIntent.CREATOR.createFromParcel(parcel); 1359 } 1360 if (parcel.readInt() != 0) { 1361 deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel); 1362 } 1363 if (parcel.readInt() != 0) { 1364 tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel); 1365 } 1366 if (parcel.readInt() != 0) { 1367 tickerView = RemoteViews.CREATOR.createFromParcel(parcel); 1368 } 1369 if (parcel.readInt() != 0) { 1370 contentView = RemoteViews.CREATOR.createFromParcel(parcel); 1371 } 1372 if (parcel.readInt() != 0) { 1373 largeIcon = Bitmap.CREATOR.createFromParcel(parcel); 1374 } 1375 defaults = parcel.readInt(); 1376 flags = parcel.readInt(); 1377 if (parcel.readInt() != 0) { 1378 sound = Uri.CREATOR.createFromParcel(parcel); 1379 } 1380 1381 audioStreamType = parcel.readInt(); 1382 if (parcel.readInt() != 0) { 1383 audioAttributes = AudioAttributes.CREATOR.createFromParcel(parcel); 1384 } 1385 vibrate = parcel.createLongArray(); 1386 ledARGB = parcel.readInt(); 1387 ledOnMS = parcel.readInt(); 1388 ledOffMS = parcel.readInt(); 1389 iconLevel = parcel.readInt(); 1390 1391 if (parcel.readInt() != 0) { 1392 fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel); 1393 } 1394 1395 priority = parcel.readInt(); 1396 1397 category = parcel.readString(); 1398 1399 mGroupKey = parcel.readString(); 1400 1401 mSortKey = parcel.readString(); 1402 1403 extras = parcel.readBundle(); // may be null 1404 1405 actions = parcel.createTypedArray(Action.CREATOR); // may be null 1406 1407 if (parcel.readInt() != 0) { 1408 bigContentView = RemoteViews.CREATOR.createFromParcel(parcel); 1409 } 1410 1411 if (parcel.readInt() != 0) { 1412 headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel); 1413 } 1414 1415 visibility = parcel.readInt(); 1416 1417 if (parcel.readInt() != 0) { 1418 publicVersion = Notification.CREATOR.createFromParcel(parcel); 1419 } 1420 1421 color = parcel.readInt(); 1422 } 1423 1424 @Override 1425 public Notification clone() { 1426 Notification that = new Notification(); 1427 cloneInto(that, true); 1428 return that; 1429 } 1430 1431 /** 1432 * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members 1433 * of this into that. 1434 * @hide 1435 */ 1436 public void cloneInto(Notification that, boolean heavy) { 1437 that.when = this.when; 1438 that.icon = this.icon; 1439 that.number = this.number; 1440 1441 // PendingIntents are global, so there's no reason (or way) to clone them. 1442 that.contentIntent = this.contentIntent; 1443 that.deleteIntent = this.deleteIntent; 1444 that.fullScreenIntent = this.fullScreenIntent; 1445 1446 if (this.tickerText != null) { 1447 that.tickerText = this.tickerText.toString(); 1448 } 1449 if (heavy && this.tickerView != null) { 1450 that.tickerView = this.tickerView.clone(); 1451 } 1452 if (heavy && this.contentView != null) { 1453 that.contentView = this.contentView.clone(); 1454 } 1455 if (heavy && this.largeIcon != null) { 1456 that.largeIcon = Bitmap.createBitmap(this.largeIcon); 1457 } 1458 that.iconLevel = this.iconLevel; 1459 that.sound = this.sound; // android.net.Uri is immutable 1460 that.audioStreamType = this.audioStreamType; 1461 if (this.audioAttributes != null) { 1462 that.audioAttributes = new AudioAttributes.Builder(this.audioAttributes).build(); 1463 } 1464 1465 final long[] vibrate = this.vibrate; 1466 if (vibrate != null) { 1467 final int N = vibrate.length; 1468 final long[] vib = that.vibrate = new long[N]; 1469 System.arraycopy(vibrate, 0, vib, 0, N); 1470 } 1471 1472 that.ledARGB = this.ledARGB; 1473 that.ledOnMS = this.ledOnMS; 1474 that.ledOffMS = this.ledOffMS; 1475 that.defaults = this.defaults; 1476 1477 that.flags = this.flags; 1478 1479 that.priority = this.priority; 1480 1481 that.category = this.category; 1482 1483 that.mGroupKey = this.mGroupKey; 1484 1485 that.mSortKey = this.mSortKey; 1486 1487 if (this.extras != null) { 1488 try { 1489 that.extras = new Bundle(this.extras); 1490 // will unparcel 1491 that.extras.size(); 1492 } catch (BadParcelableException e) { 1493 Log.e(TAG, "could not unparcel extras from notification: " + this, e); 1494 that.extras = null; 1495 } 1496 } 1497 1498 if (this.actions != null) { 1499 that.actions = new Action[this.actions.length]; 1500 for(int i=0; i<this.actions.length; i++) { 1501 that.actions[i] = this.actions[i].clone(); 1502 } 1503 } 1504 1505 if (heavy && this.bigContentView != null) { 1506 that.bigContentView = this.bigContentView.clone(); 1507 } 1508 1509 if (heavy && this.headsUpContentView != null) { 1510 that.headsUpContentView = this.headsUpContentView.clone(); 1511 } 1512 1513 that.visibility = this.visibility; 1514 1515 if (this.publicVersion != null) { 1516 that.publicVersion = new Notification(); 1517 this.publicVersion.cloneInto(that.publicVersion, heavy); 1518 } 1519 1520 that.color = this.color; 1521 1522 if (!heavy) { 1523 that.lightenPayload(); // will clean out extras 1524 } 1525 } 1526 1527 /** 1528 * Removes heavyweight parts of the Notification object for archival or for sending to 1529 * listeners when the full contents are not necessary. 1530 * @hide 1531 */ 1532 public final void lightenPayload() { 1533 tickerView = null; 1534 contentView = null; 1535 bigContentView = null; 1536 headsUpContentView = null; 1537 largeIcon = null; 1538 if (extras != null) { 1539 extras.remove(Notification.EXTRA_LARGE_ICON); 1540 extras.remove(Notification.EXTRA_LARGE_ICON_BIG); 1541 extras.remove(Notification.EXTRA_PICTURE); 1542 extras.remove(Notification.EXTRA_BIG_TEXT); 1543 // Prevent light notifications from being rebuilt. 1544 extras.remove(Builder.EXTRA_NEEDS_REBUILD); 1545 } 1546 } 1547 1548 /** 1549 * Make sure this CharSequence is safe to put into a bundle, which basically 1550 * means it had better not be some custom Parcelable implementation. 1551 * @hide 1552 */ 1553 public static CharSequence safeCharSequence(CharSequence cs) { 1554 if (cs == null) return cs; 1555 if (cs.length() > MAX_CHARSEQUENCE_LENGTH) { 1556 cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH); 1557 } 1558 if (cs instanceof Parcelable) { 1559 Log.e(TAG, "warning: " + cs.getClass().getCanonicalName() 1560 + " instance is a custom Parcelable and not allowed in Notification"); 1561 return cs.toString(); 1562 } 1563 1564 return cs; 1565 } 1566 1567 public int describeContents() { 1568 return 0; 1569 } 1570 1571 /** 1572 * Flatten this notification from a parcel. 1573 */ 1574 public void writeToParcel(Parcel parcel, int flags) 1575 { 1576 parcel.writeInt(1); 1577 1578 parcel.writeLong(when); 1579 parcel.writeInt(icon); 1580 parcel.writeInt(number); 1581 if (contentIntent != null) { 1582 parcel.writeInt(1); 1583 contentIntent.writeToParcel(parcel, 0); 1584 } else { 1585 parcel.writeInt(0); 1586 } 1587 if (deleteIntent != null) { 1588 parcel.writeInt(1); 1589 deleteIntent.writeToParcel(parcel, 0); 1590 } else { 1591 parcel.writeInt(0); 1592 } 1593 if (tickerText != null) { 1594 parcel.writeInt(1); 1595 TextUtils.writeToParcel(tickerText, parcel, flags); 1596 } else { 1597 parcel.writeInt(0); 1598 } 1599 if (tickerView != null) { 1600 parcel.writeInt(1); 1601 tickerView.writeToParcel(parcel, 0); 1602 } else { 1603 parcel.writeInt(0); 1604 } 1605 if (contentView != null) { 1606 parcel.writeInt(1); 1607 contentView.writeToParcel(parcel, 0); 1608 } else { 1609 parcel.writeInt(0); 1610 } 1611 if (largeIcon != null) { 1612 parcel.writeInt(1); 1613 largeIcon.writeToParcel(parcel, 0); 1614 } else { 1615 parcel.writeInt(0); 1616 } 1617 1618 parcel.writeInt(defaults); 1619 parcel.writeInt(this.flags); 1620 1621 if (sound != null) { 1622 parcel.writeInt(1); 1623 sound.writeToParcel(parcel, 0); 1624 } else { 1625 parcel.writeInt(0); 1626 } 1627 parcel.writeInt(audioStreamType); 1628 1629 if (audioAttributes != null) { 1630 parcel.writeInt(1); 1631 audioAttributes.writeToParcel(parcel, 0); 1632 } else { 1633 parcel.writeInt(0); 1634 } 1635 1636 parcel.writeLongArray(vibrate); 1637 parcel.writeInt(ledARGB); 1638 parcel.writeInt(ledOnMS); 1639 parcel.writeInt(ledOffMS); 1640 parcel.writeInt(iconLevel); 1641 1642 if (fullScreenIntent != null) { 1643 parcel.writeInt(1); 1644 fullScreenIntent.writeToParcel(parcel, 0); 1645 } else { 1646 parcel.writeInt(0); 1647 } 1648 1649 parcel.writeInt(priority); 1650 1651 parcel.writeString(category); 1652 1653 parcel.writeString(mGroupKey); 1654 1655 parcel.writeString(mSortKey); 1656 1657 parcel.writeBundle(extras); // null ok 1658 1659 parcel.writeTypedArray(actions, 0); // null ok 1660 1661 if (bigContentView != null) { 1662 parcel.writeInt(1); 1663 bigContentView.writeToParcel(parcel, 0); 1664 } else { 1665 parcel.writeInt(0); 1666 } 1667 1668 if (headsUpContentView != null) { 1669 parcel.writeInt(1); 1670 headsUpContentView.writeToParcel(parcel, 0); 1671 } else { 1672 parcel.writeInt(0); 1673 } 1674 1675 parcel.writeInt(visibility); 1676 1677 if (publicVersion != null) { 1678 parcel.writeInt(1); 1679 publicVersion.writeToParcel(parcel, 0); 1680 } else { 1681 parcel.writeInt(0); 1682 } 1683 1684 parcel.writeInt(color); 1685 } 1686 1687 /** 1688 * Parcelable.Creator that instantiates Notification objects 1689 */ 1690 public static final Parcelable.Creator<Notification> CREATOR 1691 = new Parcelable.Creator<Notification>() 1692 { 1693 public Notification createFromParcel(Parcel parcel) 1694 { 1695 return new Notification(parcel); 1696 } 1697 1698 public Notification[] newArray(int size) 1699 { 1700 return new Notification[size]; 1701 } 1702 }; 1703 1704 /** 1705 * Sets the {@link #contentView} field to be a view with the standard "Latest Event" 1706 * layout. 1707 * 1708 * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields 1709 * in the view.</p> 1710 * @param context The context for your application / activity. 1711 * @param contentTitle The title that goes in the expanded entry. 1712 * @param contentText The text that goes in the expanded entry. 1713 * @param contentIntent The intent to launch when the user clicks the expanded notification. 1714 * If this is an activity, it must include the 1715 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires 1716 * that you take care of task management as described in the 1717 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back 1718 * Stack</a> document. 1719 * 1720 * @deprecated Use {@link Builder} instead. 1721 */ 1722 @Deprecated 1723 public void setLatestEventInfo(Context context, 1724 CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) { 1725 Notification.Builder builder = new Notification.Builder(context); 1726 1727 // First, ensure that key pieces of information that may have been set directly 1728 // are preserved 1729 builder.setWhen(this.when); 1730 builder.setSmallIcon(this.icon); 1731 builder.setPriority(this.priority); 1732 builder.setTicker(this.tickerText); 1733 builder.setNumber(this.number); 1734 builder.setColor(this.color); 1735 builder.mFlags = this.flags; 1736 builder.setSound(this.sound, this.audioStreamType); 1737 builder.setDefaults(this.defaults); 1738 builder.setVibrate(this.vibrate); 1739 builder.setDeleteIntent(this.deleteIntent); 1740 1741 // now apply the latestEventInfo fields 1742 if (contentTitle != null) { 1743 builder.setContentTitle(contentTitle); 1744 } 1745 if (contentText != null) { 1746 builder.setContentText(contentText); 1747 } 1748 builder.setContentIntent(contentIntent); 1749 builder.buildInto(this); 1750 } 1751 1752 @Override 1753 public String toString() { 1754 StringBuilder sb = new StringBuilder(); 1755 sb.append("Notification(pri="); 1756 sb.append(priority); 1757 sb.append(" contentView="); 1758 if (contentView != null) { 1759 sb.append(contentView.getPackage()); 1760 sb.append("/0x"); 1761 sb.append(Integer.toHexString(contentView.getLayoutId())); 1762 } else { 1763 sb.append("null"); 1764 } 1765 sb.append(" vibrate="); 1766 if ((this.defaults & DEFAULT_VIBRATE) != 0) { 1767 sb.append("default"); 1768 } else if (this.vibrate != null) { 1769 int N = this.vibrate.length-1; 1770 sb.append("["); 1771 for (int i=0; i<N; i++) { 1772 sb.append(this.vibrate[i]); 1773 sb.append(','); 1774 } 1775 if (N != -1) { 1776 sb.append(this.vibrate[N]); 1777 } 1778 sb.append("]"); 1779 } else { 1780 sb.append("null"); 1781 } 1782 sb.append(" sound="); 1783 if ((this.defaults & DEFAULT_SOUND) != 0) { 1784 sb.append("default"); 1785 } else if (this.sound != null) { 1786 sb.append(this.sound.toString()); 1787 } else { 1788 sb.append("null"); 1789 } 1790 sb.append(" defaults=0x"); 1791 sb.append(Integer.toHexString(this.defaults)); 1792 sb.append(" flags=0x"); 1793 sb.append(Integer.toHexString(this.flags)); 1794 sb.append(String.format(" color=0x%08x", this.color)); 1795 if (this.category != null) { 1796 sb.append(" category="); 1797 sb.append(this.category); 1798 } 1799 if (this.mGroupKey != null) { 1800 sb.append(" groupKey="); 1801 sb.append(this.mGroupKey); 1802 } 1803 if (this.mSortKey != null) { 1804 sb.append(" sortKey="); 1805 sb.append(this.mSortKey); 1806 } 1807 if (actions != null) { 1808 sb.append(" actions="); 1809 sb.append(actions.length); 1810 } 1811 sb.append(" vis="); 1812 sb.append(visibilityToString(this.visibility)); 1813 if (this.publicVersion != null) { 1814 sb.append(" publicVersion="); 1815 sb.append(publicVersion.toString()); 1816 } 1817 sb.append(")"); 1818 return sb.toString(); 1819 } 1820 1821 /** 1822 * {@hide} 1823 */ 1824 public static String visibilityToString(int vis) { 1825 switch (vis) { 1826 case VISIBILITY_PRIVATE: 1827 return "PRIVATE"; 1828 case VISIBILITY_PUBLIC: 1829 return "PUBLIC"; 1830 case VISIBILITY_SECRET: 1831 return "SECRET"; 1832 default: 1833 return "UNKNOWN(" + String.valueOf(vis) + ")"; 1834 } 1835 } 1836 1837 /** 1838 * @hide 1839 */ 1840 public boolean isValid() { 1841 // Would like to check for icon!=0 here, too, but NotificationManagerService accepts that 1842 // for legacy reasons. 1843 return contentView != null || extras.getBoolean(Builder.EXTRA_REBUILD_CONTENT_VIEW); 1844 } 1845 1846 /** 1847 * @hide 1848 */ 1849 public boolean isGroupSummary() { 1850 return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) != 0; 1851 } 1852 1853 /** 1854 * @hide 1855 */ 1856 public boolean isGroupChild() { 1857 return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) == 0; 1858 } 1859 1860 /** 1861 * Builder class for {@link Notification} objects. 1862 * 1863 * Provides a convenient way to set the various fields of a {@link Notification} and generate 1864 * content views using the platform's notification layout template. If your app supports 1865 * versions of Android as old as API level 4, you can instead use 1866 * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder}, 1867 * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support 1868 * library</a>. 1869 * 1870 * <p>Example: 1871 * 1872 * <pre class="prettyprint"> 1873 * Notification noti = new Notification.Builder(mContext) 1874 * .setContentTitle("New mail from " + sender.toString()) 1875 * .setContentText(subject) 1876 * .setSmallIcon(R.drawable.new_mail) 1877 * .setLargeIcon(aBitmap) 1878 * .build(); 1879 * </pre> 1880 */ 1881 public static class Builder { 1882 private static final int MAX_ACTION_BUTTONS = 3; 1883 private static final float LARGE_TEXT_SCALE = 1.3f; 1884 1885 /** 1886 * @hide 1887 */ 1888 public static final String EXTRA_NEEDS_REBUILD = "android.rebuild"; 1889 1890 /** 1891 * @hide 1892 */ 1893 public static final String EXTRA_REBUILD_LARGE_ICON = "android.rebuild.largeIcon"; 1894 /** 1895 * @hide 1896 */ 1897 public static final String EXTRA_REBUILD_CONTENT_VIEW = "android.rebuild.contentView"; 1898 /** 1899 * @hide 1900 */ 1901 public static final String EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT = 1902 "android.rebuild.contentViewActionCount"; 1903 /** 1904 * @hide 1905 */ 1906 public static final String EXTRA_REBUILD_BIG_CONTENT_VIEW 1907 = "android.rebuild.bigView"; 1908 /** 1909 * @hide 1910 */ 1911 public static final String EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT 1912 = "android.rebuild.bigViewActionCount"; 1913 /** 1914 * @hide 1915 */ 1916 public static final String EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW 1917 = "android.rebuild.hudView"; 1918 /** 1919 * @hide 1920 */ 1921 public static final String EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT 1922 = "android.rebuild.hudViewActionCount"; 1923 1924 /** 1925 * The ApplicationInfo of the package that created the notification, used to create 1926 * a context to rebuild the notification via a Builder. 1927 * @hide 1928 */ 1929 private static final String EXTRA_REBUILD_CONTEXT_APPLICATION_INFO = 1930 "android.rebuild.applicationInfo"; 1931 1932 // Whether to enable stripping (at post time) & rebuilding (at listener receive time) of 1933 // memory intensive resources. 1934 private static final boolean STRIP_AND_REBUILD = true; 1935 1936 private Context mContext; 1937 1938 private long mWhen; 1939 private int mSmallIcon; 1940 private int mSmallIconLevel; 1941 private int mNumber; 1942 private CharSequence mContentTitle; 1943 private CharSequence mContentText; 1944 private CharSequence mContentInfo; 1945 private CharSequence mSubText; 1946 private PendingIntent mContentIntent; 1947 private RemoteViews mContentView; 1948 private PendingIntent mDeleteIntent; 1949 private PendingIntent mFullScreenIntent; 1950 private CharSequence mTickerText; 1951 private RemoteViews mTickerView; 1952 private Bitmap mLargeIcon; 1953 private Uri mSound; 1954 private int mAudioStreamType; 1955 private AudioAttributes mAudioAttributes; 1956 private long[] mVibrate; 1957 private int mLedArgb; 1958 private int mLedOnMs; 1959 private int mLedOffMs; 1960 private int mDefaults; 1961 private int mFlags; 1962 private int mProgressMax; 1963 private int mProgress; 1964 private boolean mProgressIndeterminate; 1965 private String mCategory; 1966 private String mGroupKey; 1967 private String mSortKey; 1968 private Bundle mExtras; 1969 private int mPriority; 1970 private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS); 1971 private boolean mUseChronometer; 1972 private Style mStyle; 1973 private boolean mShowWhen = true; 1974 private int mVisibility = VISIBILITY_PRIVATE; 1975 private Notification mPublicVersion = null; 1976 private final NotificationColorUtil mColorUtil; 1977 private ArrayList<String> mPeople; 1978 private int mColor = COLOR_DEFAULT; 1979 1980 /** 1981 * The user that built the notification originally. 1982 */ 1983 private int mOriginatingUserId; 1984 1985 /** 1986 * Contains extras related to rebuilding during the build phase. 1987 */ 1988 private Bundle mRebuildBundle = new Bundle(); 1989 /** 1990 * Contains the notification to rebuild when this Builder is in "rebuild" mode. 1991 * Null otherwise. 1992 */ 1993 private Notification mRebuildNotification = null; 1994 1995 /** 1996 * Whether the build notification has three lines. This is used to make the top padding for 1997 * both the contracted and expanded layout consistent. 1998 * 1999 * <p> 2000 * This field is only valid during the build phase. 2001 */ 2002 private boolean mHasThreeLines; 2003 2004 /** 2005 * Constructs a new Builder with the defaults: 2006 * 2007 2008 * <table> 2009 * <tr><th align=right>priority</th> 2010 * <td>{@link #PRIORITY_DEFAULT}</td></tr> 2011 * <tr><th align=right>when</th> 2012 * <td>now ({@link System#currentTimeMillis()})</td></tr> 2013 * <tr><th align=right>audio stream</th> 2014 * <td>{@link #STREAM_DEFAULT}</td></tr> 2015 * </table> 2016 * 2017 2018 * @param context 2019 * A {@link Context} that will be used by the Builder to construct the 2020 * RemoteViews. The Context will not be held past the lifetime of this Builder 2021 * object. 2022 */ 2023 public Builder(Context context) { 2024 /* 2025 * Important compatibility note! 2026 * Some apps out in the wild create a Notification.Builder in their Activity subclass 2027 * constructor for later use. At this point Activities - themselves subclasses of 2028 * ContextWrapper - do not have their inner Context populated yet. This means that 2029 * any calls to Context methods from within this constructor can cause NPEs in existing 2030 * apps. Any data populated from mContext should therefore be populated lazily to 2031 * preserve compatibility. 2032 */ 2033 mContext = context; 2034 2035 // Set defaults to match the defaults of a Notification 2036 mWhen = System.currentTimeMillis(); 2037 mAudioStreamType = STREAM_DEFAULT; 2038 mAudioAttributes = AUDIO_ATTRIBUTES_DEFAULT; 2039 mPriority = PRIORITY_DEFAULT; 2040 mPeople = new ArrayList<String>(); 2041 2042 mColorUtil = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.LOLLIPOP ? 2043 NotificationColorUtil.getInstance(mContext) : null; 2044 } 2045 2046 /** 2047 * Creates a Builder for rebuilding the given Notification. 2048 * <p> 2049 * Call {@link #rebuild()} to retrieve the rebuilt version of 'n'. 2050 */ 2051 private Builder(Context context, Notification n) { 2052 this(context); 2053 mRebuildNotification = n; 2054 restoreFromNotification(n); 2055 2056 Style style = null; 2057 Bundle extras = n.extras; 2058 String templateClass = extras.getString(EXTRA_TEMPLATE); 2059 if (!TextUtils.isEmpty(templateClass)) { 2060 Class<? extends Style> styleClass = getNotificationStyleClass(templateClass); 2061 if (styleClass == null) { 2062 Log.d(TAG, "Unknown style class: " + styleClass); 2063 return; 2064 } 2065 2066 try { 2067 Constructor<? extends Style> constructor = styleClass.getConstructor(); 2068 style = constructor.newInstance(); 2069 style.restoreFromExtras(extras); 2070 } catch (Throwable t) { 2071 Log.e(TAG, "Could not create Style", t); 2072 return; 2073 } 2074 } 2075 if (style != null) { 2076 setStyle(style); 2077 } 2078 } 2079 2080 /** 2081 * Add a timestamp pertaining to the notification (usually the time the event occurred). 2082 * It will be shown in the notification content view by default; use 2083 * {@link #setShowWhen(boolean) setShowWhen} to control this. 2084 * 2085 * @see Notification#when 2086 */ 2087 public Builder setWhen(long when) { 2088 mWhen = when; 2089 return this; 2090 } 2091 2092 /** 2093 * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown 2094 * in the content view. 2095 */ 2096 public Builder setShowWhen(boolean show) { 2097 mShowWhen = show; 2098 return this; 2099 } 2100 2101 /** 2102 * Show the {@link Notification#when} field as a stopwatch. 2103 * 2104 * Instead of presenting <code>when</code> as a timestamp, the notification will show an 2105 * automatically updating display of the minutes and seconds since <code>when</code>. 2106 * 2107 * Useful when showing an elapsed time (like an ongoing phone call). 2108 * 2109 * @see android.widget.Chronometer 2110 * @see Notification#when 2111 */ 2112 public Builder setUsesChronometer(boolean b) { 2113 mUseChronometer = b; 2114 return this; 2115 } 2116 2117 /** 2118 * Set the small icon resource, which will be used to represent the notification in the 2119 * status bar. 2120 * 2121 2122 * The platform template for the expanded view will draw this icon in the left, unless a 2123 * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small 2124 * icon will be moved to the right-hand side. 2125 * 2126 2127 * @param icon 2128 * A resource ID in the application's package of the drawable to use. 2129 * @see Notification#icon 2130 */ 2131 public Builder setSmallIcon(int icon) { 2132 mSmallIcon = icon; 2133 return this; 2134 } 2135 2136 /** 2137 * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional 2138 * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable 2139 * LevelListDrawable}. 2140 * 2141 * @param icon A resource ID in the application's package of the drawable to use. 2142 * @param level The level to use for the icon. 2143 * 2144 * @see Notification#icon 2145 * @see Notification#iconLevel 2146 */ 2147 public Builder setSmallIcon(int icon, int level) { 2148 mSmallIcon = icon; 2149 mSmallIconLevel = level; 2150 return this; 2151 } 2152 2153 /** 2154 * Set the first line of text in the platform notification template. 2155 */ 2156 public Builder setContentTitle(CharSequence title) { 2157 mContentTitle = safeCharSequence(title); 2158 return this; 2159 } 2160 2161 /** 2162 * Set the second line of text in the platform notification template. 2163 */ 2164 public Builder setContentText(CharSequence text) { 2165 mContentText = safeCharSequence(text); 2166 return this; 2167 } 2168 2169 /** 2170 * Set the third line of text in the platform notification template. 2171 * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the 2172 * same location in the standard template. 2173 */ 2174 public Builder setSubText(CharSequence text) { 2175 mSubText = safeCharSequence(text); 2176 return this; 2177 } 2178 2179 /** 2180 * Set the large number at the right-hand side of the notification. This is 2181 * equivalent to setContentInfo, although it might show the number in a different 2182 * font size for readability. 2183 */ 2184 public Builder setNumber(int number) { 2185 mNumber = number; 2186 return this; 2187 } 2188 2189 /** 2190 * A small piece of additional information pertaining to this notification. 2191 * 2192 * The platform template will draw this on the last line of the notification, at the far 2193 * right (to the right of a smallIcon if it has been placed there). 2194 */ 2195 public Builder setContentInfo(CharSequence info) { 2196 mContentInfo = safeCharSequence(info); 2197 return this; 2198 } 2199 2200 /** 2201 * Set the progress this notification represents. 2202 * 2203 * The platform template will represent this using a {@link ProgressBar}. 2204 */ 2205 public Builder setProgress(int max, int progress, boolean indeterminate) { 2206 mProgressMax = max; 2207 mProgress = progress; 2208 mProgressIndeterminate = indeterminate; 2209 return this; 2210 } 2211 2212 /** 2213 * Supply a custom RemoteViews to use instead of the platform template. 2214 * 2215 * @see Notification#contentView 2216 */ 2217 public Builder setContent(RemoteViews views) { 2218 mContentView = views; 2219 return this; 2220 } 2221 2222 /** 2223 * Supply a {@link PendingIntent} to be sent when the notification is clicked. 2224 * 2225 * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you 2226 * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use 2227 * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)} 2228 * to assign PendingIntents to individual views in that custom layout (i.e., to create 2229 * clickable buttons inside the notification view). 2230 * 2231 * @see Notification#contentIntent Notification.contentIntent 2232 */ 2233 public Builder setContentIntent(PendingIntent intent) { 2234 mContentIntent = intent; 2235 return this; 2236 } 2237 2238 /** 2239 * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user. 2240 * 2241 * @see Notification#deleteIntent 2242 */ 2243 public Builder setDeleteIntent(PendingIntent intent) { 2244 mDeleteIntent = intent; 2245 return this; 2246 } 2247 2248 /** 2249 * An intent to launch instead of posting the notification to the status bar. 2250 * Only for use with extremely high-priority notifications demanding the user's 2251 * <strong>immediate</strong> attention, such as an incoming phone call or 2252 * alarm clock that the user has explicitly set to a particular time. 2253 * If this facility is used for something else, please give the user an option 2254 * to turn it off and use a normal notification, as this can be extremely 2255 * disruptive. 2256 * 2257 * <p> 2258 * The system UI may choose to display a heads-up notification, instead of 2259 * launching this intent, while the user is using the device. 2260 * </p> 2261 * 2262 * @param intent The pending intent to launch. 2263 * @param highPriority Passing true will cause this notification to be sent 2264 * even if other notifications are suppressed. 2265 * 2266 * @see Notification#fullScreenIntent 2267 */ 2268 public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) { 2269 mFullScreenIntent = intent; 2270 setFlag(FLAG_HIGH_PRIORITY, highPriority); 2271 return this; 2272 } 2273 2274 /** 2275 * Set the "ticker" text which is sent to accessibility services. 2276 * 2277 * @see Notification#tickerText 2278 */ 2279 public Builder setTicker(CharSequence tickerText) { 2280 mTickerText = safeCharSequence(tickerText); 2281 return this; 2282 } 2283 2284 /** 2285 * Obsolete version of {@link #setTicker(CharSequence)}. 2286 * 2287 */ 2288 @Deprecated 2289 public Builder setTicker(CharSequence tickerText, RemoteViews views) { 2290 mTickerText = safeCharSequence(tickerText); 2291 mTickerView = views; // we'll save it for you anyway 2292 return this; 2293 } 2294 2295 /** 2296 * Add a large icon to the notification (and the ticker on some devices). 2297 * 2298 * In the platform template, this image will be shown on the left of the notification view 2299 * in place of the {@link #setSmallIcon(int) small icon} (which will move to the right side). 2300 * 2301 * @see Notification#largeIcon 2302 */ 2303 public Builder setLargeIcon(Bitmap icon) { 2304 mLargeIcon = icon; 2305 return this; 2306 } 2307 2308 /** 2309 * Set the sound to play. 2310 * 2311 * It will be played using the {@link #AUDIO_ATTRIBUTES_DEFAULT default audio attributes} 2312 * for notifications. 2313 * 2314 * <p> 2315 * A notification that is noisy is more likely to be presented as a heads-up notification. 2316 * </p> 2317 * 2318 * @see Notification#sound 2319 */ 2320 public Builder setSound(Uri sound) { 2321 mSound = sound; 2322 mAudioAttributes = AUDIO_ATTRIBUTES_DEFAULT; 2323 return this; 2324 } 2325 2326 /** 2327 * Set the sound to play, along with a specific stream on which to play it. 2328 * 2329 * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants. 2330 * 2331 * <p> 2332 * A notification that is noisy is more likely to be presented as a heads-up notification. 2333 * </p> 2334 * @deprecated use {@link #setSound(Uri, AudioAttributes)} instead. 2335 * @see Notification#sound 2336 */ 2337 @Deprecated 2338 public Builder setSound(Uri sound, int streamType) { 2339 mSound = sound; 2340 mAudioStreamType = streamType; 2341 return this; 2342 } 2343 2344 /** 2345 * Set the sound to play, along with specific {@link AudioAttributes audio attributes} to 2346 * use during playback. 2347 * 2348 * <p> 2349 * A notification that is noisy is more likely to be presented as a heads-up notification. 2350 * </p> 2351 * 2352 * @see Notification#sound 2353 */ 2354 public Builder setSound(Uri sound, AudioAttributes audioAttributes) { 2355 mSound = sound; 2356 mAudioAttributes = audioAttributes; 2357 return this; 2358 } 2359 2360 /** 2361 * Set the vibration pattern to use. 2362 * 2363 * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the 2364 * <code>pattern</code> parameter. 2365 * 2366 * <p> 2367 * A notification that vibrates is more likely to be presented as a heads-up notification. 2368 * </p> 2369 * 2370 * @see Notification#vibrate 2371 */ 2372 public Builder setVibrate(long[] pattern) { 2373 mVibrate = pattern; 2374 return this; 2375 } 2376 2377 /** 2378 * Set the desired color for the indicator LED on the device, as well as the 2379 * blink duty cycle (specified in milliseconds). 2380 * 2381 2382 * Not all devices will honor all (or even any) of these values. 2383 * 2384 2385 * @see Notification#ledARGB 2386 * @see Notification#ledOnMS 2387 * @see Notification#ledOffMS 2388 */ 2389 public Builder setLights(int argb, int onMs, int offMs) { 2390 mLedArgb = argb; 2391 mLedOnMs = onMs; 2392 mLedOffMs = offMs; 2393 return this; 2394 } 2395 2396 /** 2397 * Set whether this is an "ongoing" notification. 2398 * 2399 2400 * Ongoing notifications cannot be dismissed by the user, so your application or service 2401 * must take care of canceling them. 2402 * 2403 2404 * They are typically used to indicate a background task that the user is actively engaged 2405 * with (e.g., playing music) or is pending in some way and therefore occupying the device 2406 * (e.g., a file download, sync operation, active network connection). 2407 * 2408 2409 * @see Notification#FLAG_ONGOING_EVENT 2410 * @see Service#setForeground(boolean) 2411 */ 2412 public Builder setOngoing(boolean ongoing) { 2413 setFlag(FLAG_ONGOING_EVENT, ongoing); 2414 return this; 2415 } 2416 2417 /** 2418 * Set this flag if you would only like the sound, vibrate 2419 * and ticker to be played if the notification is not already showing. 2420 * 2421 * @see Notification#FLAG_ONLY_ALERT_ONCE 2422 */ 2423 public Builder setOnlyAlertOnce(boolean onlyAlertOnce) { 2424 setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce); 2425 return this; 2426 } 2427 2428 /** 2429 * Make this notification automatically dismissed when the user touches it. The 2430 * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens. 2431 * 2432 * @see Notification#FLAG_AUTO_CANCEL 2433 */ 2434 public Builder setAutoCancel(boolean autoCancel) { 2435 setFlag(FLAG_AUTO_CANCEL, autoCancel); 2436 return this; 2437 } 2438 2439 /** 2440 * Set whether or not this notification should not bridge to other devices. 2441 * 2442 * <p>Some notifications can be bridged to other devices for remote display. 2443 * This hint can be set to recommend this notification not be bridged. 2444 */ 2445 public Builder setLocalOnly(boolean localOnly) { 2446 setFlag(FLAG_LOCAL_ONLY, localOnly); 2447 return this; 2448 } 2449 2450 /** 2451 * Set which notification properties will be inherited from system defaults. 2452 * <p> 2453 * The value should be one or more of the following fields combined with 2454 * bitwise-or: 2455 * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. 2456 * <p> 2457 * For all default values, use {@link #DEFAULT_ALL}. 2458 */ 2459 public Builder setDefaults(int defaults) { 2460 mDefaults = defaults; 2461 return this; 2462 } 2463 2464 /** 2465 * Set the priority of this notification. 2466 * 2467 * @see Notification#priority 2468 */ 2469 public Builder setPriority(@Priority int pri) { 2470 mPriority = pri; 2471 return this; 2472 } 2473 2474 /** 2475 * Set the notification category. 2476 * 2477 * @see Notification#category 2478 */ 2479 public Builder setCategory(String category) { 2480 mCategory = category; 2481 return this; 2482 } 2483 2484 /** 2485 * Add a person that is relevant to this notification. 2486 * 2487 * <P> 2488 * Depending on user preferences, this annotation may allow the notification to pass 2489 * through interruption filters, and to appear more prominently in the user interface. 2490 * </P> 2491 * 2492 * <P> 2493 * The person should be specified by the {@code String} representation of a 2494 * {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}. 2495 * </P> 2496 * 2497 * <P>The system will also attempt to resolve {@code mailto:} and {@code tel:} schema 2498 * URIs. The path part of these URIs must exist in the contacts database, in the 2499 * appropriate column, or the reference will be discarded as invalid. Telephone schema 2500 * URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}. 2501 * </P> 2502 * 2503 * @param uri A URI for the person. 2504 * @see Notification#EXTRA_PEOPLE 2505 */ 2506 public Builder addPerson(String uri) { 2507 mPeople.add(uri); 2508 return this; 2509 } 2510 2511 /** 2512 * Set this notification to be part of a group of notifications sharing the same key. 2513 * Grouped notifications may display in a cluster or stack on devices which 2514 * support such rendering. 2515 * 2516 * <p>To make this notification the summary for its group, also call 2517 * {@link #setGroupSummary}. A sort order can be specified for group members by using 2518 * {@link #setSortKey}. 2519 * @param groupKey The group key of the group. 2520 * @return this object for method chaining 2521 */ 2522 public Builder setGroup(String groupKey) { 2523 mGroupKey = groupKey; 2524 return this; 2525 } 2526 2527 /** 2528 * Set this notification to be the group summary for a group of notifications. 2529 * Grouped notifications may display in a cluster or stack on devices which 2530 * support such rendering. Requires a group key also be set using {@link #setGroup}. 2531 * @param isGroupSummary Whether this notification should be a group summary. 2532 * @return this object for method chaining 2533 */ 2534 public Builder setGroupSummary(boolean isGroupSummary) { 2535 setFlag(FLAG_GROUP_SUMMARY, isGroupSummary); 2536 return this; 2537 } 2538 2539 /** 2540 * Set a sort key that orders this notification among other notifications from the 2541 * same package. This can be useful if an external sort was already applied and an app 2542 * would like to preserve this. Notifications will be sorted lexicographically using this 2543 * value, although providing different priorities in addition to providing sort key may 2544 * cause this value to be ignored. 2545 * 2546 * <p>This sort key can also be used to order members of a notification group. See 2547 * {@link #setGroup}. 2548 * 2549 * @see String#compareTo(String) 2550 */ 2551 public Builder setSortKey(String sortKey) { 2552 mSortKey = sortKey; 2553 return this; 2554 } 2555 2556 /** 2557 * Merge additional metadata into this notification. 2558 * 2559 * <p>Values within the Bundle will replace existing extras values in this Builder. 2560 * 2561 * @see Notification#extras 2562 */ 2563 public Builder addExtras(Bundle extras) { 2564 if (extras != null) { 2565 if (mExtras == null) { 2566 mExtras = new Bundle(extras); 2567 } else { 2568 mExtras.putAll(extras); 2569 } 2570 } 2571 return this; 2572 } 2573 2574 /** 2575 * Set metadata for this notification. 2576 * 2577 * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's 2578 * current contents are copied into the Notification each time {@link #build()} is 2579 * called. 2580 * 2581 * <p>Replaces any existing extras values with those from the provided Bundle. 2582 * Use {@link #addExtras} to merge in metadata instead. 2583 * 2584 * @see Notification#extras 2585 */ 2586 public Builder setExtras(Bundle extras) { 2587 mExtras = extras; 2588 return this; 2589 } 2590 2591 /** 2592 * Get the current metadata Bundle used by this notification Builder. 2593 * 2594 * <p>The returned Bundle is shared with this Builder. 2595 * 2596 * <p>The current contents of this Bundle are copied into the Notification each time 2597 * {@link #build()} is called. 2598 * 2599 * @see Notification#extras 2600 */ 2601 public Bundle getExtras() { 2602 if (mExtras == null) { 2603 mExtras = new Bundle(); 2604 } 2605 return mExtras; 2606 } 2607 2608 /** 2609 * Add an action to this notification. Actions are typically displayed by 2610 * the system as a button adjacent to the notification content. 2611 * <p> 2612 * Every action must have an icon (32dp square and matching the 2613 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 2614 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 2615 * <p> 2616 * A notification in its expanded form can display up to 3 actions, from left to right in 2617 * the order they were added. Actions will not be displayed when the notification is 2618 * collapsed, however, so be sure that any essential functions may be accessed by the user 2619 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 2620 * 2621 * @param icon Resource ID of a drawable that represents the action. 2622 * @param title Text describing the action. 2623 * @param intent PendingIntent to be fired when the action is invoked. 2624 */ 2625 public Builder addAction(int icon, CharSequence title, PendingIntent intent) { 2626 mActions.add(new Action(icon, safeCharSequence(title), intent)); 2627 return this; 2628 } 2629 2630 /** 2631 * Add an action to this notification. Actions are typically displayed by 2632 * the system as a button adjacent to the notification content. 2633 * <p> 2634 * Every action must have an icon (32dp square and matching the 2635 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 2636 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 2637 * <p> 2638 * A notification in its expanded form can display up to 3 actions, from left to right in 2639 * the order they were added. Actions will not be displayed when the notification is 2640 * collapsed, however, so be sure that any essential functions may be accessed by the user 2641 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 2642 * 2643 * @param action The action to add. 2644 */ 2645 public Builder addAction(Action action) { 2646 mActions.add(action); 2647 return this; 2648 } 2649 2650 /** 2651 * Add a rich notification style to be applied at build time. 2652 * 2653 * @param style Object responsible for modifying the notification style. 2654 */ 2655 public Builder setStyle(Style style) { 2656 if (mStyle != style) { 2657 mStyle = style; 2658 if (mStyle != null) { 2659 mStyle.setBuilder(this); 2660 } 2661 } 2662 return this; 2663 } 2664 2665 /** 2666 * Specify the value of {@link #visibility}. 2667 * 2668 * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default), 2669 * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}. 2670 * 2671 * @return The same Builder. 2672 */ 2673 public Builder setVisibility(int visibility) { 2674 mVisibility = visibility; 2675 return this; 2676 } 2677 2678 /** 2679 * Supply a replacement Notification whose contents should be shown in insecure contexts 2680 * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}. 2681 * @param n A replacement notification, presumably with some or all info redacted. 2682 * @return The same Builder. 2683 */ 2684 public Builder setPublicVersion(Notification n) { 2685 mPublicVersion = n; 2686 return this; 2687 } 2688 2689 /** 2690 * Apply an extender to this notification builder. Extenders may be used to add 2691 * metadata or change options on this builder. 2692 */ 2693 public Builder extend(Extender extender) { 2694 extender.extend(this); 2695 return this; 2696 } 2697 2698 private void setFlag(int mask, boolean value) { 2699 if (value) { 2700 mFlags |= mask; 2701 } else { 2702 mFlags &= ~mask; 2703 } 2704 } 2705 2706 /** 2707 * Sets {@link Notification#color}. 2708 * 2709 * @param argb The accent color to use 2710 * 2711 * @return The same Builder. 2712 */ 2713 public Builder setColor(int argb) { 2714 mColor = argb; 2715 return this; 2716 } 2717 2718 private Drawable getProfileBadgeDrawable() { 2719 // Note: This assumes that the current user can read the profile badge of the 2720 // originating user. 2721 return mContext.getPackageManager().getUserBadgeForDensity( 2722 new UserHandle(mOriginatingUserId), 0); 2723 } 2724 2725 private Bitmap getProfileBadge() { 2726 Drawable badge = getProfileBadgeDrawable(); 2727 if (badge == null) { 2728 return null; 2729 } 2730 final int size = mContext.getResources().getDimensionPixelSize( 2731 R.dimen.notification_badge_size); 2732 Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); 2733 Canvas canvas = new Canvas(bitmap); 2734 badge.setBounds(0, 0, size, size); 2735 badge.draw(canvas); 2736 return bitmap; 2737 } 2738 2739 private boolean addProfileBadge(RemoteViews contentView, int resId) { 2740 Bitmap profileBadge = getProfileBadge(); 2741 2742 contentView.setViewVisibility(R.id.profile_badge_large_template, View.GONE); 2743 contentView.setViewVisibility(R.id.profile_badge_line2, View.GONE); 2744 contentView.setViewVisibility(R.id.profile_badge_line3, View.GONE); 2745 2746 if (profileBadge != null) { 2747 contentView.setImageViewBitmap(resId, profileBadge); 2748 contentView.setViewVisibility(resId, View.VISIBLE); 2749 2750 // Make sure Line 3 is visible. As badge will be here if there 2751 // is no text to display. 2752 if (resId == R.id.profile_badge_line3) { 2753 contentView.setViewVisibility(R.id.line3, View.VISIBLE); 2754 } 2755 return true; 2756 } 2757 return false; 2758 } 2759 2760 private void shrinkLine3Text(RemoteViews contentView) { 2761 float subTextSize = mContext.getResources().getDimensionPixelSize( 2762 R.dimen.notification_subtext_size); 2763 contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize); 2764 } 2765 2766 private void unshrinkLine3Text(RemoteViews contentView) { 2767 float regularTextSize = mContext.getResources().getDimensionPixelSize( 2768 com.android.internal.R.dimen.notification_text_size); 2769 contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, regularTextSize); 2770 } 2771 2772 private void resetStandardTemplate(RemoteViews contentView) { 2773 removeLargeIconBackground(contentView); 2774 contentView.setViewPadding(R.id.icon, 0, 0, 0, 0); 2775 contentView.setImageViewResource(R.id.icon, 0); 2776 contentView.setInt(R.id.icon, "setBackgroundResource", 0); 2777 contentView.setViewVisibility(R.id.right_icon, View.GONE); 2778 contentView.setInt(R.id.right_icon, "setBackgroundResource", 0); 2779 contentView.setImageViewResource(R.id.right_icon, 0); 2780 contentView.setImageViewResource(R.id.icon, 0); 2781 contentView.setTextViewText(R.id.title, null); 2782 contentView.setTextViewText(R.id.text, null); 2783 unshrinkLine3Text(contentView); 2784 contentView.setTextViewText(R.id.text2, null); 2785 contentView.setViewVisibility(R.id.text2, View.GONE); 2786 contentView.setViewVisibility(R.id.info, View.GONE); 2787 contentView.setViewVisibility(R.id.time, View.GONE); 2788 contentView.setViewVisibility(R.id.line3, View.GONE); 2789 contentView.setViewVisibility(R.id.overflow_divider, View.GONE); 2790 contentView.setViewVisibility(R.id.progress, View.GONE); 2791 contentView.setViewVisibility(R.id.chronometer, View.GONE); 2792 contentView.setViewVisibility(R.id.time, View.GONE); 2793 } 2794 2795 private RemoteViews applyStandardTemplate(int resId) { 2796 return applyStandardTemplate(resId, true /* hasProgress */); 2797 } 2798 2799 /** 2800 * @param hasProgress whether the progress bar should be shown and set 2801 */ 2802 private RemoteViews applyStandardTemplate(int resId, boolean hasProgress) { 2803 RemoteViews contentView = new BuilderRemoteViews(mContext.getApplicationInfo(), resId); 2804 2805 resetStandardTemplate(contentView); 2806 2807 boolean showLine3 = false; 2808 boolean showLine2 = false; 2809 boolean contentTextInLine2 = false; 2810 2811 if (mLargeIcon != null) { 2812 contentView.setImageViewBitmap(R.id.icon, mLargeIcon); 2813 processLargeLegacyIcon(mLargeIcon, contentView); 2814 contentView.setImageViewResource(R.id.right_icon, mSmallIcon); 2815 contentView.setViewVisibility(R.id.right_icon, View.VISIBLE); 2816 processSmallRightIcon(mSmallIcon, contentView); 2817 } else { // small icon at left 2818 contentView.setImageViewResource(R.id.icon, mSmallIcon); 2819 contentView.setViewVisibility(R.id.icon, View.VISIBLE); 2820 processSmallIconAsLarge(mSmallIcon, contentView); 2821 } 2822 if (mContentTitle != null) { 2823 contentView.setTextViewText(R.id.title, processLegacyText(mContentTitle)); 2824 } 2825 if (mContentText != null) { 2826 contentView.setTextViewText(R.id.text, processLegacyText(mContentText)); 2827 showLine3 = true; 2828 } 2829 if (mContentInfo != null) { 2830 contentView.setTextViewText(R.id.info, processLegacyText(mContentInfo)); 2831 contentView.setViewVisibility(R.id.info, View.VISIBLE); 2832 showLine3 = true; 2833 } else if (mNumber > 0) { 2834 final int tooBig = mContext.getResources().getInteger( 2835 R.integer.status_bar_notification_info_maxnum); 2836 if (mNumber > tooBig) { 2837 contentView.setTextViewText(R.id.info, processLegacyText( 2838 mContext.getResources().getString( 2839 R.string.status_bar_notification_info_overflow))); 2840 } else { 2841 NumberFormat f = NumberFormat.getIntegerInstance(); 2842 contentView.setTextViewText(R.id.info, processLegacyText(f.format(mNumber))); 2843 } 2844 contentView.setViewVisibility(R.id.info, View.VISIBLE); 2845 showLine3 = true; 2846 } else { 2847 contentView.setViewVisibility(R.id.info, View.GONE); 2848 } 2849 2850 // Need to show three lines? 2851 if (mSubText != null) { 2852 contentView.setTextViewText(R.id.text, processLegacyText(mSubText)); 2853 if (mContentText != null) { 2854 contentView.setTextViewText(R.id.text2, processLegacyText(mContentText)); 2855 contentView.setViewVisibility(R.id.text2, View.VISIBLE); 2856 showLine2 = true; 2857 contentTextInLine2 = true; 2858 } else { 2859 contentView.setViewVisibility(R.id.text2, View.GONE); 2860 } 2861 } else { 2862 contentView.setViewVisibility(R.id.text2, View.GONE); 2863 if (hasProgress && (mProgressMax != 0 || mProgressIndeterminate)) { 2864 contentView.setViewVisibility(R.id.progress, View.VISIBLE); 2865 contentView.setProgressBar( 2866 R.id.progress, mProgressMax, mProgress, mProgressIndeterminate); 2867 contentView.setProgressBackgroundTintList( 2868 R.id.progress, ColorStateList.valueOf(mContext.getResources().getColor( 2869 R.color.notification_progress_background_color))); 2870 if (mColor != COLOR_DEFAULT) { 2871 ColorStateList colorStateList = ColorStateList.valueOf(mColor); 2872 contentView.setProgressTintList(R.id.progress, colorStateList); 2873 contentView.setProgressIndeterminateTintList(R.id.progress, colorStateList); 2874 } 2875 showLine2 = true; 2876 } else { 2877 contentView.setViewVisibility(R.id.progress, View.GONE); 2878 } 2879 } 2880 if (showLine2) { 2881 2882 // need to shrink all the type to make sure everything fits 2883 shrinkLine3Text(contentView); 2884 } 2885 2886 if (showsTimeOrChronometer()) { 2887 if (mUseChronometer) { 2888 contentView.setViewVisibility(R.id.chronometer, View.VISIBLE); 2889 contentView.setLong(R.id.chronometer, "setBase", 2890 mWhen + (SystemClock.elapsedRealtime() - System.currentTimeMillis())); 2891 contentView.setBoolean(R.id.chronometer, "setStarted", true); 2892 } else { 2893 contentView.setViewVisibility(R.id.time, View.VISIBLE); 2894 contentView.setLong(R.id.time, "setTime", mWhen); 2895 } 2896 } 2897 2898 // Adjust padding depending on line count and font size. 2899 contentView.setViewPadding(R.id.line1, 0, calculateTopPadding(mContext, 2900 mHasThreeLines, mContext.getResources().getConfiguration().fontScale), 2901 0, 0); 2902 2903 // We want to add badge to first line of text. 2904 boolean addedBadge = addProfileBadge(contentView, 2905 contentTextInLine2 ? R.id.profile_badge_line2 : R.id.profile_badge_line3); 2906 // If we added the badge to line 3 then we should show line 3. 2907 if (addedBadge && !contentTextInLine2) { 2908 showLine3 = true; 2909 } 2910 2911 // Note getStandardView may hide line 3 again. 2912 contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE); 2913 contentView.setViewVisibility(R.id.overflow_divider, showLine3 ? View.VISIBLE : View.GONE); 2914 return contentView; 2915 } 2916 2917 /** 2918 * @return true if the built notification will show the time or the chronometer; false 2919 * otherwise 2920 */ 2921 private boolean showsTimeOrChronometer() { 2922 return mWhen != 0 && mShowWhen; 2923 } 2924 2925 /** 2926 * Logic to find out whether the notification is going to have three lines in the contracted 2927 * layout. This is used to adjust the top padding. 2928 * 2929 * @return true if the notification is going to have three lines; false if the notification 2930 * is going to have one or two lines 2931 */ 2932 private boolean hasThreeLines() { 2933 boolean contentTextInLine2 = mSubText != null && mContentText != null; 2934 boolean hasProgress = mStyle == null || mStyle.hasProgress(); 2935 // If we have content text in line 2, badge goes into line 2, or line 3 otherwise 2936 boolean badgeInLine3 = getProfileBadgeDrawable() != null && !contentTextInLine2; 2937 boolean hasLine3 = mContentText != null || mContentInfo != null || mNumber > 0 2938 || badgeInLine3; 2939 boolean hasLine2 = (mSubText != null && mContentText != null) || 2940 (hasProgress && mSubText == null 2941 && (mProgressMax != 0 || mProgressIndeterminate)); 2942 return hasLine2 && hasLine3; 2943 } 2944 2945 /** 2946 * @hide 2947 */ 2948 public static int calculateTopPadding(Context ctx, boolean hasThreeLines, 2949 float fontScale) { 2950 int padding = ctx.getResources().getDimensionPixelSize(hasThreeLines 2951 ? R.dimen.notification_top_pad_narrow 2952 : R.dimen.notification_top_pad); 2953 int largePadding = ctx.getResources().getDimensionPixelSize(hasThreeLines 2954 ? R.dimen.notification_top_pad_large_text_narrow 2955 : R.dimen.notification_top_pad_large_text); 2956 float largeFactor = (MathUtils.constrain(fontScale, 1.0f, LARGE_TEXT_SCALE) - 1f) 2957 / (LARGE_TEXT_SCALE - 1f); 2958 2959 // Linearly interpolate the padding between large and normal with the font scale ranging 2960 // from 1f to LARGE_TEXT_SCALE 2961 return Math.round((1 - largeFactor) * padding + largeFactor * largePadding); 2962 } 2963 2964 private void resetStandardTemplateWithActions(RemoteViews big) { 2965 big.setViewVisibility(R.id.actions, View.GONE); 2966 big.setViewVisibility(R.id.action_divider, View.GONE); 2967 big.removeAllViews(R.id.actions); 2968 } 2969 2970 private RemoteViews applyStandardTemplateWithActions(int layoutId) { 2971 RemoteViews big = applyStandardTemplate(layoutId); 2972 2973 resetStandardTemplateWithActions(big); 2974 2975 int N = mActions.size(); 2976 if (N > 0) { 2977 big.setViewVisibility(R.id.actions, View.VISIBLE); 2978 big.setViewVisibility(R.id.action_divider, View.VISIBLE); 2979 if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS; 2980 for (int i=0; i<N; i++) { 2981 final RemoteViews button = generateActionButton(mActions.get(i)); 2982 big.addView(R.id.actions, button); 2983 } 2984 } 2985 return big; 2986 } 2987 2988 private RemoteViews makeContentView() { 2989 if (mContentView != null) { 2990 return mContentView; 2991 } else { 2992 return applyStandardTemplate(getBaseLayoutResource()); 2993 } 2994 } 2995 2996 private RemoteViews makeTickerView() { 2997 if (mTickerView != null) { 2998 return mTickerView; 2999 } 3000 return null; // tickers are not created by default anymore 3001 } 3002 3003 private RemoteViews makeBigContentView() { 3004 if (mActions.size() == 0) return null; 3005 3006 return applyStandardTemplateWithActions(getBigBaseLayoutResource()); 3007 } 3008 3009 private RemoteViews makeHeadsUpContentView() { 3010 if (mActions.size() == 0) return null; 3011 3012 return applyStandardTemplateWithActions(getBigBaseLayoutResource()); 3013 } 3014 3015 3016 private RemoteViews generateActionButton(Action action) { 3017 final boolean tombstone = (action.actionIntent == null); 3018 RemoteViews button = new RemoteViews(mContext.getPackageName(), 3019 tombstone ? getActionTombstoneLayoutResource() 3020 : getActionLayoutResource()); 3021 button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0); 3022 button.setTextViewText(R.id.action0, processLegacyText(action.title)); 3023 if (!tombstone) { 3024 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 3025 } 3026 button.setContentDescription(R.id.action0, action.title); 3027 processLegacyAction(action, button); 3028 return button; 3029 } 3030 3031 /** 3032 * @return Whether we are currently building a notification from a legacy (an app that 3033 * doesn't create material notifications by itself) app. 3034 */ 3035 private boolean isLegacy() { 3036 return mColorUtil != null; 3037 } 3038 3039 private void processLegacyAction(Action action, RemoteViews button) { 3040 if (!isLegacy() || mColorUtil.isGrayscaleIcon(mContext, action.icon)) { 3041 button.setTextViewCompoundDrawablesRelativeColorFilter(R.id.action0, 0, 3042 mContext.getResources().getColor(R.color.notification_action_color_filter), 3043 PorterDuff.Mode.MULTIPLY); 3044 } 3045 } 3046 3047 private CharSequence processLegacyText(CharSequence charSequence) { 3048 if (isLegacy()) { 3049 return mColorUtil.invertCharSequenceColors(charSequence); 3050 } else { 3051 return charSequence; 3052 } 3053 } 3054 3055 /** 3056 * Apply any necessary background to smallIcons being used in the largeIcon spot. 3057 */ 3058 private void processSmallIconAsLarge(int largeIconId, RemoteViews contentView) { 3059 if (!isLegacy() || mColorUtil.isGrayscaleIcon(mContext, largeIconId)) { 3060 applyLargeIconBackground(contentView); 3061 } 3062 } 3063 3064 /** 3065 * Apply any necessary background to a largeIcon if it's a fake smallIcon (that is, 3066 * if it's grayscale). 3067 */ 3068 // TODO: also check bounds, transparency, that sort of thing. 3069 private void processLargeLegacyIcon(Bitmap largeIcon, RemoteViews contentView) { 3070 if (isLegacy() && mColorUtil.isGrayscaleIcon(largeIcon)) { 3071 applyLargeIconBackground(contentView); 3072 } else { 3073 removeLargeIconBackground(contentView); 3074 } 3075 } 3076 3077 /** 3078 * Add a colored circle behind the largeIcon slot. 3079 */ 3080 private void applyLargeIconBackground(RemoteViews contentView) { 3081 contentView.setInt(R.id.icon, "setBackgroundResource", 3082 R.drawable.notification_icon_legacy_bg); 3083 3084 contentView.setDrawableParameters( 3085 R.id.icon, 3086 true, 3087 -1, 3088 resolveColor(), 3089 PorterDuff.Mode.SRC_ATOP, 3090 -1); 3091 3092 int padding = mContext.getResources().getDimensionPixelSize( 3093 R.dimen.notification_large_icon_circle_padding); 3094 contentView.setViewPadding(R.id.icon, padding, padding, padding, padding); 3095 } 3096 3097 private void removeLargeIconBackground(RemoteViews contentView) { 3098 contentView.setInt(R.id.icon, "setBackgroundResource", 0); 3099 } 3100 3101 /** 3102 * Recolor small icons when used in the R.id.right_icon slot. 3103 */ 3104 private void processSmallRightIcon(int smallIconDrawableId, 3105 RemoteViews contentView) { 3106 if (!isLegacy() || mColorUtil.isGrayscaleIcon(mContext, smallIconDrawableId)) { 3107 contentView.setDrawableParameters(R.id.right_icon, false, -1, 3108 0xFFFFFFFF, 3109 PorterDuff.Mode.SRC_ATOP, -1); 3110 3111 contentView.setInt(R.id.right_icon, 3112 "setBackgroundResource", 3113 R.drawable.notification_icon_legacy_bg); 3114 3115 contentView.setDrawableParameters( 3116 R.id.right_icon, 3117 true, 3118 -1, 3119 resolveColor(), 3120 PorterDuff.Mode.SRC_ATOP, 3121 -1); 3122 } 3123 } 3124 3125 private int sanitizeColor() { 3126 if (mColor != COLOR_DEFAULT) { 3127 mColor |= 0xFF000000; // no alpha for custom colors 3128 } 3129 return mColor; 3130 } 3131 3132 private int resolveColor() { 3133 if (mColor == COLOR_DEFAULT) { 3134 return mContext.getResources().getColor(R.color.notification_icon_bg_color); 3135 } 3136 return mColor; 3137 } 3138 3139 /** 3140 * Apply the unstyled operations and return a new {@link Notification} object. 3141 * @hide 3142 */ 3143 public Notification buildUnstyled() { 3144 Notification n = new Notification(); 3145 n.when = mWhen; 3146 n.icon = mSmallIcon; 3147 n.iconLevel = mSmallIconLevel; 3148 n.number = mNumber; 3149 3150 n.color = sanitizeColor(); 3151 3152 setBuilderContentView(n, makeContentView()); 3153 n.contentIntent = mContentIntent; 3154 n.deleteIntent = mDeleteIntent; 3155 n.fullScreenIntent = mFullScreenIntent; 3156 n.tickerText = mTickerText; 3157 n.tickerView = makeTickerView(); 3158 n.largeIcon = mLargeIcon; 3159 n.sound = mSound; 3160 n.audioStreamType = mAudioStreamType; 3161 n.audioAttributes = mAudioAttributes; 3162 n.vibrate = mVibrate; 3163 n.ledARGB = mLedArgb; 3164 n.ledOnMS = mLedOnMs; 3165 n.ledOffMS = mLedOffMs; 3166 n.defaults = mDefaults; 3167 n.flags = mFlags; 3168 setBuilderBigContentView(n, makeBigContentView()); 3169 setBuilderHeadsUpContentView(n, makeHeadsUpContentView()); 3170 if (mLedOnMs != 0 || mLedOffMs != 0) { 3171 n.flags |= FLAG_SHOW_LIGHTS; 3172 } 3173 if ((mDefaults & DEFAULT_LIGHTS) != 0) { 3174 n.flags |= FLAG_SHOW_LIGHTS; 3175 } 3176 n.category = mCategory; 3177 n.mGroupKey = mGroupKey; 3178 n.mSortKey = mSortKey; 3179 n.priority = mPriority; 3180 if (mActions.size() > 0) { 3181 n.actions = new Action[mActions.size()]; 3182 mActions.toArray(n.actions); 3183 } 3184 n.visibility = mVisibility; 3185 3186 if (mPublicVersion != null) { 3187 n.publicVersion = new Notification(); 3188 mPublicVersion.cloneInto(n.publicVersion, true); 3189 } 3190 // Note: If you're adding new fields, also update restoreFromNotitification(). 3191 return n; 3192 } 3193 3194 /** 3195 * Capture, in the provided bundle, semantic information used in the construction of 3196 * this Notification object. 3197 * @hide 3198 */ 3199 public void populateExtras(Bundle extras) { 3200 // Store original information used in the construction of this object 3201 extras.putInt(EXTRA_ORIGINATING_USERID, mOriginatingUserId); 3202 extras.putParcelable(EXTRA_REBUILD_CONTEXT_APPLICATION_INFO, 3203 mContext.getApplicationInfo()); 3204 extras.putCharSequence(EXTRA_TITLE, mContentTitle); 3205 extras.putCharSequence(EXTRA_TEXT, mContentText); 3206 extras.putCharSequence(EXTRA_SUB_TEXT, mSubText); 3207 extras.putCharSequence(EXTRA_INFO_TEXT, mContentInfo); 3208 extras.putInt(EXTRA_SMALL_ICON, mSmallIcon); 3209 extras.putInt(EXTRA_PROGRESS, mProgress); 3210 extras.putInt(EXTRA_PROGRESS_MAX, mProgressMax); 3211 extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, mProgressIndeterminate); 3212 extras.putBoolean(EXTRA_SHOW_CHRONOMETER, mUseChronometer); 3213 extras.putBoolean(EXTRA_SHOW_WHEN, mShowWhen); 3214 if (mLargeIcon != null) { 3215 extras.putParcelable(EXTRA_LARGE_ICON, mLargeIcon); 3216 } 3217 if (!mPeople.isEmpty()) { 3218 extras.putStringArray(EXTRA_PEOPLE, mPeople.toArray(new String[mPeople.size()])); 3219 } 3220 // NOTE: If you're adding new extras also update restoreFromNotification(). 3221 } 3222 3223 3224 /** 3225 * @hide 3226 */ 3227 public static void stripForDelivery(Notification n) { 3228 if (!STRIP_AND_REBUILD) { 3229 return; 3230 } 3231 3232 String templateClass = n.extras.getString(EXTRA_TEMPLATE); 3233 // Only strip views for known Styles because we won't know how to 3234 // re-create them otherwise. 3235 boolean stripViews = TextUtils.isEmpty(templateClass) || 3236 getNotificationStyleClass(templateClass) != null; 3237 3238 boolean isStripped = false; 3239 3240 if (n.largeIcon != null && n.extras.containsKey(EXTRA_LARGE_ICON)) { 3241 // TODO: Would like to check for equality here, but if the notification 3242 // has been cloned, we can't. 3243 n.largeIcon = null; 3244 n.extras.putBoolean(EXTRA_REBUILD_LARGE_ICON, true); 3245 isStripped = true; 3246 } 3247 // Get rid of unmodified BuilderRemoteViews. 3248 3249 if (stripViews && 3250 n.contentView instanceof BuilderRemoteViews && 3251 n.extras.getInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, -1) == 3252 n.contentView.getSequenceNumber()) { 3253 n.contentView = null; 3254 n.extras.putBoolean(EXTRA_REBUILD_CONTENT_VIEW, true); 3255 n.extras.remove(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT); 3256 isStripped = true; 3257 } 3258 if (stripViews && 3259 n.bigContentView instanceof BuilderRemoteViews && 3260 n.extras.getInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, -1) == 3261 n.bigContentView.getSequenceNumber()) { 3262 n.bigContentView = null; 3263 n.extras.putBoolean(EXTRA_REBUILD_BIG_CONTENT_VIEW, true); 3264 n.extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT); 3265 isStripped = true; 3266 } 3267 if (stripViews && 3268 n.headsUpContentView instanceof BuilderRemoteViews && 3269 n.extras.getInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, -1) == 3270 n.headsUpContentView.getSequenceNumber()) { 3271 n.headsUpContentView = null; 3272 n.extras.putBoolean(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW, true); 3273 n.extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT); 3274 isStripped = true; 3275 } 3276 3277 if (isStripped) { 3278 n.extras.putBoolean(EXTRA_NEEDS_REBUILD, true); 3279 } 3280 } 3281 3282 /** 3283 * @hide 3284 */ 3285 public static Notification rebuild(Context context, Notification n) { 3286 Bundle extras = n.extras; 3287 if (!extras.getBoolean(EXTRA_NEEDS_REBUILD)) return n; 3288 extras.remove(EXTRA_NEEDS_REBUILD); 3289 3290 // Re-create notification context so we can access app resources. 3291 ApplicationInfo applicationInfo = extras.getParcelable( 3292 EXTRA_REBUILD_CONTEXT_APPLICATION_INFO); 3293 Context builderContext; 3294 try { 3295 builderContext = context.createApplicationContext(applicationInfo, 3296 Context.CONTEXT_RESTRICTED); 3297 } catch (NameNotFoundException e) { 3298 Log.e(TAG, "ApplicationInfo " + applicationInfo + " not found"); 3299 builderContext = context; // try with our context 3300 } 3301 3302 Builder b = new Builder(builderContext, n); 3303 return b.rebuild(); 3304 } 3305 3306 /** 3307 * Rebuilds the notification passed in to the rebuild-constructor 3308 * {@link #Builder(Context, Notification)}. 3309 * 3310 * <p> 3311 * Throws IllegalStateException when invoked on a Builder that isn't in rebuild mode. 3312 * 3313 * @hide 3314 */ 3315 private Notification rebuild() { 3316 if (mRebuildNotification == null) { 3317 throw new IllegalStateException("rebuild() only valid when in 'rebuild' mode."); 3318 } 3319 mHasThreeLines = hasThreeLines(); 3320 3321 Bundle extras = mRebuildNotification.extras; 3322 3323 if (extras.getBoolean(EXTRA_REBUILD_LARGE_ICON)) { 3324 mRebuildNotification.largeIcon = extras.getParcelable(EXTRA_LARGE_ICON); 3325 } 3326 extras.remove(EXTRA_REBUILD_LARGE_ICON); 3327 3328 if (extras.getBoolean(EXTRA_REBUILD_CONTENT_VIEW)) { 3329 setBuilderContentView(mRebuildNotification, makeContentView()); 3330 if (mStyle != null) { 3331 mStyle.populateContentView(mRebuildNotification); 3332 } 3333 } 3334 extras.remove(EXTRA_REBUILD_CONTENT_VIEW); 3335 3336 if (extras.getBoolean(EXTRA_REBUILD_BIG_CONTENT_VIEW)) { 3337 setBuilderBigContentView(mRebuildNotification, makeBigContentView()); 3338 if (mStyle != null) { 3339 mStyle.populateBigContentView(mRebuildNotification); 3340 } 3341 } 3342 extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW); 3343 3344 if (extras.getBoolean(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW)) { 3345 setBuilderHeadsUpContentView(mRebuildNotification, makeHeadsUpContentView()); 3346 if (mStyle != null) { 3347 mStyle.populateHeadsUpContentView(mRebuildNotification); 3348 } 3349 } 3350 extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW); 3351 3352 mHasThreeLines = false; 3353 return mRebuildNotification; 3354 } 3355 3356 private static Class<? extends Style> getNotificationStyleClass(String templateClass) { 3357 Class<? extends Style>[] classes = new Class[]{ 3358 BigTextStyle.class, BigPictureStyle.class, InboxStyle.class, MediaStyle.class}; 3359 for (Class<? extends Style> innerClass : classes) { 3360 if (templateClass.equals(innerClass.getName())) { 3361 return innerClass; 3362 } 3363 } 3364 return null; 3365 } 3366 3367 private void setBuilderContentView(Notification n, RemoteViews contentView) { 3368 n.contentView = contentView; 3369 if (contentView instanceof BuilderRemoteViews) { 3370 mRebuildBundle.putInt(Builder.EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, 3371 contentView.getSequenceNumber()); 3372 } 3373 } 3374 3375 private void setBuilderBigContentView(Notification n, RemoteViews bigContentView) { 3376 n.bigContentView = bigContentView; 3377 if (bigContentView instanceof BuilderRemoteViews) { 3378 mRebuildBundle.putInt(Builder.EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, 3379 bigContentView.getSequenceNumber()); 3380 } 3381 } 3382 3383 private void setBuilderHeadsUpContentView(Notification n, 3384 RemoteViews headsUpContentView) { 3385 n.headsUpContentView = headsUpContentView; 3386 if (headsUpContentView instanceof BuilderRemoteViews) { 3387 mRebuildBundle.putInt(Builder.EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, 3388 headsUpContentView.getSequenceNumber()); 3389 } 3390 } 3391 3392 private void restoreFromNotification(Notification n) { 3393 3394 // Notification fields. 3395 mWhen = n.when; 3396 mSmallIcon = n.icon; 3397 mSmallIconLevel = n.iconLevel; 3398 mNumber = n.number; 3399 3400 mColor = n.color; 3401 3402 mContentView = n.contentView; 3403 mDeleteIntent = n.deleteIntent; 3404 mFullScreenIntent = n.fullScreenIntent; 3405 mTickerText = n.tickerText; 3406 mTickerView = n.tickerView; 3407 mLargeIcon = n.largeIcon; 3408 mSound = n.sound; 3409 mAudioStreamType = n.audioStreamType; 3410 mAudioAttributes = n.audioAttributes; 3411 3412 mVibrate = n.vibrate; 3413 mLedArgb = n.ledARGB; 3414 mLedOnMs = n.ledOnMS; 3415 mLedOffMs = n.ledOffMS; 3416 mDefaults = n.defaults; 3417 mFlags = n.flags; 3418 3419 mCategory = n.category; 3420 mGroupKey = n.mGroupKey; 3421 mSortKey = n.mSortKey; 3422 mPriority = n.priority; 3423 mActions.clear(); 3424 if (n.actions != null) { 3425 Collections.addAll(mActions, n.actions); 3426 } 3427 mVisibility = n.visibility; 3428 3429 mPublicVersion = n.publicVersion; 3430 3431 // Extras. 3432 Bundle extras = n.extras; 3433 mOriginatingUserId = extras.getInt(EXTRA_ORIGINATING_USERID); 3434 mContentTitle = extras.getCharSequence(EXTRA_TITLE); 3435 mContentText = extras.getCharSequence(EXTRA_TEXT); 3436 mSubText = extras.getCharSequence(EXTRA_SUB_TEXT); 3437 mContentInfo = extras.getCharSequence(EXTRA_INFO_TEXT); 3438 mSmallIcon = extras.getInt(EXTRA_SMALL_ICON); 3439 mProgress = extras.getInt(EXTRA_PROGRESS); 3440 mProgressMax = extras.getInt(EXTRA_PROGRESS_MAX); 3441 mProgressIndeterminate = extras.getBoolean(EXTRA_PROGRESS_INDETERMINATE); 3442 mUseChronometer = extras.getBoolean(EXTRA_SHOW_CHRONOMETER); 3443 mShowWhen = extras.getBoolean(EXTRA_SHOW_WHEN); 3444 if (extras.containsKey(EXTRA_LARGE_ICON)) { 3445 mLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON); 3446 } 3447 if (extras.containsKey(EXTRA_PEOPLE)) { 3448 mPeople.clear(); 3449 Collections.addAll(mPeople, extras.getStringArray(EXTRA_PEOPLE)); 3450 } 3451 } 3452 3453 /** 3454 * @deprecated Use {@link #build()} instead. 3455 */ 3456 @Deprecated 3457 public Notification getNotification() { 3458 return build(); 3459 } 3460 3461 /** 3462 * Combine all of the options that have been set and return a new {@link Notification} 3463 * object. 3464 */ 3465 public Notification build() { 3466 mOriginatingUserId = mContext.getUserId(); 3467 mHasThreeLines = hasThreeLines(); 3468 3469 Notification n = buildUnstyled(); 3470 3471 if (mStyle != null) { 3472 n = mStyle.buildStyled(n); 3473 } 3474 3475 if (mExtras != null) { 3476 n.extras.putAll(mExtras); 3477 } 3478 3479 if (mRebuildBundle.size() > 0) { 3480 n.extras.putAll(mRebuildBundle); 3481 mRebuildBundle.clear(); 3482 } 3483 3484 populateExtras(n.extras); 3485 if (mStyle != null) { 3486 mStyle.addExtras(n.extras); 3487 } 3488 3489 mHasThreeLines = false; 3490 return n; 3491 } 3492 3493 /** 3494 * Apply this Builder to an existing {@link Notification} object. 3495 * 3496 * @hide 3497 */ 3498 public Notification buildInto(Notification n) { 3499 build().cloneInto(n, true); 3500 return n; 3501 } 3502 3503 private int getBaseLayoutResource() { 3504 return R.layout.notification_template_material_base; 3505 } 3506 3507 private int getBigBaseLayoutResource() { 3508 return R.layout.notification_template_material_big_base; 3509 } 3510 3511 private int getBigPictureLayoutResource() { 3512 return R.layout.notification_template_material_big_picture; 3513 } 3514 3515 private int getBigTextLayoutResource() { 3516 return R.layout.notification_template_material_big_text; 3517 } 3518 3519 private int getInboxLayoutResource() { 3520 return R.layout.notification_template_material_inbox; 3521 } 3522 3523 private int getActionLayoutResource() { 3524 return R.layout.notification_material_action; 3525 } 3526 3527 private int getActionTombstoneLayoutResource() { 3528 return R.layout.notification_material_action_tombstone; 3529 } 3530 } 3531 3532 /** 3533 * An object that can apply a rich notification style to a {@link Notification.Builder} 3534 * object. 3535 */ 3536 public static abstract class Style { 3537 private CharSequence mBigContentTitle; 3538 3539 /** 3540 * @hide 3541 */ 3542 protected CharSequence mSummaryText = null; 3543 3544 /** 3545 * @hide 3546 */ 3547 protected boolean mSummaryTextSet = false; 3548 3549 protected Builder mBuilder; 3550 3551 /** 3552 * Overrides ContentTitle in the big form of the template. 3553 * This defaults to the value passed to setContentTitle(). 3554 */ 3555 protected void internalSetBigContentTitle(CharSequence title) { 3556 mBigContentTitle = title; 3557 } 3558 3559 /** 3560 * Set the first line of text after the detail section in the big form of the template. 3561 */ 3562 protected void internalSetSummaryText(CharSequence cs) { 3563 mSummaryText = cs; 3564 mSummaryTextSet = true; 3565 } 3566 3567 public void setBuilder(Builder builder) { 3568 if (mBuilder != builder) { 3569 mBuilder = builder; 3570 if (mBuilder != null) { 3571 mBuilder.setStyle(this); 3572 } 3573 } 3574 } 3575 3576 protected void checkBuilder() { 3577 if (mBuilder == null) { 3578 throw new IllegalArgumentException("Style requires a valid Builder object"); 3579 } 3580 } 3581 3582 protected RemoteViews getStandardView(int layoutId) { 3583 checkBuilder(); 3584 3585 // Nasty. 3586 CharSequence oldBuilderContentTitle = mBuilder.mContentTitle; 3587 if (mBigContentTitle != null) { 3588 mBuilder.setContentTitle(mBigContentTitle); 3589 } 3590 3591 RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId); 3592 3593 mBuilder.mContentTitle = oldBuilderContentTitle; 3594 3595 if (mBigContentTitle != null && mBigContentTitle.equals("")) { 3596 contentView.setViewVisibility(R.id.line1, View.GONE); 3597 } else { 3598 contentView.setViewVisibility(R.id.line1, View.VISIBLE); 3599 } 3600 3601 // The last line defaults to the subtext, but can be replaced by mSummaryText 3602 final CharSequence overflowText = 3603 mSummaryTextSet ? mSummaryText 3604 : mBuilder.mSubText; 3605 if (overflowText != null) { 3606 contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(overflowText)); 3607 contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE); 3608 contentView.setViewVisibility(R.id.line3, View.VISIBLE); 3609 } else { 3610 // Clear text in case we use the line to show the profile badge. 3611 contentView.setTextViewText(R.id.text, ""); 3612 contentView.setViewVisibility(R.id.overflow_divider, View.GONE); 3613 contentView.setViewVisibility(R.id.line3, View.GONE); 3614 } 3615 3616 return contentView; 3617 } 3618 3619 /** 3620 * Changes the padding of the first line such that the big and small content view have the 3621 * same top padding. 3622 * 3623 * @hide 3624 */ 3625 protected void applyTopPadding(RemoteViews contentView) { 3626 int topPadding = Builder.calculateTopPadding(mBuilder.mContext, 3627 mBuilder.mHasThreeLines, 3628 mBuilder.mContext.getResources().getConfiguration().fontScale); 3629 contentView.setViewPadding(R.id.line1, 0, topPadding, 0, 0); 3630 } 3631 3632 /** 3633 * @hide 3634 */ 3635 public void addExtras(Bundle extras) { 3636 if (mSummaryTextSet) { 3637 extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText); 3638 } 3639 if (mBigContentTitle != null) { 3640 extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle); 3641 } 3642 extras.putString(EXTRA_TEMPLATE, this.getClass().getName()); 3643 } 3644 3645 /** 3646 * @hide 3647 */ 3648 protected void restoreFromExtras(Bundle extras) { 3649 if (extras.containsKey(EXTRA_SUMMARY_TEXT)) { 3650 mSummaryText = extras.getCharSequence(EXTRA_SUMMARY_TEXT); 3651 mSummaryTextSet = true; 3652 } 3653 if (extras.containsKey(EXTRA_TITLE_BIG)) { 3654 mBigContentTitle = extras.getCharSequence(EXTRA_TITLE_BIG); 3655 } 3656 } 3657 3658 3659 /** 3660 * @hide 3661 */ 3662 public Notification buildStyled(Notification wip) { 3663 populateTickerView(wip); 3664 populateContentView(wip); 3665 populateBigContentView(wip); 3666 populateHeadsUpContentView(wip); 3667 return wip; 3668 } 3669 3670 // The following methods are split out so we can re-create notification partially. 3671 /** 3672 * @hide 3673 */ 3674 protected void populateTickerView(Notification wip) {} 3675 /** 3676 * @hide 3677 */ 3678 protected void populateContentView(Notification wip) {} 3679 3680 /** 3681 * @hide 3682 */ 3683 protected void populateBigContentView(Notification wip) {} 3684 3685 /** 3686 * @hide 3687 */ 3688 protected void populateHeadsUpContentView(Notification wip) {} 3689 3690 /** 3691 * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is 3692 * attached to. 3693 * 3694 * @return the fully constructed Notification. 3695 */ 3696 public Notification build() { 3697 checkBuilder(); 3698 return mBuilder.build(); 3699 } 3700 3701 /** 3702 * @hide 3703 * @return true if the style positions the progress bar on the second line; false if the 3704 * style hides the progress bar 3705 */ 3706 protected boolean hasProgress() { 3707 return true; 3708 } 3709 } 3710 3711 /** 3712 * Helper class for generating large-format notifications that include a large image attachment. 3713 * 3714 * Here's how you'd set the <code>BigPictureStyle</code> on a notification: 3715 * <pre class="prettyprint"> 3716 * Notification notif = new Notification.Builder(mContext) 3717 * .setContentTitle("New photo from " + sender.toString()) 3718 * .setContentText(subject) 3719 * .setSmallIcon(R.drawable.new_post) 3720 * .setLargeIcon(aBitmap) 3721 * .setStyle(new Notification.BigPictureStyle() 3722 * .bigPicture(aBigBitmap)) 3723 * .build(); 3724 * </pre> 3725 * 3726 * @see Notification#bigContentView 3727 */ 3728 public static class BigPictureStyle extends Style { 3729 private Bitmap mPicture; 3730 private Bitmap mBigLargeIcon; 3731 private boolean mBigLargeIconSet = false; 3732 3733 public BigPictureStyle() { 3734 } 3735 3736 public BigPictureStyle(Builder builder) { 3737 setBuilder(builder); 3738 } 3739 3740 /** 3741 * Overrides ContentTitle in the big form of the template. 3742 * This defaults to the value passed to setContentTitle(). 3743 */ 3744 public BigPictureStyle setBigContentTitle(CharSequence title) { 3745 internalSetBigContentTitle(safeCharSequence(title)); 3746 return this; 3747 } 3748 3749 /** 3750 * Set the first line of text after the detail section in the big form of the template. 3751 */ 3752 public BigPictureStyle setSummaryText(CharSequence cs) { 3753 internalSetSummaryText(safeCharSequence(cs)); 3754 return this; 3755 } 3756 3757 /** 3758 * Provide the bitmap to be used as the payload for the BigPicture notification. 3759 */ 3760 public BigPictureStyle bigPicture(Bitmap b) { 3761 mPicture = b; 3762 return this; 3763 } 3764 3765 /** 3766 * Override the large icon when the big notification is shown. 3767 */ 3768 public BigPictureStyle bigLargeIcon(Bitmap b) { 3769 mBigLargeIconSet = true; 3770 mBigLargeIcon = b; 3771 return this; 3772 } 3773 3774 private RemoteViews makeBigContentView() { 3775 3776 // Replace mLargeIcon with mBigLargeIcon if mBigLargeIconSet 3777 // This covers the following cases: 3778 // 1. mBigLargeIconSet -> mBigLargeIcon (null or non-null) applies, overrides 3779 // mLargeIcon 3780 // 2. !mBigLargeIconSet -> mLargeIcon applies 3781 Bitmap oldLargeIcon = null; 3782 if (mBigLargeIconSet) { 3783 oldLargeIcon = mBuilder.mLargeIcon; 3784 mBuilder.mLargeIcon = mBigLargeIcon; 3785 } 3786 3787 RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource()); 3788 3789 if (mBigLargeIconSet) { 3790 mBuilder.mLargeIcon = oldLargeIcon; 3791 } 3792 3793 contentView.setImageViewBitmap(R.id.big_picture, mPicture); 3794 3795 applyTopPadding(contentView); 3796 3797 boolean twoTextLines = mBuilder.mSubText != null && mBuilder.mContentText != null; 3798 mBuilder.addProfileBadge(contentView, 3799 twoTextLines ? R.id.profile_badge_line2 : R.id.profile_badge_line3); 3800 return contentView; 3801 } 3802 3803 /** 3804 * @hide 3805 */ 3806 public void addExtras(Bundle extras) { 3807 super.addExtras(extras); 3808 3809 if (mBigLargeIconSet) { 3810 extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon); 3811 } 3812 extras.putParcelable(EXTRA_PICTURE, mPicture); 3813 } 3814 3815 /** 3816 * @hide 3817 */ 3818 @Override 3819 protected void restoreFromExtras(Bundle extras) { 3820 super.restoreFromExtras(extras); 3821 3822 if (extras.containsKey(EXTRA_LARGE_ICON_BIG)) { 3823 mBigLargeIconSet = true; 3824 mBigLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON_BIG); 3825 } 3826 mPicture = extras.getParcelable(EXTRA_PICTURE); 3827 } 3828 3829 /** 3830 * @hide 3831 */ 3832 @Override 3833 public void populateBigContentView(Notification wip) { 3834 mBuilder.setBuilderBigContentView(wip, makeBigContentView()); 3835 } 3836 } 3837 3838 /** 3839 * Helper class for generating large-format notifications that include a lot of text. 3840 * 3841 * Here's how you'd set the <code>BigTextStyle</code> on a notification: 3842 * <pre class="prettyprint"> 3843 * Notification notif = new Notification.Builder(mContext) 3844 * .setContentTitle("New mail from " + sender.toString()) 3845 * .setContentText(subject) 3846 * .setSmallIcon(R.drawable.new_mail) 3847 * .setLargeIcon(aBitmap) 3848 * .setStyle(new Notification.BigTextStyle() 3849 * .bigText(aVeryLongString)) 3850 * .build(); 3851 * </pre> 3852 * 3853 * @see Notification#bigContentView 3854 */ 3855 public static class BigTextStyle extends Style { 3856 3857 private static final int MAX_LINES = 13; 3858 private static final int LINES_CONSUMED_BY_ACTIONS = 3; 3859 private static final int LINES_CONSUMED_BY_SUMMARY = 2; 3860 3861 private CharSequence mBigText; 3862 3863 public BigTextStyle() { 3864 } 3865 3866 public BigTextStyle(Builder builder) { 3867 setBuilder(builder); 3868 } 3869 3870 /** 3871 * Overrides ContentTitle in the big form of the template. 3872 * This defaults to the value passed to setContentTitle(). 3873 */ 3874 public BigTextStyle setBigContentTitle(CharSequence title) { 3875 internalSetBigContentTitle(safeCharSequence(title)); 3876 return this; 3877 } 3878 3879 /** 3880 * Set the first line of text after the detail section in the big form of the template. 3881 */ 3882 public BigTextStyle setSummaryText(CharSequence cs) { 3883 internalSetSummaryText(safeCharSequence(cs)); 3884 return this; 3885 } 3886 3887 /** 3888 * Provide the longer text to be displayed in the big form of the 3889 * template in place of the content text. 3890 */ 3891 public BigTextStyle bigText(CharSequence cs) { 3892 mBigText = safeCharSequence(cs); 3893 return this; 3894 } 3895 3896 /** 3897 * @hide 3898 */ 3899 public void addExtras(Bundle extras) { 3900 super.addExtras(extras); 3901 3902 extras.putCharSequence(EXTRA_BIG_TEXT, mBigText); 3903 } 3904 3905 /** 3906 * @hide 3907 */ 3908 @Override 3909 protected void restoreFromExtras(Bundle extras) { 3910 super.restoreFromExtras(extras); 3911 3912 mBigText = extras.getCharSequence(EXTRA_BIG_TEXT); 3913 } 3914 3915 private RemoteViews makeBigContentView() { 3916 3917 // Nasty 3918 CharSequence oldBuilderContentText = mBuilder.mContentText; 3919 mBuilder.mContentText = null; 3920 3921 RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource()); 3922 3923 mBuilder.mContentText = oldBuilderContentText; 3924 3925 contentView.setTextViewText(R.id.big_text, mBuilder.processLegacyText(mBigText)); 3926 contentView.setViewVisibility(R.id.big_text, View.VISIBLE); 3927 contentView.setInt(R.id.big_text, "setMaxLines", calculateMaxLines()); 3928 contentView.setViewVisibility(R.id.text2, View.GONE); 3929 3930 applyTopPadding(contentView); 3931 3932 mBuilder.shrinkLine3Text(contentView); 3933 3934 mBuilder.addProfileBadge(contentView, R.id.profile_badge_large_template); 3935 3936 return contentView; 3937 } 3938 3939 private int calculateMaxLines() { 3940 int lineCount = MAX_LINES; 3941 boolean hasActions = mBuilder.mActions.size() > 0; 3942 boolean hasSummary = (mSummaryTextSet ? mSummaryText : mBuilder.mSubText) != null; 3943 if (hasActions) { 3944 lineCount -= LINES_CONSUMED_BY_ACTIONS; 3945 } 3946 if (hasSummary) { 3947 lineCount -= LINES_CONSUMED_BY_SUMMARY; 3948 } 3949 3950 // If we have less top padding at the top, we can fit less lines. 3951 if (!mBuilder.mHasThreeLines) { 3952 lineCount--; 3953 } 3954 return lineCount; 3955 } 3956 3957 /** 3958 * @hide 3959 */ 3960 @Override 3961 public void populateBigContentView(Notification wip) { 3962 mBuilder.setBuilderBigContentView(wip, makeBigContentView()); 3963 } 3964 } 3965 3966 /** 3967 * Helper class for generating large-format notifications that include a list of (up to 5) strings. 3968 * 3969 * Here's how you'd set the <code>InboxStyle</code> on a notification: 3970 * <pre class="prettyprint"> 3971 * Notification notif = new Notification.Builder(mContext) 3972 * .setContentTitle("5 New mails from " + sender.toString()) 3973 * .setContentText(subject) 3974 * .setSmallIcon(R.drawable.new_mail) 3975 * .setLargeIcon(aBitmap) 3976 * .setStyle(new Notification.InboxStyle() 3977 * .addLine(str1) 3978 * .addLine(str2) 3979 * .setContentTitle("") 3980 * .setSummaryText("+3 more")) 3981 * .build(); 3982 * </pre> 3983 * 3984 * @see Notification#bigContentView 3985 */ 3986 public static class InboxStyle extends Style { 3987 private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5); 3988 3989 public InboxStyle() { 3990 } 3991 3992 public InboxStyle(Builder builder) { 3993 setBuilder(builder); 3994 } 3995 3996 /** 3997 * Overrides ContentTitle in the big form of the template. 3998 * This defaults to the value passed to setContentTitle(). 3999 */ 4000 public InboxStyle setBigContentTitle(CharSequence title) { 4001 internalSetBigContentTitle(safeCharSequence(title)); 4002 return this; 4003 } 4004 4005 /** 4006 * Set the first line of text after the detail section in the big form of the template. 4007 */ 4008 public InboxStyle setSummaryText(CharSequence cs) { 4009 internalSetSummaryText(safeCharSequence(cs)); 4010 return this; 4011 } 4012 4013 /** 4014 * Append a line to the digest section of the Inbox notification. 4015 */ 4016 public InboxStyle addLine(CharSequence cs) { 4017 mTexts.add(safeCharSequence(cs)); 4018 return this; 4019 } 4020 4021 /** 4022 * @hide 4023 */ 4024 public void addExtras(Bundle extras) { 4025 super.addExtras(extras); 4026 4027 CharSequence[] a = new CharSequence[mTexts.size()]; 4028 extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a)); 4029 } 4030 4031 /** 4032 * @hide 4033 */ 4034 @Override 4035 protected void restoreFromExtras(Bundle extras) { 4036 super.restoreFromExtras(extras); 4037 4038 mTexts.clear(); 4039 if (extras.containsKey(EXTRA_TEXT_LINES)) { 4040 Collections.addAll(mTexts, extras.getCharSequenceArray(EXTRA_TEXT_LINES)); 4041 } 4042 } 4043 4044 private RemoteViews makeBigContentView() { 4045 // Remove the content text so line3 disappears unless you have a summary 4046 4047 // Nasty 4048 CharSequence oldBuilderContentText = mBuilder.mContentText; 4049 mBuilder.mContentText = null; 4050 4051 RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource()); 4052 4053 mBuilder.mContentText = oldBuilderContentText; 4054 4055 contentView.setViewVisibility(R.id.text2, View.GONE); 4056 4057 int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3, 4058 R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6}; 4059 4060 // Make sure all rows are gone in case we reuse a view. 4061 for (int rowId : rowIds) { 4062 contentView.setViewVisibility(rowId, View.GONE); 4063 } 4064 4065 final boolean largeText = 4066 mBuilder.mContext.getResources().getConfiguration().fontScale > 1f; 4067 final float subTextSize = mBuilder.mContext.getResources().getDimensionPixelSize( 4068 R.dimen.notification_subtext_size); 4069 int i=0; 4070 while (i < mTexts.size() && i < rowIds.length) { 4071 CharSequence str = mTexts.get(i); 4072 if (str != null && !str.equals("")) { 4073 contentView.setViewVisibility(rowIds[i], View.VISIBLE); 4074 contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str)); 4075 if (largeText) { 4076 contentView.setTextViewTextSize(rowIds[i], TypedValue.COMPLEX_UNIT_PX, 4077 subTextSize); 4078 } 4079 } 4080 i++; 4081 } 4082 4083 contentView.setViewVisibility(R.id.inbox_end_pad, 4084 mTexts.size() > 0 ? View.VISIBLE : View.GONE); 4085 4086 contentView.setViewVisibility(R.id.inbox_more, 4087 mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE); 4088 4089 applyTopPadding(contentView); 4090 4091 mBuilder.shrinkLine3Text(contentView); 4092 4093 mBuilder.addProfileBadge(contentView, R.id.profile_badge_large_template); 4094 4095 return contentView; 4096 } 4097 4098 /** 4099 * @hide 4100 */ 4101 @Override 4102 public void populateBigContentView(Notification wip) { 4103 mBuilder.setBuilderBigContentView(wip, makeBigContentView()); 4104 } 4105 } 4106 4107 /** 4108 * Notification style for media playback notifications. 4109 * 4110 * In the expanded form, {@link Notification#bigContentView}, up to 5 4111 * {@link Notification.Action}s specified with 4112 * {@link Notification.Builder#addAction(int, CharSequence, PendingIntent) addAction} will be 4113 * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to 4114 * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be 4115 * treated as album artwork. 4116 * 4117 * Unlike the other styles provided here, MediaStyle can also modify the standard-size 4118 * {@link Notification#contentView}; by providing action indices to 4119 * {@link #setShowActionsInCompactView(int...)} you can promote up to 3 actions to be displayed 4120 * in the standard view alongside the usual content. 4121 * 4122 * Notifications created with MediaStyle will have their category set to 4123 * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different 4124 * category using {@link Notification.Builder#setCategory(String) setCategory()}. 4125 * 4126 * Finally, if you attach a {@link android.media.session.MediaSession.Token} using 4127 * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)}, 4128 * the System UI can identify this as a notification representing an active media session 4129 * and respond accordingly (by showing album artwork in the lockscreen, for example). 4130 * 4131 * To use this style with your Notification, feed it to 4132 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so: 4133 * <pre class="prettyprint"> 4134 * Notification noti = new Notification.Builder() 4135 * .setSmallIcon(R.drawable.ic_stat_player) 4136 * .setContentTitle("Track title") 4137 * .setContentText("Artist - Album") 4138 * .setLargeIcon(albumArtBitmap)) 4139 * .setStyle(<b>new Notification.MediaStyle()</b> 4140 * .setMediaSession(mySession)) 4141 * .build(); 4142 * </pre> 4143 * 4144 * @see Notification#bigContentView 4145 */ 4146 public static class MediaStyle extends Style { 4147 static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3; 4148 static final int MAX_MEDIA_BUTTONS = 5; 4149 4150 private int[] mActionsToShowInCompact = null; 4151 private MediaSession.Token mToken; 4152 4153 public MediaStyle() { 4154 } 4155 4156 public MediaStyle(Builder builder) { 4157 setBuilder(builder); 4158 } 4159 4160 /** 4161 * Request up to 3 actions (by index in the order of addition) to be shown in the compact 4162 * notification view. 4163 * 4164 * @param actions the indices of the actions to show in the compact notification view 4165 */ 4166 public MediaStyle setShowActionsInCompactView(int...actions) { 4167 mActionsToShowInCompact = actions; 4168 return this; 4169 } 4170 4171 /** 4172 * Attach a {@link android.media.session.MediaSession.Token} to this Notification 4173 * to provide additional playback information and control to the SystemUI. 4174 */ 4175 public MediaStyle setMediaSession(MediaSession.Token token) { 4176 mToken = token; 4177 return this; 4178 } 4179 4180 /** 4181 * @hide 4182 */ 4183 @Override 4184 public Notification buildStyled(Notification wip) { 4185 super.buildStyled(wip); 4186 if (wip.category == null) { 4187 wip.category = Notification.CATEGORY_TRANSPORT; 4188 } 4189 return wip; 4190 } 4191 4192 /** 4193 * @hide 4194 */ 4195 @Override 4196 public void populateContentView(Notification wip) { 4197 mBuilder.setBuilderContentView(wip, makeMediaContentView()); 4198 } 4199 4200 /** 4201 * @hide 4202 */ 4203 @Override 4204 public void populateBigContentView(Notification wip) { 4205 mBuilder.setBuilderBigContentView(wip, makeMediaBigContentView()); 4206 } 4207 4208 /** @hide */ 4209 @Override 4210 public void addExtras(Bundle extras) { 4211 super.addExtras(extras); 4212 4213 if (mToken != null) { 4214 extras.putParcelable(EXTRA_MEDIA_SESSION, mToken); 4215 } 4216 if (mActionsToShowInCompact != null) { 4217 extras.putIntArray(EXTRA_COMPACT_ACTIONS, mActionsToShowInCompact); 4218 } 4219 } 4220 4221 /** 4222 * @hide 4223 */ 4224 @Override 4225 protected void restoreFromExtras(Bundle extras) { 4226 super.restoreFromExtras(extras); 4227 4228 if (extras.containsKey(EXTRA_MEDIA_SESSION)) { 4229 mToken = extras.getParcelable(EXTRA_MEDIA_SESSION); 4230 } 4231 if (extras.containsKey(EXTRA_COMPACT_ACTIONS)) { 4232 mActionsToShowInCompact = extras.getIntArray(EXTRA_COMPACT_ACTIONS); 4233 } 4234 } 4235 4236 private RemoteViews generateMediaActionButton(Action action) { 4237 final boolean tombstone = (action.actionIntent == null); 4238 RemoteViews button = new RemoteViews(mBuilder.mContext.getPackageName(), 4239 R.layout.notification_material_media_action); 4240 button.setImageViewResource(R.id.action0, action.icon); 4241 button.setDrawableParameters(R.id.action0, false, -1, 4242 0xFFFFFFFF, 4243 PorterDuff.Mode.SRC_ATOP, -1); 4244 if (!tombstone) { 4245 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 4246 } 4247 button.setContentDescription(R.id.action0, action.title); 4248 return button; 4249 } 4250 4251 private RemoteViews makeMediaContentView() { 4252 RemoteViews view = mBuilder.applyStandardTemplate( 4253 R.layout.notification_template_material_media, false /* hasProgress */); 4254 4255 final int numActions = mBuilder.mActions.size(); 4256 final int N = mActionsToShowInCompact == null 4257 ? 0 4258 : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT); 4259 if (N > 0) { 4260 view.removeAllViews(com.android.internal.R.id.media_actions); 4261 for (int i = 0; i < N; i++) { 4262 if (i >= numActions) { 4263 throw new IllegalArgumentException(String.format( 4264 "setShowActionsInCompactView: action %d out of bounds (max %d)", 4265 i, numActions - 1)); 4266 } 4267 4268 final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]); 4269 final RemoteViews button = generateMediaActionButton(action); 4270 view.addView(com.android.internal.R.id.media_actions, button); 4271 } 4272 } 4273 styleText(view); 4274 hideRightIcon(view); 4275 return view; 4276 } 4277 4278 private RemoteViews makeMediaBigContentView() { 4279 final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS); 4280 RemoteViews big = mBuilder.applyStandardTemplate(getBigLayoutResource(actionCount), 4281 false /* hasProgress */); 4282 4283 if (actionCount > 0) { 4284 big.removeAllViews(com.android.internal.R.id.media_actions); 4285 for (int i = 0; i < actionCount; i++) { 4286 final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i)); 4287 big.addView(com.android.internal.R.id.media_actions, button); 4288 } 4289 } 4290 styleText(big); 4291 hideRightIcon(big); 4292 applyTopPadding(big); 4293 big.setViewVisibility(android.R.id.progress, View.GONE); 4294 return big; 4295 } 4296 4297 private int getBigLayoutResource(int actionCount) { 4298 if (actionCount <= 3) { 4299 return R.layout.notification_template_material_big_media_narrow; 4300 } else { 4301 return R.layout.notification_template_material_big_media; 4302 } 4303 } 4304 4305 private void hideRightIcon(RemoteViews contentView) { 4306 contentView.setViewVisibility(R.id.right_icon, View.GONE); 4307 } 4308 4309 /** 4310 * Applies the special text colors for media notifications to all text views. 4311 */ 4312 private void styleText(RemoteViews contentView) { 4313 int primaryColor = mBuilder.mContext.getResources().getColor( 4314 R.color.notification_media_primary_color); 4315 int secondaryColor = mBuilder.mContext.getResources().getColor( 4316 R.color.notification_media_secondary_color); 4317 contentView.setTextColor(R.id.title, primaryColor); 4318 if (mBuilder.showsTimeOrChronometer()) { 4319 if (mBuilder.mUseChronometer) { 4320 contentView.setTextColor(R.id.chronometer, secondaryColor); 4321 } else { 4322 contentView.setTextColor(R.id.time, secondaryColor); 4323 } 4324 } 4325 contentView.setTextColor(R.id.text2, secondaryColor); 4326 contentView.setTextColor(R.id.text, secondaryColor); 4327 contentView.setTextColor(R.id.info, secondaryColor); 4328 } 4329 4330 /** 4331 * @hide 4332 */ 4333 @Override 4334 protected boolean hasProgress() { 4335 return false; 4336 } 4337 } 4338 4339 // When adding a new Style subclass here, don't forget to update 4340 // Builder.getNotificationStyleClass. 4341 4342 /** 4343 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add 4344 * metadata or change options on a notification builder. 4345 */ 4346 public interface Extender { 4347 /** 4348 * Apply this extender to a notification builder. 4349 * @param builder the builder to be modified. 4350 * @return the build object for chaining. 4351 */ 4352 public Builder extend(Builder builder); 4353 } 4354 4355 /** 4356 * Helper class to add wearable extensions to notifications. 4357 * <p class="note"> See 4358 * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications 4359 * for Android Wear</a> for more information on how to use this class. 4360 * <p> 4361 * To create a notification with wearable extensions: 4362 * <ol> 4363 * <li>Create a {@link android.app.Notification.Builder}, setting any desired 4364 * properties. 4365 * <li>Create a {@link android.app.Notification.WearableExtender}. 4366 * <li>Set wearable-specific properties using the 4367 * {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}. 4368 * <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a 4369 * notification. 4370 * <li>Post the notification to the notification system with the 4371 * {@code NotificationManager.notify(...)} methods. 4372 * </ol> 4373 * 4374 * <pre class="prettyprint"> 4375 * Notification notif = new Notification.Builder(mContext) 4376 * .setContentTitle("New mail from " + sender.toString()) 4377 * .setContentText(subject) 4378 * .setSmallIcon(R.drawable.new_mail) 4379 * .extend(new Notification.WearableExtender() 4380 * .setContentIcon(R.drawable.new_mail)) 4381 * .build(); 4382 * NotificationManager notificationManger = 4383 * (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 4384 * notificationManger.notify(0, notif);</pre> 4385 * 4386 * <p>Wearable extensions can be accessed on an existing notification by using the 4387 * {@code WearableExtender(Notification)} constructor, 4388 * and then using the {@code get} methods to access values. 4389 * 4390 * <pre class="prettyprint"> 4391 * Notification.WearableExtender wearableExtender = new Notification.WearableExtender( 4392 * notification); 4393 * List<Notification> pages = wearableExtender.getPages();</pre> 4394 */ 4395 public static final class WearableExtender implements Extender { 4396 /** 4397 * Sentinel value for an action index that is unset. 4398 */ 4399 public static final int UNSET_ACTION_INDEX = -1; 4400 4401 /** 4402 * Size value for use with {@link #setCustomSizePreset} to show this notification with 4403 * default sizing. 4404 * <p>For custom display notifications created using {@link #setDisplayIntent}, 4405 * the default is {@link #SIZE_LARGE}. All other notifications size automatically based 4406 * on their content. 4407 */ 4408 public static final int SIZE_DEFAULT = 0; 4409 4410 /** 4411 * Size value for use with {@link #setCustomSizePreset} to show this notification 4412 * with an extra small size. 4413 * <p>This value is only applicable for custom display notifications created using 4414 * {@link #setDisplayIntent}. 4415 */ 4416 public static final int SIZE_XSMALL = 1; 4417 4418 /** 4419 * Size value for use with {@link #setCustomSizePreset} to show this notification 4420 * with a small size. 4421 * <p>This value is only applicable for custom display notifications created using 4422 * {@link #setDisplayIntent}. 4423 */ 4424 public static final int SIZE_SMALL = 2; 4425 4426 /** 4427 * Size value for use with {@link #setCustomSizePreset} to show this notification 4428 * with a medium size. 4429 * <p>This value is only applicable for custom display notifications created using 4430 * {@link #setDisplayIntent}. 4431 */ 4432 public static final int SIZE_MEDIUM = 3; 4433 4434 /** 4435 * Size value for use with {@link #setCustomSizePreset} to show this notification 4436 * with a large size. 4437 * <p>This value is only applicable for custom display notifications created using 4438 * {@link #setDisplayIntent}. 4439 */ 4440 public static final int SIZE_LARGE = 4; 4441 4442 /** 4443 * Size value for use with {@link #setCustomSizePreset} to show this notification 4444 * full screen. 4445 * <p>This value is only applicable for custom display notifications created using 4446 * {@link #setDisplayIntent}. 4447 */ 4448 public static final int SIZE_FULL_SCREEN = 5; 4449 4450 /** 4451 * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a 4452 * short amount of time when this notification is displayed on the screen. This 4453 * is the default value. 4454 */ 4455 public static final int SCREEN_TIMEOUT_SHORT = 0; 4456 4457 /** 4458 * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on 4459 * for a longer amount of time when this notification is displayed on the screen. 4460 */ 4461 public static final int SCREEN_TIMEOUT_LONG = -1; 4462 4463 /** Notification extra which contains wearable extensions */ 4464 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS"; 4465 4466 // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options. 4467 private static final String KEY_ACTIONS = "actions"; 4468 private static final String KEY_FLAGS = "flags"; 4469 private static final String KEY_DISPLAY_INTENT = "displayIntent"; 4470 private static final String KEY_PAGES = "pages"; 4471 private static final String KEY_BACKGROUND = "background"; 4472 private static final String KEY_CONTENT_ICON = "contentIcon"; 4473 private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity"; 4474 private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex"; 4475 private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset"; 4476 private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight"; 4477 private static final String KEY_GRAVITY = "gravity"; 4478 private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout"; 4479 4480 // Flags bitwise-ored to mFlags 4481 private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1; 4482 private static final int FLAG_HINT_HIDE_ICON = 1 << 1; 4483 private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2; 4484 private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3; 4485 private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4; 4486 4487 // Default value for flags integer 4488 private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE; 4489 4490 private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END; 4491 private static final int DEFAULT_GRAVITY = Gravity.BOTTOM; 4492 4493 private ArrayList<Action> mActions = new ArrayList<Action>(); 4494 private int mFlags = DEFAULT_FLAGS; 4495 private PendingIntent mDisplayIntent; 4496 private ArrayList<Notification> mPages = new ArrayList<Notification>(); 4497 private Bitmap mBackground; 4498 private int mContentIcon; 4499 private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY; 4500 private int mContentActionIndex = UNSET_ACTION_INDEX; 4501 private int mCustomSizePreset = SIZE_DEFAULT; 4502 private int mCustomContentHeight; 4503 private int mGravity = DEFAULT_GRAVITY; 4504 private int mHintScreenTimeout; 4505 4506 /** 4507 * Create a {@link android.app.Notification.WearableExtender} with default 4508 * options. 4509 */ 4510 public WearableExtender() { 4511 } 4512 4513 public WearableExtender(Notification notif) { 4514 Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS); 4515 if (wearableBundle != null) { 4516 List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS); 4517 if (actions != null) { 4518 mActions.addAll(actions); 4519 } 4520 4521 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS); 4522 mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT); 4523 4524 Notification[] pages = getNotificationArrayFromBundle( 4525 wearableBundle, KEY_PAGES); 4526 if (pages != null) { 4527 Collections.addAll(mPages, pages); 4528 } 4529 4530 mBackground = wearableBundle.getParcelable(KEY_BACKGROUND); 4531 mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON); 4532 mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY, 4533 DEFAULT_CONTENT_ICON_GRAVITY); 4534 mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX, 4535 UNSET_ACTION_INDEX); 4536 mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET, 4537 SIZE_DEFAULT); 4538 mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT); 4539 mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY); 4540 mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT); 4541 } 4542 } 4543 4544 /** 4545 * Apply wearable extensions to a notification that is being built. This is typically 4546 * called by the {@link android.app.Notification.Builder#extend} method of 4547 * {@link android.app.Notification.Builder}. 4548 */ 4549 @Override 4550 public Notification.Builder extend(Notification.Builder builder) { 4551 Bundle wearableBundle = new Bundle(); 4552 4553 if (!mActions.isEmpty()) { 4554 wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions); 4555 } 4556 if (mFlags != DEFAULT_FLAGS) { 4557 wearableBundle.putInt(KEY_FLAGS, mFlags); 4558 } 4559 if (mDisplayIntent != null) { 4560 wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent); 4561 } 4562 if (!mPages.isEmpty()) { 4563 wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray( 4564 new Notification[mPages.size()])); 4565 } 4566 if (mBackground != null) { 4567 wearableBundle.putParcelable(KEY_BACKGROUND, mBackground); 4568 } 4569 if (mContentIcon != 0) { 4570 wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon); 4571 } 4572 if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) { 4573 wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity); 4574 } 4575 if (mContentActionIndex != UNSET_ACTION_INDEX) { 4576 wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX, 4577 mContentActionIndex); 4578 } 4579 if (mCustomSizePreset != SIZE_DEFAULT) { 4580 wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset); 4581 } 4582 if (mCustomContentHeight != 0) { 4583 wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight); 4584 } 4585 if (mGravity != DEFAULT_GRAVITY) { 4586 wearableBundle.putInt(KEY_GRAVITY, mGravity); 4587 } 4588 if (mHintScreenTimeout != 0) { 4589 wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout); 4590 } 4591 4592 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle); 4593 return builder; 4594 } 4595 4596 @Override 4597 public WearableExtender clone() { 4598 WearableExtender that = new WearableExtender(); 4599 that.mActions = new ArrayList<Action>(this.mActions); 4600 that.mFlags = this.mFlags; 4601 that.mDisplayIntent = this.mDisplayIntent; 4602 that.mPages = new ArrayList<Notification>(this.mPages); 4603 that.mBackground = this.mBackground; 4604 that.mContentIcon = this.mContentIcon; 4605 that.mContentIconGravity = this.mContentIconGravity; 4606 that.mContentActionIndex = this.mContentActionIndex; 4607 that.mCustomSizePreset = this.mCustomSizePreset; 4608 that.mCustomContentHeight = this.mCustomContentHeight; 4609 that.mGravity = this.mGravity; 4610 that.mHintScreenTimeout = this.mHintScreenTimeout; 4611 return that; 4612 } 4613 4614 /** 4615 * Add a wearable action to this notification. 4616 * 4617 * <p>When wearable actions are added using this method, the set of actions that 4618 * show on a wearable device splits from devices that only show actions added 4619 * using {@link android.app.Notification.Builder#addAction}. This allows for customization 4620 * of which actions display on different devices. 4621 * 4622 * @param action the action to add to this notification 4623 * @return this object for method chaining 4624 * @see android.app.Notification.Action 4625 */ 4626 public WearableExtender addAction(Action action) { 4627 mActions.add(action); 4628 return this; 4629 } 4630 4631 /** 4632 * Adds wearable actions to this notification. 4633 * 4634 * <p>When wearable actions are added using this method, the set of actions that 4635 * show on a wearable device splits from devices that only show actions added 4636 * using {@link android.app.Notification.Builder#addAction}. This allows for customization 4637 * of which actions display on different devices. 4638 * 4639 * @param actions the actions to add to this notification 4640 * @return this object for method chaining 4641 * @see android.app.Notification.Action 4642 */ 4643 public WearableExtender addActions(List<Action> actions) { 4644 mActions.addAll(actions); 4645 return this; 4646 } 4647 4648 /** 4649 * Clear all wearable actions present on this builder. 4650 * @return this object for method chaining. 4651 * @see #addAction 4652 */ 4653 public WearableExtender clearActions() { 4654 mActions.clear(); 4655 return this; 4656 } 4657 4658 /** 4659 * Get the wearable actions present on this notification. 4660 */ 4661 public List<Action> getActions() { 4662 return mActions; 4663 } 4664 4665 /** 4666 * Set an intent to launch inside of an activity view when displaying 4667 * this notification. The {@link PendingIntent} provided should be for an activity. 4668 * 4669 * <pre class="prettyprint"> 4670 * Intent displayIntent = new Intent(context, MyDisplayActivity.class); 4671 * PendingIntent displayPendingIntent = PendingIntent.getActivity(context, 4672 * 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT); 4673 * Notification notif = new Notification.Builder(context) 4674 * .extend(new Notification.WearableExtender() 4675 * .setDisplayIntent(displayPendingIntent) 4676 * .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM)) 4677 * .build();</pre> 4678 * 4679 * <p>The activity to launch needs to allow embedding, must be exported, and 4680 * should have an empty task affinity. It is also recommended to use the device 4681 * default light theme. 4682 * 4683 * <p>Example AndroidManifest.xml entry: 4684 * <pre class="prettyprint"> 4685 * <activity android:name="com.example.MyDisplayActivity" 4686 * android:exported="true" 4687 * android:allowEmbedded="true" 4688 * android:taskAffinity="" 4689 * android:theme="@android:style/Theme.DeviceDefault.Light" /></pre> 4690 * 4691 * @param intent the {@link PendingIntent} for an activity 4692 * @return this object for method chaining 4693 * @see android.app.Notification.WearableExtender#getDisplayIntent 4694 */ 4695 public WearableExtender setDisplayIntent(PendingIntent intent) { 4696 mDisplayIntent = intent; 4697 return this; 4698 } 4699 4700 /** 4701 * Get the intent to launch inside of an activity view when displaying this 4702 * notification. This {@code PendingIntent} should be for an activity. 4703 */ 4704 public PendingIntent getDisplayIntent() { 4705 return mDisplayIntent; 4706 } 4707 4708 /** 4709 * Add an additional page of content to display with this notification. The current 4710 * notification forms the first page, and pages added using this function form 4711 * subsequent pages. This field can be used to separate a notification into multiple 4712 * sections. 4713 * 4714 * @param page the notification to add as another page 4715 * @return this object for method chaining 4716 * @see android.app.Notification.WearableExtender#getPages 4717 */ 4718 public WearableExtender addPage(Notification page) { 4719 mPages.add(page); 4720 return this; 4721 } 4722 4723 /** 4724 * Add additional pages of content to display with this notification. The current 4725 * notification forms the first page, and pages added using this function form 4726 * subsequent pages. This field can be used to separate a notification into multiple 4727 * sections. 4728 * 4729 * @param pages a list of notifications 4730 * @return this object for method chaining 4731 * @see android.app.Notification.WearableExtender#getPages 4732 */ 4733 public WearableExtender addPages(List<Notification> pages) { 4734 mPages.addAll(pages); 4735 return this; 4736 } 4737 4738 /** 4739 * Clear all additional pages present on this builder. 4740 * @return this object for method chaining. 4741 * @see #addPage 4742 */ 4743 public WearableExtender clearPages() { 4744 mPages.clear(); 4745 return this; 4746 } 4747 4748 /** 4749 * Get the array of additional pages of content for displaying this notification. The 4750 * current notification forms the first page, and elements within this array form 4751 * subsequent pages. This field can be used to separate a notification into multiple 4752 * sections. 4753 * @return the pages for this notification 4754 */ 4755 public List<Notification> getPages() { 4756 return mPages; 4757 } 4758 4759 /** 4760 * Set a background image to be displayed behind the notification content. 4761 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background 4762 * will work with any notification style. 4763 * 4764 * @param background the background bitmap 4765 * @return this object for method chaining 4766 * @see android.app.Notification.WearableExtender#getBackground 4767 */ 4768 public WearableExtender setBackground(Bitmap background) { 4769 mBackground = background; 4770 return this; 4771 } 4772 4773 /** 4774 * Get a background image to be displayed behind the notification content. 4775 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background 4776 * will work with any notification style. 4777 * 4778 * @return the background image 4779 * @see android.app.Notification.WearableExtender#setBackground 4780 */ 4781 public Bitmap getBackground() { 4782 return mBackground; 4783 } 4784 4785 /** 4786 * Set an icon that goes with the content of this notification. 4787 */ 4788 public WearableExtender setContentIcon(int icon) { 4789 mContentIcon = icon; 4790 return this; 4791 } 4792 4793 /** 4794 * Get an icon that goes with the content of this notification. 4795 */ 4796 public int getContentIcon() { 4797 return mContentIcon; 4798 } 4799 4800 /** 4801 * Set the gravity that the content icon should have within the notification display. 4802 * Supported values include {@link android.view.Gravity#START} and 4803 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}. 4804 * @see #setContentIcon 4805 */ 4806 public WearableExtender setContentIconGravity(int contentIconGravity) { 4807 mContentIconGravity = contentIconGravity; 4808 return this; 4809 } 4810 4811 /** 4812 * Get the gravity that the content icon should have within the notification display. 4813 * Supported values include {@link android.view.Gravity#START} and 4814 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}. 4815 * @see #getContentIcon 4816 */ 4817 public int getContentIconGravity() { 4818 return mContentIconGravity; 4819 } 4820 4821 /** 4822 * Set an action from this notification's actions to be clickable with the content of 4823 * this notification. This action will no longer display separately from the 4824 * notification's content. 4825 * 4826 * <p>For notifications with multiple pages, child pages can also have content actions 4827 * set, although the list of available actions comes from the main notification and not 4828 * from the child page's notification. 4829 * 4830 * @param actionIndex The index of the action to hoist onto the current notification page. 4831 * If wearable actions were added to the main notification, this index 4832 * will apply to that list, otherwise it will apply to the regular 4833 * actions list. 4834 */ 4835 public WearableExtender setContentAction(int actionIndex) { 4836 mContentActionIndex = actionIndex; 4837 return this; 4838 } 4839 4840 /** 4841 * Get the index of the notification action, if any, that was specified as being clickable 4842 * with the content of this notification. This action will no longer display separately 4843 * from the notification's content. 4844 * 4845 * <p>For notifications with multiple pages, child pages can also have content actions 4846 * set, although the list of available actions comes from the main notification and not 4847 * from the child page's notification. 4848 * 4849 * <p>If wearable specific actions were added to the main notification, this index will 4850 * apply to that list, otherwise it will apply to the regular actions list. 4851 * 4852 * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected. 4853 */ 4854 public int getContentAction() { 4855 return mContentActionIndex; 4856 } 4857 4858 /** 4859 * Set the gravity that this notification should have within the available viewport space. 4860 * Supported values include {@link android.view.Gravity#TOP}, 4861 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}. 4862 * The default value is {@link android.view.Gravity#BOTTOM}. 4863 */ 4864 public WearableExtender setGravity(int gravity) { 4865 mGravity = gravity; 4866 return this; 4867 } 4868 4869 /** 4870 * Get the gravity that this notification should have within the available viewport space. 4871 * Supported values include {@link android.view.Gravity#TOP}, 4872 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}. 4873 * The default value is {@link android.view.Gravity#BOTTOM}. 4874 */ 4875 public int getGravity() { 4876 return mGravity; 4877 } 4878 4879 /** 4880 * Set the custom size preset for the display of this notification out of the available 4881 * presets found in {@link android.app.Notification.WearableExtender}, e.g. 4882 * {@link #SIZE_LARGE}. 4883 * <p>Some custom size presets are only applicable for custom display notifications created 4884 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the 4885 * documentation for the preset in question. See also 4886 * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}. 4887 */ 4888 public WearableExtender setCustomSizePreset(int sizePreset) { 4889 mCustomSizePreset = sizePreset; 4890 return this; 4891 } 4892 4893 /** 4894 * Get the custom size preset for the display of this notification out of the available 4895 * presets found in {@link android.app.Notification.WearableExtender}, e.g. 4896 * {@link #SIZE_LARGE}. 4897 * <p>Some custom size presets are only applicable for custom display notifications created 4898 * using {@link #setDisplayIntent}. Check the documentation for the preset in question. 4899 * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}. 4900 */ 4901 public int getCustomSizePreset() { 4902 return mCustomSizePreset; 4903 } 4904 4905 /** 4906 * Set the custom height in pixels for the display of this notification's content. 4907 * <p>This option is only available for custom display notifications created 4908 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also 4909 * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and 4910 * {@link #getCustomContentHeight}. 4911 */ 4912 public WearableExtender setCustomContentHeight(int height) { 4913 mCustomContentHeight = height; 4914 return this; 4915 } 4916 4917 /** 4918 * Get the custom height in pixels for the display of this notification's content. 4919 * <p>This option is only available for custom display notifications created 4920 * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and 4921 * {@link #setCustomContentHeight}. 4922 */ 4923 public int getCustomContentHeight() { 4924 return mCustomContentHeight; 4925 } 4926 4927 /** 4928 * Set whether the scrolling position for the contents of this notification should start 4929 * at the bottom of the contents instead of the top when the contents are too long to 4930 * display within the screen. Default is false (start scroll at the top). 4931 */ 4932 public WearableExtender setStartScrollBottom(boolean startScrollBottom) { 4933 setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom); 4934 return this; 4935 } 4936 4937 /** 4938 * Get whether the scrolling position for the contents of this notification should start 4939 * at the bottom of the contents instead of the top when the contents are too long to 4940 * display within the screen. Default is false (start scroll at the top). 4941 */ 4942 public boolean getStartScrollBottom() { 4943 return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0; 4944 } 4945 4946 /** 4947 * Set whether the content intent is available when the wearable device is not connected 4948 * to a companion device. The user can still trigger this intent when the wearable device 4949 * is offline, but a visual hint will indicate that the content intent may not be available. 4950 * Defaults to true. 4951 */ 4952 public WearableExtender setContentIntentAvailableOffline( 4953 boolean contentIntentAvailableOffline) { 4954 setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline); 4955 return this; 4956 } 4957 4958 /** 4959 * Get whether the content intent is available when the wearable device is not connected 4960 * to a companion device. The user can still trigger this intent when the wearable device 4961 * is offline, but a visual hint will indicate that the content intent may not be available. 4962 * Defaults to true. 4963 */ 4964 public boolean getContentIntentAvailableOffline() { 4965 return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0; 4966 } 4967 4968 /** 4969 * Set a hint that this notification's icon should not be displayed. 4970 * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise. 4971 * @return this object for method chaining 4972 */ 4973 public WearableExtender setHintHideIcon(boolean hintHideIcon) { 4974 setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon); 4975 return this; 4976 } 4977 4978 /** 4979 * Get a hint that this notification's icon should not be displayed. 4980 * @return {@code true} if this icon should not be displayed, false otherwise. 4981 * The default value is {@code false} if this was never set. 4982 */ 4983 public boolean getHintHideIcon() { 4984 return (mFlags & FLAG_HINT_HIDE_ICON) != 0; 4985 } 4986 4987 /** 4988 * Set a visual hint that only the background image of this notification should be 4989 * displayed, and other semantic content should be hidden. This hint is only applicable 4990 * to sub-pages added using {@link #addPage}. 4991 */ 4992 public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) { 4993 setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly); 4994 return this; 4995 } 4996 4997 /** 4998 * Get a visual hint that only the background image of this notification should be 4999 * displayed, and other semantic content should be hidden. This hint is only applicable 5000 * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}. 5001 */ 5002 public boolean getHintShowBackgroundOnly() { 5003 return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0; 5004 } 5005 5006 /** 5007 * Set a hint that this notification's background should not be clipped if possible, 5008 * and should instead be resized to fully display on the screen, retaining the aspect 5009 * ratio of the image. This can be useful for images like barcodes or qr codes. 5010 * @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible. 5011 * @return this object for method chaining 5012 */ 5013 public WearableExtender setHintAvoidBackgroundClipping( 5014 boolean hintAvoidBackgroundClipping) { 5015 setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping); 5016 return this; 5017 } 5018 5019 /** 5020 * Get a hint that this notification's background should not be clipped if possible, 5021 * and should instead be resized to fully display on the screen, retaining the aspect 5022 * ratio of the image. This can be useful for images like barcodes or qr codes. 5023 * @return {@code true} if it's ok if the background is clipped on the screen, false 5024 * otherwise. The default value is {@code false} if this was never set. 5025 */ 5026 public boolean getHintAvoidBackgroundClipping() { 5027 return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0; 5028 } 5029 5030 /** 5031 * Set a hint that the screen should remain on for at least this duration when 5032 * this notification is displayed on the screen. 5033 * @param timeout The requested screen timeout in milliseconds. Can also be either 5034 * {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}. 5035 * @return this object for method chaining 5036 */ 5037 public WearableExtender setHintScreenTimeout(int timeout) { 5038 mHintScreenTimeout = timeout; 5039 return this; 5040 } 5041 5042 /** 5043 * Get the duration, in milliseconds, that the screen should remain on for 5044 * when this notification is displayed. 5045 * @return the duration in milliseconds if > 0, or either one of the sentinel values 5046 * {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}. 5047 */ 5048 public int getHintScreenTimeout() { 5049 return mHintScreenTimeout; 5050 } 5051 5052 private void setFlag(int mask, boolean value) { 5053 if (value) { 5054 mFlags |= mask; 5055 } else { 5056 mFlags &= ~mask; 5057 } 5058 } 5059 } 5060 5061 /** 5062 * Get an array of Notification objects from a parcelable array bundle field. 5063 * Update the bundle to have a typed array so fetches in the future don't need 5064 * to do an array copy. 5065 */ 5066 private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) { 5067 Parcelable[] array = bundle.getParcelableArray(key); 5068 if (array instanceof Notification[] || array == null) { 5069 return (Notification[]) array; 5070 } 5071 Notification[] typedArray = Arrays.copyOf(array, array.length, 5072 Notification[].class); 5073 bundle.putParcelableArray(key, typedArray); 5074 return typedArray; 5075 } 5076 5077 private static class BuilderRemoteViews extends RemoteViews { 5078 public BuilderRemoteViews(Parcel parcel) { 5079 super(parcel); 5080 } 5081 5082 public BuilderRemoteViews(ApplicationInfo appInfo, int layoutId) { 5083 super(appInfo, layoutId); 5084 } 5085 5086 @Override 5087 public BuilderRemoteViews clone() { 5088 Parcel p = Parcel.obtain(); 5089 writeToParcel(p, 0); 5090 p.setDataPosition(0); 5091 BuilderRemoteViews brv = new BuilderRemoteViews(p); 5092 p.recycle(); 5093 return brv; 5094 } 5095 } 5096} 5097